import React, { Component } from 'react';
import { connect } from 'dva';
import { Alert, Button, Form, Modal, message, Badge, Tabs, Popover, notification  } from 'antd';
import ReactDOM from 'react-dom';
import * as api from '../../../../services/api';
// import './less/contract.less';
import PTable from '../../../../components/Pro/PTable';
import PSelect from '../../../../components/Pro/PSelect';
import ContractDrawer from '../../../Administrative/ContractManagement/ContractDrawer';
import DrawRenew from '../../../Administrative/ContractManagement/DrawRenew';

const confirm = Modal.confirm;
const { TabPane } = Tabs;

@connect(state => ({ 
  profile: state.profile
}))
@Form.create()
export default class ContractList extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      open: false, //编辑查看
      editable: false, //抽屉的输入框是否可编辑
      renewOpen: false, //续签合同
      number: 0,
      forceUpdate: false,
      typesd: '', //合同类型
      pageParm: {
        contractType: '',
        contractName: '',
        pageSize: '10',
        pageNumber: '1',
        perId: this.props.perId
      },
      contractType: '',
      contractName: '',
      fileListUrl: '', //文件地址
      visible: false, //续签合同 抽屉 是否可见
      update: true,
      // table: null  //导出表格的元素对象
    };
  }

  //终止合同
  interrupt = record => {
    const that = this;
    confirm({
      title: '即将终止合同，是否继续？',
      content: <p style={{color: 'orange'}}>
        合同终止后，若有关联人员或任务的，将自动解除关联关系，你还要继续吗？
      </p>,
      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);
                }
              );
          }
        });
      }
    });
  };

 

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

  //表格变化
  changeTable = () => {
    this.setState(
      {
        forceUpdate: true,
        open: false
      },
      () => {
        this.setState({
          forceUpdate: false
        });
      }
    );
  };
  /**iverry */
  downLoad = url => {
    if(url) {
      location.href = url;
    }else {
      notification.warning({
        message: '该合同未上传附件！',
        description: '请先上传合同文件，方可下载。'
      });
    }
  }
  /**iverry end */
  //搜索
  handleContractSubmit = () => {
    const pageParm = { ...this.state.pageParm };
    const { contractType, contractName } = this.state; //合同类型//合同名称
    pageParm.contractType = contractType;
    pageParm.contractName = contractName;
    this.setState(
      {
        pageParm,
        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 });
    this.setState({
      comContractId: record.comContractId,
      typesd: record.contractType,
      fileListUrl: record.contractUrl
      // update: true
    });
  };
  handleChange = () => {};

  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',
        // width: 100,
        render: (text, record) => (
          <span
            style={{
              // width: '100px',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
              overflow: 'hidden'
            }}
          >
            {record.contractType_name}
          </span>
        )
      },
      {
        title: '合同名称',
        dataIndex: 'contractName',
        key: 'contractName',
        // width: 200,
        // fixed: 'left',
        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: 'effectStartDate',
        key: 'effectStartDate'
      },  
      {
        title: '合同结束时间',
        dataIndex: 'effectEndDate',
        key: 'effectEndDate'
      },  
      {
        title: '合同状态',
        dataIndex: 'contractEffect',
        key: 'contractEffect',
        // width: 100,
        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',
        // width: 150,
        render: (text, record) => (
          <span
            style={{
              width: '150px',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
              overflow: 'hidden'
            }}
          >
            {record.lastUpdateTime}
          </span>
        )
      },
      {
        title: '操作',
        key: 'action',
        // width: 200,
        render: (text, record) => {
          return(
            <span className="action">
              <span
                onClick={this.changeDrawer2.bind(this, record)}
                style={{ color: '#0F71FF' }}
              >
                查看
              </span>
              {/* iverry  annotation
                * 合同类型（1：已签订:2：已完成、9：已终止，3：已续签）             
              */}
              {record.contractStatus === '2' || record.contractStatus === '9' ? (
                <span style={{ color: '#c7c7c7', cursor: 'not-allowed' }}>
                  编辑
                </span>
              ) : (
                <span
                  onClick={this.changeDrawer3.bind(this, record)}
                  style={{ color: '#0F71FF' }}
                >
                  编辑
                </span>
              )}
              <a
                // href={record.contractUrl}
                href="javascript:void(0);"
                style={{ marginRight: '8px', color: '#0F71FF' }}
                onClick={this.downLoad.bind(this,record.contractUrl)}
              >
                下载
              </a>
              <span
                style={{marginRight: '8px', color: 'red'}}
                onClick={this.showDeleteConfirm.bind(this, record)}
              >
                删除
              </span>
              {/* <span
                onClick={this.openDrawRenew.bind(this, record)}
                style={{ color: '#0F71FF' }}
              >
                续签
              </span>
              <span
                onClick={this.changeDrawer3.bind(this, record)}
                style={{ color: '#0F71FF' }}
              >
                变更
              </span> */}
              {record.contractStatus === '2' || record.contractStatus === '9' ? (
                <span style={{ color: '#c7c7c7', cursor: 'not-allowed' }}>
                  终止
                </span>
              ) : (
                <span
                  onClick={this.interrupt.bind(this, record)}
                  style={{ color: '#0F71FF' }}
                >
                  终止
                </span>
              )}
            </span>
          )
        }
      }
    ];
    return (
      <div>
        <PTable
          style={{ marginTop: 20 }}
          columns={columns}
          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 });
  };

  openDrawRenew = record => {
    this.setState({ comContractId: record.comContractId, renewOpen: true });
  };

  changeDrawer = () => {
    this.props.history.push('./contractList/AddContract');
  };

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

  render() {
    // const { getFieldDecorator } = this.props.form;
    const { renewOpen } = this.state;
    return (
      <div className="contractWrapper">
        <Alert
          message={<div>若您需要新增人员的合同信息，请到【合同管理】中操作。</div>}
          type="warning"
          showIcon
          style={{ marginBottom: '15px' }}
        />
        {/* <Button type="primary">关联合同</Button> */}
       {this.renderTable()}
        <ContractDrawer
          onChange={this.openContractDrawer}
          visiable={this.state.open}
          editable={this.state.editable}
          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}
        />

        {/*续签合同*/}
        {/*<RenewContractDrawer onChange={(renewOpen) => {
          this.setState({renewOpen});
        }} visiable={this.state.renewOpen} editable={this.state.editable} comContractId={this.state.comContractId}
                            typesd={this.state.typesd} fileUrl={this.state.fileListUrl}
                            changeTable={this.changeTable}/>*/}
        {/* 续签合同 */}
        <DrawRenew
          visible={renewOpen}
          closeDrawer={this.closeDrawer}
          confirDrawer={this.confirmDrawer}
          comContractId={this.state.comContractId}
          changeTable={this.changeTable}
        />
      </div>
    );
  }
}
