import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Input,
  Button,
  Table,
  Select,
  Modal,
  message,
  notification,
  Radio,
  Alert,
  TreeSelect,
  DatePicker,
  Popover
} from 'antd';
import moment from 'moment';
const RadioGroup = Radio.Group;
import "moment/locale/zh-cn";
import { withRouter } from 'dva/router';
import './less/insurance.less';
import { gup,log, $log } from '../../../../utils/utils';
import * as ajax from '../../../../services/api';
import ExcelButtonOline from '../../../../components/ExcelButtonOline';
const { Option } = Select;
@connect(state => ({
  global: state.global
}))
@withRouter
export default class Uninsured extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      canExport: false, //是否可以导出表格
      // 搜索部分
      searchData: {  // 表格数据请求参数
        comInsId: '',  //保单id
        keyword: '',  //关键字
        departId: '',  //部门id
        isIncumbency: '', //是否在职：1.是；0.否
        pageNumber: '1',  // 页	
        pageSize: '10'  //条目
      },
      keyword: '', //关键字
      comInsId: '',  //保单id
      departId: '', //部门id
      isIncumbency: '',  //就职状态
      orderId: '', //保单订单id
      treeData: [  // 部门数据
        //树
        { title: '', key: '' }
      ],
      policeys: [], //保险列表
      policeyIndex: 0,  //保险列表当前的值
      buyMode: '', //区分线上线下
      // 表格部分
      tableList: [], // 表格数据
      pagination: {  //分页数据
        total:1,
        current: 1,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions:['10', '50', '100', '500']
      },
      selectedRows: [], //表格中选中的数组
      selectedRowKeys: [],

      // 弹窗部分
      // 批量减员
      modalVisible: false, // 批量减员模态框显示状态
      // 单个减员
      quitCount: 0  //离职在保数量
    };
  }


  componentWillReceiveProps(props) {
    if(props.updateNum && props.updateNum > 0) {
      this.getTable(this.state.searchData);
    }
  }
  componentDidMount() {
    this.initPage();
  }

  // 初始化
  initPage = () => {
    // 先获取部门
    this.getDepart(() => {
      // 在获取保单
      this.getPolicey(() => {
        // 再初始化表格
        this.getTable(this.state.searchData, data => {
          // this.props.getTotal(data.total);
        });
      });
    });

    // 
    ajax.findYIncumbencyPerCount().then(res => {
      this.setState({
        quitCount: res.data
      });
    });
  }
  getPolicey = (cb) => {
    // 线上保单
    ajax.findOfflineOrOnlinePolicy({buyMode:1}).then(res => {
      const onlineList = res.data.map(item => {
        item.buyMode = 1;  //线上
        return item;
      });
      onlineList.unshift({
        comInsId: "",
        label: "全部",
        orderId: "",
        buyMode: 0   // 不区分线上线下
      });
      //线下保单
      ajax.findOfflineOrOnlinePolicy({buyMode:2}).then(result => {
        const outlineList = result.data.map(item => {
          item.buyMode = 2; //线下
          return item;
        });
        this.setState({
          policeys: [...onlineList, ...outlineList]
        },() => {
          this.setState({
            comInsId: this.state.policeys[0].comInsId,
            orderId: this.state.policeys[0].orderId,
            buyMode: this.state.policeys[0].buyMode
          });
          cb&&cb();
        });
      });
    });
  }
   // 获取表格信息
   getTable = (data, cb) => {
    ajax.findUnderWarrantyPerList(data).then(res => {
      const { pageNumber, pageSize } = res.data;
      const tableList = res.data.data.map((item, i) => {
        return {
          ...item,
          number: (pageNumber - 1) * pageSize + i + 1
        }
      });
      this.setState({
        tableList,
        pagination: {
          ...this.state.pagination,
          total: res.data.total,
          current: res.data.pageNumber,
          pageSize: res.data.pageSize
        },
        selectedRowKeys: [],
        selectedRows: []
      }, () => {
        cb&&cb(res.data);
        this.props.getTotal(res.data.other);
      });
    });
  }

  //获取部门树数据
  getDepart = (cb) => {
    //获取部门树数据
    ajax.systemComDepartGetTreeDepart().then(
      response => {
        // $log(response, 'blue');
        let { data } = response;
        data = JSON.parse(
          JSON.stringify(data).replace(/\"children\":\[\]/g, '"isLeaf":true')
        );
        data.unshift({
          label: '全部',
          value: ''
        });
        this.setState({
          treeData: data
        });
        cb&&cb();
      },
      err => {
        console.log(err, 'getTreeDepart-选择部门-err');
      }
    );
  }


  // 表格渲染
  renderOrderList = () => {
    const columns = [
      {
        title: '序号',
        dataIndex: 'number',
        key: 'number'
      },
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '手机号',
        dataIndex: 'mobilePhone',
        key: 'mobilePhone'
      },
      {
        title: '身份证号',
        dataIndex: 'idCardNo',
        key: 'idCardNo'
      },
      {
        title: '人员类别',
        dataIndex: 'majorGroup',
        key: 'majorGroup'
      },
      {
        title: '关联保单号',
        dataIndex: 'policyNo',
        key: 'policyNo'
      },
      {
        title: '保单有效期',
        dataIndex: 'effectDate',
        key: 'effectDate'
      },
      {
        title: '购买方式',
        dataIndex: 'buyModeName',
        key: 'buyModeName'
      },
      {
        title: '在职状态',
        dataIndex: 'incumbencyName',
        key: 'incumbencyName',
        render: (text, record) => (
          record.incumbencyName == '在职'? <span style={{color: '#00cc66'}}>在职</span>: <span style={{color: '#ff6600'}}>离职</span>
        )
      },

      {
        title: '操作',
        key: 'operation',
        render: (text, record) => (
          <div>
            <span
              style={{
                color: '#108EE9',
                cursor: 'pointer',
                marginRight: '20px'
              }}
              onClick={() => {
                Modal.confirm({
                  title: '是否为选中的人员进行减员操作？',
                  content: (<div>
                    <p>关联线下保单，则直接移除关联；</p>
                    <p>关联线上保单，则提交减员申请。</p>
                  </div>),
                  okText: '确认',
                  onOk:() => {
                    // 线上保单
                    if(record.buyMode == '1') {
                      const perIds = record.perId;
                      const orderId = record.orderId;
                      ajax.saveInsBlbMinusPreservationService({orderId, perIds}).then(res => {
                        Modal.success({
                          title: '提交减员申请成功！',
                          okText: '确定',
                          content: <p className="modal_tip left0">注：关联线上保单时，需要等待保险公司审核，请在<a>批单申请记录中</a>查看进度。</p>
                        });
                        this.getTable(this.state.searchData);
                      });
                    }else {  //线下
                      const idCards = record.idCardNo;
                      const comInsId = record.comInsId;
                      ajax.minusBatchRelevancePer({idCards, comInsId}).then(res => {
                        // Modal.success({
                        //   title: '移除成功！',
                        //   content: <p className="modal_tip left0">已将所选选择人员移除保障状态！</p>
                        // });
                        Modal.confirm({
                          title: '上传批单提示',
                          content: (<div>
                            <p style={{ color: 'red' }}>*企业若发生人员变动，可通过【保险保单管理】-【修改】上传批单，后台将进行人工校验，请务必上传真实有效数据！</p>
                            <p>本次共移除<span style={{ color: 'red' }}>1</span>位，请及时上传相应批单！</p>
                          </div>),
                          okText: '马上办理',
                          cancelText: '取消',
                          onOk: () => {
                            this.props.history.push(`/insurancemanagement/enterpriseinsurance/insurancedetails?comInsId=${comInsId}&edit=00`);
                          }
                        });
                        this.getTable(this.state.searchData);
                      });
                    }
                  },
                  cancelText: '取消'
                });
              }}
            >
              减员
            </span>
          </div>
        )
      }
    ];
    return (
      <Table
        dataSource={this.state.tableList}
        columns={columns}
        pagination={this.state.pagination}
        onChange={pagination => {
          const data =  {  // 搜索数据
            ...this.state.searchData,
            pageNumber: pagination.current,  // 页	
            pageSize: pagination.pageSize  
          };
          this.setState({
            searchData: data
          });
          this.getTable(data);
        }}
        rowSelection={{
          onChange: (selectedRowKeys, selectedRows) => {
            this.setState({
              selectedRows,
              selectedRowKeys
            });
          },
          selectedRowKeys: this.state.selectedRowKeys
        }}
      />
    );
  };
  render() {
    return (
      <div className="insurance">
        {
          this.state.quitCount>0?<Alert
          message={<div>当前有{this.state.quitCount}个已离职人员未退保，请逐单处理，若对应的保单过期了，则会自动将已投保人员变更为未投保状态；
          <br/>
          减员：可将已投保人员移出投保单（退保），请先筛选保单，再选择需要减员的人员，点击 <span style={{color: '#f5222d'}}>减员</span> 按钮，进行操作。</div>}
          type="warning"
          showIcon
          style={{ marginBottom: '15px' }}
        />: ''
        }
        <div className="form" style={{paddingBottom: 16 }}>
          <label style={{ marginRight: 16}}>
            选择保单：
            <Select style={{minWidth: 600}} value={this.state.policeyIndex} onChange={(value) => {
                const comInsId = this.state.policeys[value].comInsId;
                const orderId = this.state.policeys[value].orderId;
                const buyMode = this.state.policeys[value].buyMode;
                this.setState({
                  comInsId,
                  orderId,
                  buyMode,
                  policeyIndex: value
                });
              }}>
                {this.state.policeys.map((item, index) => {
                  return (
                    <Option key={index} value={index}>{item.label}</Option>
                  );
                })}
              </Select>
          </label>
        </div>
        <div className="form">
          <label style={{ marginRight: 16 }}>
            关键词：
            <Input
              style={{ width: '214px', marginBottom: '10px' }}
              placeholder="请输入姓名/手机号/身份证"
              value={this.state.keyword}
              onChange={(e) => {
                this.setState({
                  keyword: e.target.value
                });
              }}
              maxLength={20}
            />
          </label>
          <label style={{ marginRight: 16 }}>
            部门：
            <TreeSelect
              style={{ width: 200 }}  
              className="w-400 ipt-h"
              dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
              treeData={this.state.treeData}
              placeholder="请选择部门"
              treeDefaultExpandAll
              value={this.state.departId}
              onChange={value => {
                this.setState({
                  departId: value
                });
              }}
            />
          </label>
          <label style={{ marginRight: 16 }}>
            就职状态：
            <Select
              value={this.state.isIncumbency}
              style={{ width: 200 }}
              placeholder="请选择"
              onChange={(value) => {
                $log(value, 'green', '人员类别');
                this.setState({
                  isIncumbency: value
                });
              }}
            >
              <Option key="" value="">全部</Option>
              <Option key="0" value="0">离职</Option>
              <Option key="1" value="1">在职</Option>
            </Select>
          </label>
          <Button
            style={{
              marginRight: '16px',
              marginBottom: '16px',
              padding: window && window.innerWidth <= 1366 ? '0 10px' : '0 15px'
            }}
            type="primary"
            onClick={() => {
              const data = {
                ...this.state.searchData,
                comInsId: this.state.comInsId,  //保单id
                keyword: this.state.keyword,  //关键字
                departId: this.state.departId,  //部门id
                isIncumbency: this.state.isIncumbency, //是否在职：1.是；0.否
             };

             this.setState({
               searchData: data,
               canExport: true
             });
             this.getTable(data);
            }}
          >
            搜索
          </Button>
          <Button
            onClick={() => {
              this.setState({
                searchData: {
                  comInsId: '',
                  keyword: '',  //关键字
                  departId: '',  //部门id
                  isIncumbency: '',
                  pageNumber: '1',  // 页	
                  pageSize: '10'  //条目
                }
              }, () => {
                this.setState({
                  ...this.state.searchData,
                  policeyIndex: 0
                });
                this.getTable(this.state.searchData);
              });
            }}
            style={{
              padding: window && window.innerWidth <= 1366 ? '0 10px' : '0 15px'
            }}
          >
            重置
          </Button>
        </div>
        <div className="receive-list">
          <div className="receive-row">
            <Popover content={
              <div style={{padding: '5px 10px'}}>
                <p style={{margin:0}}>请选择保单</p>
              </div>
            } title="温馨提示">  
            
              <Button type="primary" 
                disabled={this.state.searchData.comInsId == ''}
                onClick={() => {
                  if(this.state.selectedRows.length == 0) {
                    notification.error({
                      message: '请选择人员'
                    });
                  }else {
                    Modal.confirm({
                      title: '是否为选中的人员进行减员操作？',
                      content: (<div>
                        <p>关联线下保单，则直接移除关联；</p>
                        <p>关联线上保单，则提交减员申请。（一次最多减员100人）</p>
                      </div>),
                      okText: '确认',
                      onOk:() => {
                        const { orderId, comInsId } = this.state;  
                        // 线上保单
                        if(this.state.buyMode == 1) {
                          if(this.state.selectedRows.length > 100){
                            return notification.error({
                              message: '一次关联人数不超过100个'
                            });
                          }
                          const perIds = this.state.selectedRows.reduce((a, b) => {
                            return a+ ','+b.perId;
                          }, '').slice(1);
                          ajax.saveInsBlbMinusPreservationService({orderId, perIds}).then(res => {
                            Modal.success({
                              title: '提交减员申请成功！',
                              content: <p className="modal_tip left0">注：关联线上保单时，需要等待保险公司审核，请在<a>批单申请记录中</a>查看进度。</p>
                            });
                            this.getTable(this.state.searchData);
                          });
                        }else {  //线下
                          const idCards = this.state.selectedRows.reduce((a, b) => {
                            return a+ ','+b.idCardNo;
                          }, '').slice(1);
                          ajax.minusBatchRelevancePer({idCards, comInsId}).then(res => {
                            // Modal.success({
                            //   title: '移除成功！',
                            //   content: <p className="modal_tip left0">已将所选选择人员移除保障状态！</p>
                            // });
                            Modal.confirm({
                              title: '上传批单提示',
                              content: (<div>
                                <p style={{ color: 'red' }}>*企业若发生人员变动，可通过【保险保单管理】-【修改】上传批单，后台将进行人工校验，请务必上传真实有效数据！</p>
                              <p>本次共移除<span style={{ color: 'red' }}>{this.state.selectedRows.length}</span>位，请及时上传相应批单！</p>
                              </div>),
                              okText: '马上办理',
                              cancelText: '取消',
                              onOk: () => {
                                this.props.history.push(`/insurancemanagement/enterpriseinsurance/insurancedetails?comInsId=${comInsId}&edit=00`);
                              }
                            });
                            this.getTable(this.state.searchData);
                          });
                        }
                      },
                      cancelText: '取消'
                    });
                    // this.setState({
                    //   modalVisible: true
                    // });
                  }
                }}
              >
                批量减员
              </Button>
            </Popover>
            <Popover
              content={
                <div style={{padding: 10}}>搜索后可导出</div>
              }
            >
              <ExcelButtonOline
                disabled={!this.state.canExport}
                method="POST"
                style={{ marginLeft: "15px" }}
                params={this.state.searchData}
                apiurl={"/enterprise/ins/com-ins/export-under-warranty-per-list"}
                downloadname={this.props.global.companyInfo.comName + "_已投保人员"}
              >
                导出筛选结果为excel
              </ExcelButtonOline>
            </Popover>
            {/*发送信息弹窗*/}
            
            {/* <Button onClick={() => {
              log('filter')
            }}>批量设置为过滤</Button> */}
          </div>
        </div>
        {this.renderOrderList()}
        {/*查看信息弹窗1*/}
        {/* <MessageDetail
          record={this.state.record}
          visible={this.state.checkModal}
          closeModal={() => {
            this.setState({ checkModal: false });
            this.search();
          }}
        /> */}

        {/* 批量减员弹窗内容 */}
        <Modal
          title={
            <span>
              {/* <Icon style={{color: '#ff9900'}} type="warning" /> */}
              是否为选中的人员进行减员操作？
            </span>
          }
          maskClosable={true}
          visible={this.state.modalVisible}
          onOk={() => {
            const { orderId } = this.state;
            const perIds = this.state.selectedRows.reduce((a, b) => {
              return a+ ','+b.perId;
            }, '').slice(1);
            this.saveInsBlbMinusPreservationService({orderId, perIds});
          }}
          onCancel={() => {
            this.setState({
              modalVisible: false
            });
          }}
        >
          <p>关联线下保单，则直接移除关联；</p>
          <p>关联线上保单，则提交减员申请。</p>
        </Modal>

      </div>
    );
  }
}
