import React, { Component } from 'react';
import { connect } from 'dva';
// import st from 'styled-components';
import {
  Form,
  Input,
  Select,
  Button,
  DatePicker,
  Modal,
  message,
  Tabs,
  Alert,
  Popover,
  Upload,
  Icon
} from 'antd';

import PTable from '../../../components/Pro/PTable';
import * as ajax from '../../../services/api';
import moment from 'moment';
import "moment/locale/zh-cn";
import InsuranceDetails from './InsuranceDetails';
import InsuranceBuy from './InsuranceBuy';
import $loading from '../../../utils/loading';
import $modal from '../../../utils/modal';
import $nModal from '../../../utils/modal/nModal';
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;
const dateFormat = 'YYYY-MM-DD';

@connect(state => ({
  global: state.global
}))
@Form.create()
/**
 * 企业保险列表页
 */
export default class InsuranceBasic extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      comInsId: '00',
      visibleBuy: false,
      forceUpdate: false,
      onlineUrl: '', //购买在线保险的url
      orederUrl: '',
      pageParm: {
        pageSize: '10',
        pageNumber: '1',
        keyword: '', //输入框的的值
        startTime: '', //开始时间
        endTime: '', //结束时间
        buyMode: '' //选择框的下拉值
      },
      keyword: '', //输入框的的值
      startTime: '', //开始时间
      endTime: '', //结束时间
      buyMode: '', //选择框的下拉值,

      claimUrl: '',
      authorizationList: [],  //授权书内容
      authorizationModal: false
    };
  }

  componentDidMount() {
    //初始化参数，修复页面切换参数不会初始化的bug！！
    this.ajaxInsPage();
    this.messageOnline();
    // 获取订单链接
    this._getOrderPageList();
    this.__getOnlineInsBlbReportPageLink();
  }
  __getOnlineInsBlbReportPageLink() {
    ajax.getOnlineInsBlbReportPageLink({}).then(res => {
      this.setState({
        claimUrl: res.data
      });
    })
  }
  //时间选择
  onChangeTime = (date, dateString) => {
    this.setState({ startTime: dateString[0], endTime: dateString[1] });
  };

  //输入框的模糊查询关键字
  inputTracknameChange = e => {
    this.setState({ keyword: e.target.value.trim() });
  };

  //购买方式，下拉框的选择
  handleChangeBuy = value => {
    this.setState({ buyMode: value });
  };

  //在线购买保险的链接生成
  messageOnline = () => {
    ajax
      .getOnlineInsBlbLink({
        comId: this.props.global.companyInfo.comId
      })
      .then(data => {
        this.setState({
          onlineUrl: data.data
        });
      });
  };
  _getOrderPageList() {
    ajax.getOnlineInsBlbOrderPageLink().then(res => {
      this.setState({ orederUrl: res.data });
    });
  }
  //重置查询条件
  resetQueryCond = () => {
    this.setState(
      {
        keyword: '', //输入框的的值
        startTime: '', //开始时间
        endTime: '', //结束时间
        buyMode: '', //选择框的下拉值
        pageParm: {
          pageSize: '10',
          pageNumber: '1',
          keyword: '', //输入框的的值
          startTime: '', //开始时间
          endTime: '', //结束时间
          buyMode: '' //选择框的下拉值
        },
        forceUpdate: true
      },
      () => {
        this.ajaxInsPage();
      }
    );
  };

  //企业保险查询分页 点击搜索
  ajaxInsPage = () => {
    const state = { ...this.state };
    const pageParm = { ...this.state.pageParm };
    pageParm.buyMode = state.buyMode;
    pageParm.startTime = state.startTime;
    pageParm.endTime = state.endTime;
    pageParm.keyword = state.keyword;
    this.setState({ pageParm, forceUpdate: true }, () => {
      this.setState({ forceUpdate: false });
    });
  };

  //查看在线保单内容
  queryInsDetail = (comInsId, blbOrderId) => {
    const link = window.open('about:blank');
    ajax
      .getOnlineInsBlbDetailLink({
        comInsId,
        orderId: blbOrderId
      })
      .then(
        data => {
          // window.open(data.data);
          link.location = data.data;
        },
        err => {
          message.warning('获取在线保险详情链接失败，', err);
        }
      );
  };
  //删除保险订单，行按钮时间
  handleDeleteList = (orderId, time) => {
    // const d = new Date();
    // const nowTime =
    //   d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
    // const lateTime = time;

    // const nowTimes = nowTime.replace(/-/g, '/');
    // const lateTimes = lateTime.replace(/-/g, '/');

    // const a = (Date.parse(nowTimes) - Date.parse(lateTimes)) / 3600 / 1000;

    // if (a <= 0) {
    //   //比较时间
    //   Modal.confirm({
    //     title: '该条保险购买记录尚在有效期内，是否确认删除该条记录',
    //     okText: '确认',
    //     cancelText: '取消',
    //     onOk: () => {
    //       ajax
    //         .comInsDeleteComInsUnderline({
    //           comInsId: orderId
    //         })
    //         .then(
    //           data => {
    //             // message.success(data.msg);
    //             this.ajaxInsPage();
    //           },
    //           err => {
    //             // message.error(err);
    //           }
    //         );
    //     },
    //     onCancel() {
    //       console.log('Cancel');
    //     }
    //   });
    // } else {
    Modal.confirm({
      title:
        '保单删除后，关联的人员也将被释放为"未投保"状态。',
      // '删除后该保险购买记录不可找回，是否确认删除该条记录。确认后删除购买记录.',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        ajax
          .comInsDeleteComInsUnderline({
            comInsId: orderId
          })
          .then(
            data => {
              message.success(data.msg);
              this.ajaxInsPage();
            },
            err => {
              message.error(err);
            }
          );
      },
      onCancel() {
        console.log('Cancel');
      }
    });
    // }
  };

  //表格渲染
  renderOrderList = () => {
    const columns = [
      {
        title: '保险产品名称',
        dataIndex: 'productName',
        key: 'productName',
        render: (text, record) => {
          return (
            <div>
              {text}
              {
                record.remark &&
                <Popover
                  content={
                    <Input.TextArea
                      defaultValue={record.remark}
                      maxLength={100}
                      placeholder="请输入产品名字备注内容"
                      style={{ width: 300 }}
                      onBlur={e => {
                        const inputText = e.target.value;
                        if (inputText && inputText != record.remark) {
                          ajax.comInsUpdateComInsRemark({
                            comInsId: record.comInsId,
                            remark: inputText
                          }).then(res => {
                            // this.ajaxInsPage();
                          });
                        }
                      }}
                    />
                    // <span
                    //   style={{
                    //     wordBreak: 'break-all',
                    //     maxWidth: '300px',
                    //     display: 'inline-block',
                    //     padding: '10px'
                    //   }}
                    // >
                    //   {record.remark}
                    // </span>
                  }
                  placement="rightTop"
                >
                  (<div
                    style={{
                      display: 'inline-block',
                      verticalAlign: 'bottom',
                      maxWidth: '54px',
                      whiteSpace: 'nowrap',
                      textOverflow: 'ellipsis',
                      overflow: 'hidden',
                      cursor: 'pointer'
                    }}
                  >
                    {record.remark}
                  </div>)
                </Popover>
              }
            </div>
          )
        }
      },
      {
        title: '保单号',
        dataIndex: 'policyNo',
        key: 'policyNo'
      },
      {
        title: '在保人数',
        dataIndex: 'perNumBl',
        key: 'perNumBl'
      },
      {
        title: '购买方式',
        dataIndex: 'buyMode_name',
        key: 'buyMode_name',
        render: (text, record) => {
          const { isBlbBuy, buyMode } = record;
          let txt = text;
          if (buyMode !== '1' && isBlbBuy === '1') {
            txt = text + '(百联保)';
          }
          return txt;
        }
      },
      {
        title: '有效期',
        dataIndex: 'effectDate',
        key: 'effectDate'
      },
      {
        title: '保险公司',
        dataIndex: 'insComName',
        key: 'insComName'
      },
      {
        title: '操作',
        render: (text, record) => {
          const { effectStartDate, effectEndDate, comInsId, isOpenAuth, authFileUrl } = record;
          
          const renderAuth = () => {
            const nowTime = moment().valueOf();
            const startTime = moment((effectStartDate + '').replace(/-/g, '/')).valueOf();
            const endTime = moment((effectEndDate + '').replace(/-/g, '/')).valueOf();
            if(!authFileUrl) {
              if(nowTime > startTime && endTime > nowTime && isOpenAuth == '1') {
                return (
                  <a onClick={() => {
                    this.setState({
                      authorizationList: [],
                      recordComInsId: comInsId,
                      authorizationModal: true
                    });
                  }}>
                    授权
                  </a>
                );
              }
            }else {
              return (
                <a
                  onClick={() => {
                    open(authFileUrl, '_blank');
                  }}
                >
                已授权
              </a>
              );
            }
          };
          return (
            <div>
              {record.buyMode === '1' ? (
                //1在线购买
                <>
                  <a
                    style={{ color: '#0f71ff', marginRight: 15 }}
                    onClick={this.queryInsDetail.bind(
                      this,
                      record.comInsId,
                      record.blbOrderId
                    )}
                  >
                    查看
                  </a>
                  {
                    record.isPastDue == '0' &&
                    <a
                      style={{ color: '#0f71ff', marginRight: 15 }}
                      onClick={() => {
                        const layout = {
                          labelCol: { span: 3 },
                          wrapperCol: { span: 21 },
                        };
                        let remark = '';
                        $nModal({
                          title: record.remark ? '修改备注' : '添加备注',
                          // content: Form.create()(<FormContent />),
                          content: (
                            <Form {...layout}>
                              <Form.Item label="备注">
                                <Input.TextArea
                                  maxLength={100}
                                  onChange={e => {
                                    remark = e.target.value;
                                  }} placeholder="请输入产品名字备注内容" />
                              </Form.Item>
                              <div style={{ color: 'red' }}>
                                <p style={{ margin: 0 }}>1、自定义备注内容可便于区分多张在线保单；</p>
                                <p style={{ margin: 0 }}>2、限制100个字符，默认显示3个字，鼠标悬浮显示全部内容，可点击修改。</p>
                              </div>
                            </Form>
                          ),
                          onOk: (close) => {
                            if (!remark) {
                              return $modal('请输入产品名字备注内容');
                            }
                            ajax.comInsUpdateComInsRemark({
                              comInsId: record.comInsId,
                              remark
                            }).then(res => {
                              this.ajaxInsPage();
                              close();
                            });
                          }
                        });
                      }}
                    >
                      备注
                      </a>
                  }
                </>
              ) : (
                  //2线下购买
                  <>
                    <a
                      style={{ color: '#0f71ff', marginRight: 15 }}
                      onClick={() => {
                        this.setState({
                          comInsId: record.comInsId
                        });
                        this.props.props.history.push({
                          pathname: `/insurancemanagement/enterpriseinsurance/insurancedetails`,
                          search: `?comInsId=${record.comInsId}`
                        });
                      }}
                    >
                      查看
                    </a>
                    <span
                      style={{
                        color: '#3399ff',
                        cursor: 'pointer',
                        marginRight: '20px'
                      }}
                      onClick={() => {
                        // this.props.props.history.push(`/enterprise/company/insurance/${record.comInsId}`);
                        this.setState({
                          comInsId: record.comInsId
                        });
                        this.props.props.history.push({
                          pathname: `/insurancemanagement/enterpriseinsurance/insurancedetails`,
                          search: `?comInsId=${record.comInsId}&edit=00`
                        });
                      }}
                    >
                      修改
                  </span>

                    {/* <span
                    style={{
                      color: '#5cadff',
                      cursor: 'pointer',
                      marginRight: '20px'
                    }}
                    onClick={() => {
                     
                    }}
                  >
                    下载保单文件
                  </span> */}
                    <span
                      style={{ color: '#ff6600', cursor: 'pointer', marginRight: 20 }}
                      onClick={this.handleDeleteList.bind(
                        this,
                        record.comInsId,
                        record.effectEndDate
                      )}
                    >
                      删除
                    </span>
                  </>
                )}

              {renderAuth()}
            </div>
          );
        }
      }
    ];

    // const tmp = this.state.listPage.map((val, i) => {
    //   const value = val;
    //   value.key = i + 1;
    //   return value;
    // });

    return (
      <PTable
        // dataSource={tmp}
        // pagination={pageInitStudent}
        columns={columns}
        url="comInsGetComInsPage"
        pageParm={this.state.pageParm}
        forceUpdate={this.state.forceUpdate}
        showTotal={total => `共搜索到${total}条记录`}
      />
    );
  };

  render() {
    // const { getFieldDecorator } = this.props.form;

    return (
      <Tabs>
        <TabPane tab="保险管理" key="1">
          <div className="Insurance">
            <Alert
              message={<div>
                <p style={{ margin: 0 }}>1、购买保险：若未购买企业保险，请进行在线购买，系统会自动关联人员信息进行投保，投保过程中有问题的，可联系在线客服进行咨询。</p>
                <p style={{ margin: 0 }}>2、新增保单：若企业已线下购买了团险或雇主险保单，请录入到系统中，并在【金融保险】-【企业保险】-【人员投保管理】中进行关联。</p>
                <p style={{ margin: 0 }}>3、企业已将线下保单录入到系统，若发生人员变动，请及时到【保险保单管理】找到对应保单点击【修改】上传批单。</p>
                <p style={{ margin: 0 }}>4、<a onClick={() => {
                  this.props.conGetPlanBook(true);
                }}>查询本省购保政策要求</a></p>
              </div>}
              type="warning"
              showIcon
              style={{ marginBottom: '15px' }}
            />
            <div className="form">
              <label>
                关键字：
                <Input
                  style={{ width: 230, marginBottom: '10px', marginRight: 16 }}
                  placeholder="保险名称/保险公司名称/保单号"
                  onChange={this.inputTracknameChange}
                  value={this.state.keyword}
                  maxLength={20}
                />
              </label>
              <label style={{ marginRight: 16, display: 'inline-block' }}>
                购买方式：
                <Select
                  style={{ width: 120, marginBottom: '10px' }}
                  value={this.state.buyMode}
                  onChange={this.handleChangeBuy}
                  placeholder="请选择"
                >
                  <Option value="">全部</Option>
                  <Option value="1">在线购买</Option>
                  <Option value="2">线下购买</Option>
                  {/* <Option value="3">线下购买(百联保)</Option> */}
                </Select>
              </label>
              <label style={{ marginRight: '16px', display: 'inline-block' }}>
                起保日期：
                <RangePicker
                  format={dateFormat}
                  onChange={this.onChangeTime}
                  style={{ marginBottom: '10px' }}
                  value={[
                    this.state.startTime === ''
                      ? null
                      : moment(this.state.startTime, dateFormat),
                    this.state.endTime === ''
                      ? null
                      : moment(this.state.endTime, dateFormat)
                  ]}
                />
              </label>
              <Button
                style={{ marginRight: 16, marginBottom: '10px' }}
                type="primary"
                onClick={this.ajaxInsPage}
              >
                搜索
              </Button>
              <Button
                style={{ marginBottom: '10px' }}
                onClick={this.resetQueryCond}
              >
                重置
              </Button>
            </div>
            <div className="btnbox">
              <Button
                type="primary"
                onClick={() => {
                  // window.open(this.state.onlineUrl);

                  this.props.props.history.push({
                    pathname:
                      '/insurancemanagement/insurance-mart',
                    search: `?url=${encodeURIComponent(this.state.onlineUrl)}`
                  });
                  this.setState({
                    visibleBuy: true
                  });
                  // this.props.props.history.push('/insurancemanagement/insurance-management');
                }}
              >
                购买在线保险
              </Button>
              <Button
                onClick={() => {
                  $modal(
                    '上传的保单数据必须真实有效、材料必须清晰可辨、人员必须一一对应！上传成功后，后台将进行人工校验，预计审核时长为7个工作日，请您耐心等待！',
                    '',
                    [
                      {
                        text: '取消'
                      },
                      {
                        text: '确定',
                        type: 'primary',
                        onPress: () => {
                          // this.props.props.history.push(`/enterprise/company/insurance/${'00'}`);
                          this.setState({
                            comInsId: '00'
                          }, () => {
                            this.props.props.history.push({
                              pathname:
                                '/insurancemanagement/enterpriseinsurance/insurancedetails',
                              search: `?comInsId=${this.state.comInsId}&edit=00`
                            });
                          });
                        }
                      }
                    ]
                  );
                }}
              >
                新增线下保险记录
              </Button>
            </div>
            {this.renderOrderList()}

            <Modal
              visible={this.state.authorizationModal}
              title="小额案件理赔授权"
              onOk={() => {
                const { authorizationList, recordComInsId } = this.state;
                const authorizationUrl = authorizationList[0] ? authorizationList[0].url : '';
                if (!authorizationUrl) {
                  return $modal('请上传授权书');
                }
                ajax.insComInsSaveAuthFile({
                  comInsId: recordComInsId,
                  authFileUrl: authorizationUrl
                }).then(res => {
                  $modal('操作成功', '', null, 'success');
                  this.ajaxInsPage();
                  this.setState({ authorizationModal: false });
                });
              }}
              onCancel={() => {this.setState({authorizationModal: false})}}
            >
              <section>
                <p>通过平台保安的可享受平台专属理赔快速通道服务，企业可授权实际出险员工办理保险理赔的全部十一（包括但不限于理赔申请、提供理赔资料、收取理赔款等，但不好含放弃索赔权益），出险员工签名替代公司签章：</p>
                <a href="/files/关于雇主责任险小额理赔案件的授权书.docx" target="_blank">点击下载《关于雇主责任险小额理赔案件授权书》</a>
                <div style={{ marginTop: 15 }}>
                  <span><em style={{ color: '#D9001B' }}>*</em>授权书：</span>
                  <Upload
                    showUploadList={true}
                    fileList={this.state.authorizationList}
                    style={{ display: 'inline-block' }}
                    beforeUpload={(file) => {
                      let canUpload = true;
                      if (!(file.name + '').toLocaleLowerCase().match(/(\.docx)|(\.doc)/)) {
                        message.error(`请上传拓展名为.docx的文件!`);
                        canUpload = false;
                      }
                      return canUpload;
                    }}
                    onRemove={() => {
                      this.setState({ authorizationList: [] });
                    }}
                    customRequest={({ file }) => {
                      const formData = new FormData();
                      formData.append('xfile', file);
                      $loading.open('文件导入中,请稍后。。。');
                      ajax.publicCommonFileUploadFile(formData, false).then(res => {
                        $loading.close();
                        // message.success('上传成功');
                        file.url = res.data;
                        file.status = 'done';
                        this.setState({
                          authorizationList: [file]
                        });
                      }).catch(ex => {
                        $loading.close();
                        console.log(ex);
                      });
                    }}
                  >
                    <Button
                      style={{ marginLeft: 10 }}
                    >
                      <Icon type="upload" />上传文件
              </Button>
                  </Upload>
                </div>

                <div style={{ color: '#F59A23', marginTop: 15 }}>
                  <span>授权成功激活该保单在保人员百宝盾APP理赔权限；</span>
                  <br />
                  <span>出险时间在保单有效期内的索赔案件均使用本授权。</span>

                  {/* <p style={{ color: '#D9001B', padding: 0, marginTop: 15 }}>有数据无法识别，请下载失败文件查看，调整后重新上传。
                      <a>下载失败文件</a>
                  </p> */}
                </div>
              </section>
            </Modal>
          </div>
        </TabPane>
        <TabPane tab="在线订单查询" key="2">
          {this.state.orederUrl && <iframe
            title="购买在线保险"
            src={this.state.orederUrl}
            style={{ height: 'calc(100vh - 225px)' }}
            width="100%"
            frameBorder="0"
            allowFullScreen={true}
            allowtransparency="true"
          >
            您的浏览器不支持iframe，请升级
          </iframe>}
        </TabPane>
        <TabPane tab="理赔记录" key="3">
          {this.state.claimUrl && <iframe
            title="理赔记录"
            src={this.state.claimUrl}
            style={{ height: 'calc(100vh - 225px)' }}
            width="100%"
            frameBorder="0"
            allowFullScreen={true}
            allowtransparency="true"
          >
            您的浏览器不支持iframe，请升级
          </iframe>}
        </TabPane>
      </Tabs>
    );
  }
}


