/**
 * 未关联合同
 */
import React, { Component } from "react";
import { connect } from "dva";
import {
  Input,
  Alert,
  Button,
  Form,
  Modal,
  message,
  Badge,
  Tabs,
  Popover,
  notification,
  Select,
} from "antd";
import * as api from "../../../../services/api";
import PTable from "../../../../components/Pro/PTable";
import ExcelButtonOline from "../../../../components/ExcelButtonOline";
import ContractDrawer from "../ContractDrawer";
import { withRouter } from "dva/router";
const confirm = Modal.confirm;
const Option = Select.Option;
import axios from "axios";
import store from "store";
@connect((state) => ({
  profile: state.profile,
  global: state.global,
}))
@withRouter
@Form.create()
export default class NotAssociated extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      open: false, //编辑查看
      editable: false, //抽屉的输入框是否可编辑
      editOrGo: true, //抽屉的输入框是编辑还是续签（true是编辑，false是续签，默认是编辑）
      renewOpen: false, //续签合同
      number: 0,
      forceUpdate: false,
      typesd: "", //合同类型
      pageParm: {
        keyWord: "",
        // comKeyWord: "",
        contractType: "02",
        expiredMonth: "",
        pageSize: "10",
        pageNumber: "1",
        contractEffect: "",
        isSeletePer: "0",
      },
      keyWord: "",
      //   comKeyWord: "",
      // contractType: "02",
      expiredMonth: "",
      contractEffect: "",
      fileListUrl: "", //文件地址
      visible: false, //续签合同 抽屉 是否可见
      update: true,
      // table: null  //导出表格的元素对象
      expireContractCount: 0, //即将到期的合同数量
      canExport: false, //是否可以导出表格
    };
  }

  componentWillMount() {
    api.getExpireContractCount({ expiredMonth: 1 }).then((res) => {
      this.setState({
        expireContractCount: res.data,
      });
    });
  }
  //终止合同
  interrupt = (record) => {
    const that = this;
    confirm({
      title: "即将终止合同，是否继续？",
      okText: "继续",
      cancelText: "取消",
      onOk() {
        api
          .enterpriseComContractTerminationComContract({
            comContractId: record.comContractId,
          })
          .then(
            (data) => {
              that.setState(
                {
                  forceUpdate: true,
                },
                () => {
                  that.setState({
                    forceUpdate: false,
                  });
                }
              );
            },
            (err) => {
              message.error(err);
            }
          );
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };
  //根据id删除合同
  showDeleteConfirm = (record) => {
    const that = this;
    const { comContractId } = record;
    api.checkRelateTaskByContractId({ comContractId }).then((res) => {
      // isExistsRelateTask是否存在关联的任务（0：不存在 1:存在）
      const { isExistsRelateTask, taskNames } = res.data;
      if (isExistsRelateTask == 1) {
        confirm({
          title: "即将删除合同，是否继续？",
          content: (
            <p style={{ color: "orange" }}>
              合同删除后，若有关联人员或任务的，将自动解除关联关系，你还要继续吗？
            </p>
          ),
          okText: "继续",
          cancelText: "取消",
          onOk() {
            api
              .enterpriseComContractDeleteComContract({
                comContractId: record.comContractId,
                isExistsRelateTask,
              })
              .then(
                (data) => {
                  if (data.retType === 0) {
                    message.success(data.msg);
                  }
                  that.setState(
                    {
                      forceUpdate: true,
                    },
                    () => {
                      that.setState({
                        forceUpdate: false,
                      });
                    }
                  );
                },
                (err) => {
                  message.error(err);
                }
              );
          },
        });
      } else {
        confirm({
          title: "即将删除合同，是否继续？",
          content: (
            <p style={{ color: "orange" }}>
              合同删除后，若有关联人员或任务的，将自动解除关联关系，你还要继续吗？
            </p>
          ),
          okText: "继续",
          cancelText: "取消",
          onOk() {
            api
              .enterpriseComContractDeleteComContract({
                comContractId: record.comContractId,
                isExistsRelateTask,
              })
              .then(
                (data) => {
                  if (data.retType === 0) {
                    message.success(data.msg);
                  }
                  that.setState(
                    {
                      forceUpdate: true,
                    },
                    () => {
                      that.setState({
                        forceUpdate: false,
                      });
                    }
                  );
                },
                (err) => {
                  message.error(err);
                }
              );
          },
        });
      }
    });
  };

  //输入框所输入的值
  onChangeName = (e) => {
    this.setState({
      contractName: e.target.value.trim(),
    });
  };

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

  //表格变化
  changeTable = () => {
    this.setState(
      {
        forceUpdate: true,
        open: false,
      },
      () => {
        this.setState({
          forceUpdate: false,
        });
      }
    );
  };
  downLoad = (url) => {
    if (url) {
      window.open(url);
    } else {
      notification.warning({
        message: "该合同未上传附件！",
        description: "请先上传合同文件，方可下载。",
      });
    }
  };
  /**iverry end */
  //搜索
  handleContractSubmit = () => {
    const pageParm = { ...this.state.pageParm };
    let { keyWord, comKeyWord, contractType, expiredMonth } = this.state;
    pageParm.keyWord = keyWord;
    // pageParm.comKeyWord = comKeyWord;
    // pageParm.contractType = contractType;
    pageParm.expiredMonth = expiredMonth == "" ? "" : parseInt(expiredMonth);
    pageParm.contractEffect = this.state.contractEffect;
    this.setState(
      {
        pageParm,
        canExport: true,
        forceUpdate: true,
      },
      () => {
        this.setState({
          forceUpdate: false,
        });
      }
    );
  };
  //抽屉视图处理
  //查看
  changeDrawer2 = (record) => {
    this.setState({ open: true });
    this.setState({ editable: true });
    this.setState({
      comContractId: record.comContractId,
      typesd: record.contractType,
      fileListUrl: record.contractUrl,
      // update: true
    });
  };
  //编辑
  changeDrawer3 = (record) => {
    this.setState({ open: true });
    this.setState({ editable: false, editOrGo: true });
    this.setState({
      comContractId: record.comContractId,
      typesd: record.contractType,
      fileListUrl: record.contractUrl,
      // update: true
    });
  };
  //续签的状态
  openDrawRenew = (record) => {
    this.setState({
      comContractId: record.comContractId,
      typesd: record.contractType,
      fileListUrl: record.contractUrl,
      open: true,
      editable: false,
      editOrGo: false,
    });
  };
  closeUpdate = () => {
    this.setState({
      update: false,
    });
  };
  openUpdate = () => {
    this.setState({
      update: true,
    });
  };

  //报表类型 change
  pSelectChange = (value, type) => {
    this.setState({ [type]: value });
  };

  //表格渲染
  renderTable = () => {
    const columns = [
      {
        title: "合同类型",
        dataIndex: "contractType_name",
        key: "contractType_name",
        render: (text, record) => (
          <span
            style={{
              whiteSpace: "nowrap",
              textOverflow: "ellipsis",
              overflow: "hidden",
            }}
          >
            {record.contractType_name}
          </span>
        ),
      },
      {
        title: "合同名称",
        dataIndex: "contractName",
        key: "contractName",
        render: (text, record) => (
          <Popover
            content={
              <span
                style={{
                  whiteSpace: "normal",
                  width: "300px",
                  display: "inline-block",
                  padding: "10px",
                }}
              >
                {text}
              </span>
            }
            placement="rightTop"
          >
            <div
              style={{
                maxWidth: "300px",
                whiteSpace: "nowrap",
                textOverflow: "ellipsis",
                overflow: "hidden",
                marginTop: "8px",
                marginBottom: "8px",
              }}
            >
              {record.contractName}
            </div>
          </Popover>
        ),
      },

      {
        title: "企业档案编号",
        dataIndex: "comFileNo",
        key: "comFileNo",
      },
      {
        title: "甲方名称",
        dataIndex: "firstPartyName",
        key: "firstPartyName",
      },
      {
        title: "乙方名称",
        dataIndex: "secondPartyName",
        key: "secondPartyName",
      },
      // {
      //   title: "丙方名称",
      //   dataIndex: "thirdPartyName",
      //   key: "thirdPartyName",
      // },
      {
        title: "合同有效期",
        dataIndex: "effectStartDate",
        key: "effectStartDate",
        render: (text, record) => {
          return (
            <span>
              {text}~{record.effectEndDate}
            </span>
          );
        },
      },
      {
        title: "合同状态",
        dataIndex: "contractEffect",
        key: "contractEffect",
        render: (text, record) => {
          let status = "";
          switch (true) {
            case text == "未生效":
              status = "warning";
              break;
            case text == "有效":
              status = "success";
              break;
            case text == "终止":
              status = "error";
          }
          return (
            <div>
              <Badge status={status} />
              <span>{text}</span>
            </div>
          );
        },
      },
      {
        title: "最后修改时间",
        dataIndex: "lastUpdateTime",
        key: "lastUpdateTime",
        render: (text, record) => (
          <span
            style={{
              width: "150px",
              whiteSpace: "nowrap",
              textOverflow: "ellipsis",
              overflow: "hidden",
            }}
          >
            {record.lastUpdateTime}
          </span>
        ),
      },
      {
        title: "操作",
        key: "action",
        render: (text, record) => {
          return (
            <span className="action">
              <a
                onClick={this.changeDrawer2.bind(this, record)}
                style={{ marginRight: "8px",color: "#0F71FF" }}
              >
                查看
              </a>
              <a
                onClick={this.changeDrawer3.bind(this, record)}
                style={{ marginRight: "8px",color: "#0F71FF" }}
              >
                编辑
              </a>
              <a
                href="javascript:void(0);"
                style={{ marginRight: "8px", color: "#0F71FF" }}
                onClick={this.downLoad.bind(this, record.contractUrl)}
              >
                下载
              </a>
              <a
                className="delete"
                onClick={this.showDeleteConfirm.bind(this, record)}
                style={{ marginRight: "8px",color: "#0F71FF" }}
              >
                删除
              </a>
              <a
                onClick={this.openDrawRenew.bind(this, record)}
                style={{ marginRight: "8px",color: "#0F71FF" }}
              >
                续签
              </a>
              {record.contractStatus != "2" && record.contractStatus != "9" && (
                <a
                  onClick={this.interrupt.bind(this, record)}
                  style={{ marginRight: "8px",color: "#0F71FF" }}
                >
                  终止
                </a>
              )}
            </span>
          );
        },
      },
    ];
    // 导出的合同列表
    const columnsExport = [
      {
        title: "合同类型",
        dataIndex: "contractType_name",
        key: "contractType_name",
        // width: 100,
        render: (text, record) => (
          <span
            style={{
              // width: '100px',
              whiteSpace: "nowrap",
              textOverflow: "ellipsis",
              overflow: "hidden",
            }}
          >
            {record.contractType_name}
          </span>
        ),
      },
      {
        title: "合同名称",
        dataIndex: "contractName",
        key: "contractName",
        render: (text, record) => (
          <Popover
            content={
              <span
                style={{
                  whiteSpace: "normal",
                  width: "300px",
                  display: "inline-block",
                  padding: "10px",
                }}
              >
                {text}
              </span>
            }
            placement="rightTop"
          >
            <div
              style={{
                maxWidth: "300px",
                whiteSpace: "nowrap",
                textOverflow: "ellipsis",
                overflow: "hidden",
                marginTop: "8px",
                marginBottom: "8px",
              }}
            >
              {record.contractName}
            </div>
          </Popover>
        ),
      },
      {
        title: "企业档案编号",
        dataIndex: "comFileNo",
        key: "comFileNo",
        // width: 300,
        render: (text, record) => (
          <span
            style={{
              // width: '300px',
              whiteSpace: "nowrap",
              textOverflow: "ellipsis",
              overflow: "hidden",
            }}
          >
            {record.comFileNo}
          </span>
        ),
      },
      {
        title: "甲方名称",
        dataIndex: "firstPartyName",
        key: "firstPartyName",
        // width: 300,
        render: (text, record) => (
          <span
            style={{
              // width: '300px',
              whiteSpace: "nowrap",
              textOverflow: "ellipsis",
              overflow: "hidden",
            }}
          >
            {record.firstPartyName}
          </span>
        ),
      },
      {
        title: "联系电话",
        dataIndex: "firstPartyTel",
        key: "firstPartyTel",
        // width: 300,
        render: (text, record) => (
          <span
            style={{
              // width: '300px',
              whiteSpace: "nowrap",
              textOverflow: "ellipsis",
              overflow: "hidden",
            }}
          >
            {record.firstPartyTel}
          </span>
        ),
      },
      {
        title: "乙方名称",
        dataIndex: "secondPartyName",
        key: "secondPartyName",
        // width: 300,
        render: (text, record) => (
          <span
            style={{
              // width: '300px',
              whiteSpace: "nowrap",
              textOverflow: "ellipsis",
              overflow: "hidden",
            }}
          >
            {record.secondPartyName}
          </span>
        ),
      },
      {
        title: "联系电话",
        dataIndex: "secondPartyTel",
        key: "secondPartyTel",
        // width: 300,
        render: (text, record) => (
          <span
            style={{
              // width: '300px',
              whiteSpace: "nowrap",
              textOverflow: "ellipsis",
              overflow: "hidden",
            }}
          >
            {record.secondPartyTel}
          </span>
        ),
      },
      {
        title: "合同开始时间",
        dataIndex: "effectStartDate",
        key: "effectStartDate",
        // width: 150,
        render: (text, record) => (
          <span
            style={{
              width: "150px",
              whiteSpace: "nowrap",
              textOverflow: "ellipsis",
              overflow: "hidden",
            }}
          >
            {record.effectStartDate}
          </span>
        ),
      },
      {
        title: "合同结束时间",
        dataIndex: "effectEndDate",
        key: "effectEndDate",
        // width: 150,
        render: (text, record) => (
          <span
            style={{
              width: "150px",
              whiteSpace: "nowrap",
              textOverflow: "ellipsis",
              overflow: "hidden",
            }}
          >
            {record.effectEndDate}
          </span>
        ),
      },
      {
        title: "合同期限",
        dataIndex: "contractPeriod",
        key: "contractPeriod",
        // width: 150,
        render: (text, record) => (
          <span
            style={{
              width: "150px",
              whiteSpace: "nowrap",
              textOverflow: "ellipsis",
              overflow: "hidden",
            }}
          >
            {record.contractPeriod}
          </span>
        ),
      },
      {
        title: "协议签订日期",
        dataIndex: "agreementSignDate",
        key: "agreementSignDate",
        // width: 150,
        render: (text, record) => (
          <span
            style={{
              width: "150px",
              whiteSpace: "nowrap",
              textOverflow: "ellipsis",
              overflow: "hidden",
            }}
          >
            {record.agreementSignDate}
          </span>
        ),
      },
      {
        title: "合同备注信息",
        dataIndex: "remark",
        key: "remark",
        // width: 150,
        render: (text, record) => (
          <span
            style={{
              width: "150px",
              whiteSpace: "nowrap",
              textOverflow: "ellipsis",
              overflow: "hidden",
            }}
          >
            {record.remark}
          </span>
        ),
      },
    ];
    return (
      <div>
        <PTable
          style={{ marginTop: 20 }}
          columns={columns}
          url="enterpriseComContractComContractList"
          pageParm={this.state.pageParm}
          dateChange={this.dateTableChange}
          forceUpdate={this.state.forceUpdate}
        />
        <PTable
          ref="table"
          style={{ marginTop: 20, display: "none" }}
          columns={columnsExport}
          url="enterpriseComContractComContractList"
          pageParm={this.state.pageParm}
          dateChange={this.dateTableChange}
          forceUpdate={this.state.forceUpdate}
        />
      </div>
    );
  };

  //关闭 修改 item 抽屉
  closeDrawer = () => {
    Modal.confirm({
      title: "当前信息未提交，返回后无法保证。是否确认返回？",
      okText: "确定",
      cancelText: "取消",
      onOk: () => {
        this.setState({ renewOpen: false });
      },
      onCancel: () => {
        console.log("Cancel");
      },
    });
  };
  confirmDrawer = () => {
    this.setState({ renewOpen: false });
  };

  //   changeDrawer = () => {
  //     this.props.history.push({
  //       pathname: `./addContract`,
  //       state: {
  //         title: "劳务/劳动合同",
  //         url: "/contractManagement/laborContract",
  //         type: "02",
  //       },
  //     });
  //   };

  openContractDrawer = (visiable) => {
    this.setState({ open: visiable });
  };

  render() {
    // const { getFieldDecorator } = this.props.form;
    const { renewOpen, expireContractCount } = this.state;
    const { regProvince } = this.props.global.companyInfo;
    return (
      <div>
        <Alert
          style={{ marginBottom: 15 }}
          message={(() => {
            return (
              <span>
                本页面显示的是录入的劳务/劳务合同，但未使用“从组织架构选择”来关联到人员的合同信息；请确保在职人员都有关联到合同信息，否则当其他业务需要查询人员合同时会查找不到。
              </span>
            );
          })()}
          type="warning"
          showIcon
        />

        <div>
          <label style={{ display: "inline-block", marginRight: "16px" }}>
            关键词：
            <Input
              style={{
                width: "240px",
                marginLeft: "16px",
                marginBottom: "16px",
              }}
              value={this.state.keyWord}
              placeholder="合同名称/企业档案编号"
              onChange={(e) => {
                this.setState({
                  keyWord: e.target.value.trim(),
                });
              }}
              maxLength={30}
            />
          </label>
          <label style={{ display: "inline-block", margin: "0 16px 0" }}>
            到期预警：
            <Select
              style={{ width: 240 }}
              placeholder="请选择"
              onChange={(value) => {
                this.setState({
                  expiredMonth: value,
                });
              }}
              value={this.state.expiredMonth}
            >
              <Option value="">全部</Option>
              <Option value="1">近一个月到期</Option>
              <Option value="2">近两个月到期</Option>
              <Option value="3">近三个月到期</Option>
            </Select>
          </label>

          <label style={{ display: "inline-block", marginRight: "16px" }}>
            合同状态：
            <Select
              value={this.state.contractEffect}
              style={{ width: 120 }}
              onChange={(value) => {
                this.setState({
                  contractEffect: value,
                });
              }}
            >
              <Option value="">全部</Option>
              <Option value="0">未生效</Option>
              <Option value="1">有效</Option>
              <Option value="2">终止</Option>
            </Select>
          </label>
          <Popover
            content={(() => {
              return <p style={{ padding: 10 }}>搜索后可导出搜索结果</p>;
            })()}
            title="温馨提示："
          >
            <Button
              id="btnSearch"
              type="primary"
              onClick={this.handleContractSubmit}
              style={{ marginBottom: "16px" }}
            >
              搜索
            </Button>
          </Popover>
          <Button
            id="btnSearch"
            onClick={() => {
              const pageParm = {
                ...this.state.pageParm,
                keyWord: "",
                //   comKeyWord: "",
                //   contractType: '',
                expiredMonth: "",
                contractEffect: "",
              };
              this.setState(
                {
                  pageParm,
                  keyWord: "",
                  // comKeyWord: "",
                  // contractType: '',
                  expiredMonth: "",
                  forceUpdate: true,
                  canExport: false,
                  contractEffect: "",
                },
                () => {
                  this.setState({
                    forceUpdate: false,
                  });
                }
              );
            }}
            style={{ marginBottom: "16px", marginLeft: 15 }}
          >
            重置
          </Button>
        </div>
        <div>
          {/* <Button type="primary" onClick={this.changeDrawer}>
              添加合同
            </Button> */}
          <Popover
            content={(() => {
              return <p style={{ padding: 10 }}>搜索后可导出搜索结果</p>;
            })()}
            title="温馨提示："
          >
            <ExcelButtonOline
              disabled={!this.state.canExport}
              style={{ marginLeft: "15px" }}
              params={this.state.pageParm}
              apiurl={"/enterprise/com-contract/export-contract-list"}
              downloadname={this.props.global.companyInfo.comName + "_合同"}
            >
              导出为excel表格
            </ExcelButtonOline>
          </Popover>
        </div>
        {this.renderTable()}
        <ContractDrawer
          onChange={this.openContractDrawer}
          visiable={this.state.open}
          editable={this.state.editable}
          editOrGo={this.state.editOrGo}
          comContractId={this.state.comContractId}
          typesd={this.state.typesd}
          fileUrl={this.state.fileListUrl}
          changeTable={this.changeTable}
          closeUpdate={this.closeUpdate}
          openUpdate={this.openUpdate}
          update={this.state.update}
        />

        {/* 续签合同 */}
        {/* <DrawRenew
            visible={renewOpen}
            closeDrawer={this.closeDrawer}
            confirDrawer={this.confirmDrawer}
            comContractId={this.state.comContractId}
            changeTable={this.changeTable}
          /> */}
      </div>
    );
  }
}
