import React, { Component } from 'react';
import { connect } from 'dva';
import { Alert, Button, Form, Modal, Select, Badge, Tabs, Popover, notification, Input } from 'antd';
import * as api from '../../../services/apiTask';
// 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';
import { gup } from '../../../utils/utils';
const confirm = Modal.confirm;
const Option = Select.Option;

@connect(state => ({ 
  profile: state.profile
}))
@Form.create()
export default class ContractList extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      editable: false, //抽屉的输入框是否可编辑
      renewOpen: false, //续签合同
      number: 0,
      forceUpdate: false,
      typesd: '', //合同类型
      pageParm: {
        comTaskId: props.comTaskId || gup('id'),
        contractType: '',
        contractEffect:'',//合同状态
        pageSize: '10',
        pageNumber: '1',
        keyWord: '',
        isRelationComConTract: '1' //是否关联合同（1：代表查询任务关联的合同，0：代表查询关联以外的合同）
      },
      fileListUrl: '', //文件地址
      visible: false, //续签合同 抽屉 是否可见
      update: true,
      // table: null  //导出表格的元素对象


      // 关联
      relationVisible: false,
      relationPageParm: {
        comTaskId: props.comTaskId || gup('id'),
        contractType: '01',
        pageSize: '10',
        pageNumber: '1',
        keyWord: '',
        comKeyWord:'',
        contractEffect:'1',
        isRelationComConTract: '0'
      },
      relationNumber: 0,
      relationForceUpdate: false,
      selectedRowKeys: [],
      selectedRows: [],
      contractType: '01',
      contractEffect:'1',
      keyWord: '',
      comKeyWord:''
    };
  }
  componentWillReceiveProps(nextProps) {
    if(nextProps.comTaskId) {
      this.setState({
        relationPageParm: {
          ...this.state.relationPageParm,
          comTaskId: nextProps.comTaskId
        },
        pageParm: {
          ...this.state.pageParm,
          comTaskId: nextProps.comTaskId
        }
      });
    }
  }
  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: 'thirdPartyName',
      key: 'thirdPartyName'
    },
    {
      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) => {
        // contractStatus 合同类型（1：已签订:2：已完成、9：已终止，3：已续签）
        return(
          <div>
            {/* <a href="javascript:void(0)" onClick={() => {
              const data = {
                comTaskId: this.state.comTaskId,
                comContractId: this.state.selectedRows[0].comContractId
              };
              api.relateContract(data).then(res => {
                this.setState({
                    relationVisible: false
                });
              });
            }}>关联合同</a> */}
            <a href="javascript:void(0)" style={{color: 'red'}} onClick={() => {
              const THIS = this;
              confirm({
                title: '移除关联',
                content: '确定要移除该合同',
                okText: '确定',
                cancelText: '取消',
                onOk() {
                  const data = {
                    comTaskId: THIS.props.comTaskId || gup('id'),
                    comContractId: record.comContractId
                  };
                  api.cancelCelateContract(data).then(res => {
                    THIS.changeTable();
                  
                    THIS.props.onUpdate && THIS.props.onUpdate();
                  });
                },
                onCancel() {
                  console.log('Cancel');
                }
              });
              
            }}>移除关联</a>
          </div>
        );
      }
    }
  ];
  columns1 = [
    {
      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: 'thirdPartyName',
      key: 'thirdPartyName'
    },
    {
      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>
      )
    }
  ];

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

  //表格变化
  changeTable = () => {
    this.setState(
      {
        forceUpdate: true,
        relationForceUpdate: true,
        selectedRowKeys: [],
        selectedRows: []
      },
      () => {
        this.setState({
          forceUpdate: false,
          relationForceUpdate: false,
          relationVisible: false
        });
      }
    );
  };

  //搜索
  handleContractSubmit = () => {
    const relationPageParm = { ...this.state.relationPageParm };
    const { contractType, keyWord,contractEffect,comKeyWord } = this.state; //合同类型//合同名称
    relationPageParm.contractType = contractType;
    relationPageParm.keyWord = keyWord;
    relationPageParm.comKeyWord = comKeyWord;
    relationPageParm.contractEffect = contractEffect;
    this.setState(
      {
        relationPageParm,
        relationForceUpdate: true
      },
      () => {
        this.setState({
          relationForceUpdate: false
        });
      }
    );
  };




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

  //表格渲染
  renderTable = () => {
    const columns = this.columns;
    return (
      <div>
        <PTable
          style={{ marginTop: 20 }}
          columns={columns}
          url="getContractListByTask"
          pageParm={this.state.pageParm}
          dateChange={this.dateTableChange}
          forceUpdate={this.state.forceUpdate}
        />
      </div>
    );
  };

 

  render() {
    // const { getFieldDecorator } = this.props.form;
    const { renewOpen } = this.state;
    return (
      <div className="contractWrapper">
        <Alert
          message={<div>若您需要编辑合同信息，请到【合同管理】中操作；一个驻勤点只能关联一份合同，若需要修改，请先移除关联。</div>}
          type="warning"
          showIcon
          style={{ marginBottom: '10px' }}
        />
        {
          this.state.number == 0 &&
          <Button type="primary"
            onClick={() => {
            this.setState({
              relationVisible: true,
            }, () => {
              this.setState({
                relationForceUpdate: true
              }, () => {
                this.setState({
                  relationForceUpdate: false
                })
              });
            });
          }}>关联合同</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}
        />
        <DrawRenew
          visible={renewOpen}
          closeDrawer={this.closeDrawer}
          confirDrawer={this.confirmDrawer}
          comContractId={this.state.comContractId}
          changeTable={this.changeTable}
        />
        <Modal
          width="80%"
          title="选择合同"
          visible={this.state.relationVisible}
          onOk={() => {
            const comContractIds = this.state.selectedRows.reduce((a, b) => {
              return a + b.comContractId + ',';
            }, '').slice(0, -1);
            const data = {
              comTaskId: this.props.comTaskId || gup('id'),
              comContractIds
            };
            api.relateContract(data).then(res => {
              this.changeTable();
              // 更新驻勤值守列表
              this.props.onUpdate && this.props.onUpdate();
              // this.setState({
              //     relationVisible: false
              // }, () => {
                
              // });
            });
          }}
          onCancel={() => {
            this.setState({
              relationVisible: false
            });
          }}
        >
          {(() => {
            // let columns = JSON.parse(JSON.stringify(this.columns));
            // columns = columns.splice(0, columns.length-1);
            const columns = this.columns1;
            return (
              <div>
                <label style={{ display: 'inline-block', marginRight: '16px' }}>
                  关键词：
                  <Input
                    style={{
                      width: '214px',
                      marginLeft: '16px',
                      marginBottom: '16px'
                    }}
                    placeholder="合同名称/企业档案编号"
                    onChange={(e) => {
                      this.setState({
                        keyWord: e.target.value.trim()
                      });
                    }}
                    maxLength={30}
                  />
                </label>
                <label style={{ display: 'inline-block', marginRight: '16px' }}>
                  企业名称：
                  <Input
                    style={{
                      width: '240px',
                      marginLeft: '16px',
                      marginBottom: '16px'
                    }}
                    value={this.state.comKeyWord}
                    placeholder="甲方/乙方/丙方名称"
                    onChange={e => {
                      this.setState({
                        comKeyWord: e.target.value.trim()
                      });
                    }}
                    maxLength={30}
                  />
                </label>
                <label>
                  合同类型：
                  <PSelect
                    style={{ width: 214, marginBottom: '16px',marginRight: '16px' }}
                    type="contractType"
                    onChange={this.pSelectChange}
                    value={this.state.contractType}
                    addOption
                    cache={false}
                  />
                </label>
                <label style={{ width: 214, 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>
                <Button
                  id="btnSearch"
                  type="primary"
                  onClick={this.handleContractSubmit}
                  style={{ marginBottom: '16px', marginLeft: 20 }}
                >
                  搜索
                </Button>
                <PTable
                  style={{ marginTop: 20 }}
                  columns={columns}
                  url="getContractListByTask"
                  pageParm={this.state.relationPageParm}
                  dateChange={data => {
                    this.setState({
                      relationNumber: data.total
                    });
                  }}
                  forceUpdate={this.state.relationForceUpdate}
                  rowSelection={{
                    onChange: (selectedRowKeys, selectedRows) => {
                      // console.log(selectedRowKeys,selectedRows);
                      this.setState({
                        selectedRows,
                        selectedRowKeys
                      });
                    },
                    type: 'radio',
                    selectedRowKeys: this.state.selectedRowKeys
                  }}
                />
              </div>
            );
          })()}
        </Modal>
      </div>
    );
  }
}
