import React, { Component } from "react";
import { Input, Button, DatePicker, Modal, Breadcrumb, Tabs, Popover } from "antd";
import { Link } from "dva/router";
import moment from "moment";
import axios from 'axios';
import store from 'store';
import * as api from '../../../services/api';
import "./less/ResignationList.less";
import PTable from "../../../components/Pro/PTable";

const { confirm } = Modal;
const { RangePicker } = DatePicker;
const dateFormat = "YYYY-MM-DD";
const { TabPane } = Tabs;
export default class District extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      forceUpdate: false,
      pageParm: {
        pageSize: "10",
        pageNumber: "1",
        keyword: "",
        startLeaveDate: "", //离职开始日期
        endLeaveDate: "" //离职开始日期
      },
      keyword: "",
      startTime: null,
      endTime: null,
      start: false,
      end: false,
      total: 0
    };
  }

  //时间选择
  onChangeTime = (date, dateString) => {
    if (dateString[0] !== "") {
      this.setState({
        start: true,
        end: true,
        startTime: dateString[0],
        endTime: dateString[1]
      });
    } else {
      this.setState({
        start: false,
        end: false,
        startTime: "",
        endTime: ""
      });
    }
  };

  //table 数据变化
  dateTableChange = data => {
    this.setState({ total: data.data.length });
  };

  //输入框的书写，关键字（姓名或手机号）
  inputTracknameChange = e => {
    // let tmp = Object.assign({}, this.state.ajaxPagePara);
    // tmp.data.Trackname = e.target.value.trim();
    console.log(e.target.value.trim());
    this.setState({ keyword: e.target.value.trim() });
  };

  //点击搜索
  search = () => {
    const pageParm = { ...this.state.pageParm };
    if (this.state.start !== false) {
      const startLeaveDate = this.state.startTime;
      pageParm.startLeaveDate = startLeaveDate;
    } else {
      pageParm.startLeaveDate = "";
    }
    if (this.state.end !== false) {
      const endLeaveDate = this.state.endTime;
      pageParm.endLeaveDate = endLeaveDate;
    } else {
      pageParm.endLeaveDate = "";
    }
    const { keyword } = this.state;
    pageParm.keyword = keyword;
    this.setState({ pageParm });
  };

  //重置
  resetting = () => {
    this.setState(
      {
        keyword: "",
        startTime: "",
        endTime: "",
        start: false,
        end: false
      },
      () => {
        this.search();
      }
    );
  };

  // 点击查看展示信息弹窗
  // clickHandlerView = (orderID) => {
  //   console.log(orderID);
  //   this.setState({
  //     checkModal: true,
  //   });
  //   // this.checkMessageTitle(orderID);
  // };
  //删除
  showDeleteConfirm = orderID => {
    const that = this;
    confirm({
      title: "是否删除所选信息，删除后无法找回。是否确认删除？",
      okText: "确认",
      cancelText: "取消",
      onOk() {
        that.orderDelete(orderID);
      },
      onCancel() {
        console.log("Cancel");
      }
    });
  };
  // 订单删除
  orderDelete = orderID => {
    console.log(orderID);
    // lib.trainOrderDelete({data: {trainOrderID: orderID}}).then((data) => {
    //   console.log("订单删除", data);
    //   this.trainOrderPage();
    // }, (err) => {
    //   console.log("订单删除", err);
    // });
  };

  // 表格渲染
  renderOrderList = () => {
    /* const pageInitStudent = {
      defaultPageSize: 6,
      showQuickJumper: true,
      pageSizeOptions: ["5", "10", "15", "20", "25"],
      showSizeChanger: true
    }; */
    const columns = [
      {
        title: "序号",
        dataIndex: "number",
        key: "number",
        width: 100,
        fixed: 'left',
      },
      {
        title: "姓名",
        dataIndex: "name",
        key: "name"
      },
      {
        title: "所属部门",
        dataIndex: "departName",
        key: "departName"
      },
      // {
      //   title: "工号",
      //   dataIndex: "jobNo",
      //   key: "jobNo"
      // },
      {
        title: "身份证",
        dataIndex: "idCardNo",
        key: "idCardNo"
      },
      {
        title: "手机号",
        dataIndex: "mobilePhone",
        key: "mobilePhone"
      },
      // {
      //   title: "邮箱",
      //   dataIndex: "email",
      //   key: "email"
      // },
      {
        title: "人员类别",
        dataIndex: "perTypeName",
        key: "perTypeName"
      },
      {
        title: "入职日期",
        dataIndex: "entryDate",
        key: "entryDate"
      },
      {
        title: "离职日期",
        dataIndex: "leaveDate",
        key: "leaveDate"
      },
      {
        title: "离职原因",
        dataIndex: "leaveReason",
        key: "leaveReason",
        maxWidth: 300,
        render: (text, record) => {
          let txt = record.leaveReason || '员工自动提交离职申请，现已接触劳动合同关系，系统离职处理。';
          return <div style={{ maxWidth: 200, wordBreak: 'break-all' }}>{txt}</div>
        }
      }, {
        title: '操作',
        key: 'operation',
        fixed: 'right',
        width: 100,
        render: (text, record) => (
          record.isIncumbency == 0 ?
            (<span
              style={{ color: '#108EE9', cursor: 'pointer' }}
              onClick={() => {
                this.props.history.push(
                  `/PersonnelRecruitment/departmentmanagement/PersonnelInformationNav?perId=${record.perId}&reAddMember=1`
                );
              }}
            >复职</span>) : (<span style={{ color: "#999", cursor: 'pointer' }}>复职</span>)
        )
      }
    ];
    return (
      <PTable
        scroll={{ x: 1300 }}
        style={{ marginTop: 20 }}
        columns={columns}
        url="enterpriseLeaveList"
        pageParm={this.state.pageParm}
        forceUpdate={this.state.forceUpdate}
        dateChange={this.dateTableChange}
        showTotal={total => `共搜索到${total}条记录`}
      />
    );
  };

  render() {
    return (
      <div className="ResignationList">
        <Tabs defaultActiveKey="1">
          <TabPane tab="离职记录" key="1">

          </TabPane>
        </Tabs>
        <div className="form">
          <span>
            关键字：
            <Input
              style={{ width: 214 }}
              placeholder="请输入姓名/手机号/身份证"
              onChange={this.inputTracknameChange}
              value={this.state.keyword}
              maxLength={20}
            />
          </span>
          <span style={{ marginLeft: 16 }}>
            离职日期：
            <RangePicker
              format={dateFormat}
              onChange={this.onChangeTime}
              value={[
                this.state.start
                  ? moment(this.state.startTime, dateFormat)
                  : null,
                this.state.end ? moment(this.state.endTime, dateFormat) : null
              ]}
            />
          </span>
          <Button
            style={{ marginLeft: 16 }}
            type="primary"
            onClick={this.search}
          >
            搜索
          </Button>
          <Button style={{ marginLeft: 16 }} onClick={this.resetting}>
            重置
          </Button>
        </div>
        <Popover
          content={(() => {
            return <p style={{ padding: 10 }}>列表有数据才能导出</p>
          })()}
          title="温馨提示："
        >
          <Button
            type="primary"
            disabled={this.state.total == 0}
            style={{ marginLeft: 16 }}
            onClick={() => {
              if (this.state.total == 0) return;
              const { startLeaveDate, endLeaveDate, keyword } = this.state.pageParm;
              axios({
                method: 'get',
                url: `${api.host}/system/per-base-info/export-leave-per`, //后台请求地址
                params: {
                  startLeaveDate,
                  endLeaveDate,
                  keyword
                },
                responseType: 'blob',
                headers: {
                  access_token: store.get('saas')['access_token'],
        Accesstoken: store.get('saas')['access_token']|| sessionStorage.userV5Token,

                }
              }).then(data => {
                if (!data) {
                  return;
                }
                let url = window.URL.createObjectURL(data.data);
                let link = document.createElement('a');
                link.style.display = 'none';
                link.href = url;
                link.setAttribute('download', `离职人员.xls`);
                document.body.appendChild(link);
                link.click();
              });
            }}>
            导出离职记录
          </Button>
        </Popover>
        <div>{this.renderOrderList()}</div>
      </div>
    );
  }
}
