import React, { Component } from 'react';
import { Button, Card, Breadcrumb } from 'antd';
import { Link } from "dva/router";
import { connect } from 'dva';
import Result from '../../../components/Result';
import PageHeaderLayout from '../../../layouts/PageHeaderLayout';
import {
  getOnlineInsBlbLink, //STATUS=0
  enterpriseInsComInsGetOnlineInsBlbPreservationLink //STATUS=1
} from "../../../services/api";
// import axios from 'axios'
// import bcx_utils from '../../../common/bcx_utils';

@connect()

export default class TaskSuccess extends Component {
  state = {
    url: '',//保险连接
    status: '2',//表示需要投保的状态，0为全部人员需要投保，1为部分人员需要投保，2为全部人员已经投保
    extra: null,//存储提示语
    comTaskId: "",
    personName: []
  }

  componentWillMount = () => {
    console.log('props', this.props);
    let securityDatas
      = this.props.location &&
      this.props.location.state &&
      this.props.location.state.securityDatas;
      console.log(securityDatas);
      //刷新头部的消息通知
      this.props.dispatch({
        type: 'global/fetchNotices'
      });
    this.setSecurityDatas(securityDatas);
  }

  //计算重复人员数
  countRepeat = (conflict) => {
    if (conflict === "") {
      return false;
    }
    const len = conflict.split(",").length;
    if (len == 0) {
      return false;
    }
    const peoples = conflict.replace(",", "、");

    const tip = `有${len}个人员有重复的固定班：${peoples}，未加入本驻勤的成员名单，请去调整班次后，再加入。`

    return tip;
  }

  //设置是否提示语
  setSecurityDatas = (securityDatas) => {
    if (!securityDatas) {
      return;
    }
    const { taskPerInsMode, conflict, status, comTaskId } = securityDatas;//判断是否需要投保

    this.setState({ comTaskId });

    //提示语 预设
    let extra = [];

    let newState = "2";

    //判断是否有被重复安排的人员，并在 extra 插入提示语。
    const conflictArr = this.countRepeat(conflict.slice(1, conflict.length - 1));
    if (conflictArr) {
      extra.push(conflictArr);
    }

    //需要投保
    if (taskPerInsMode === "1") {
      let proLocation = this.props.location && this.props.location.state && this.props.location.state.personName;
      this.setState({
        personName: proLocation
      });
      this.setState({
        status
      });
      newState = securityDatas.status;

      this.setState({ comTaskId });
      if (status === '0' || status === '1') {
        //为全部人员需要投保
        if (status === '0') {
          let blbProductCode = securityDatas.blbProductCode || '';
          blbProductCode !== '' && this.getOnlineInsBlbLink({ blbProductCode });
        }
        //全部人员已经投保
        if (status === '1') {
          let orderId = securityDatas.blbOrderId || '';
          let perIds = securityDatas.noInsId || '';
          orderId !== '' && perIds !== '' && this.getOnlineInsBlbPreservationLink({ orderId, perIds, reviseType: '1' });
        }

        let detail = securityDatas.detail || '';
        if (detail.length > 30) {
          detail = detail.substring(1, 30) + '...';
        }
        // let noInsSize = securityDatas.noInsSize || '';
        // let str = `有${noInsSize}个驻勤成员未购买保险：${detail}执行驻勤可能存在风险，请点击【立即投保】购买保险保障`;
        if(proLocation.length > 0){
          const str = `有<span style=color:red>${proLocation.length}</span>个驻勤成员：<span style=color:red>${proLocation.join('、')}</span>未购买保险,执行驻勤可能存在风险，请点击【立即投保】购买保险保障`;
          extra.push(str);
        }
      }
    }

    extra = extra.concat([
      "请点击【人员排班】，对驻勤参与成员进行排班安排。",
      "请点击【查看驻勤】，查看刚创建好的驻勤详情。",
      "请点击【继续创建】，创建新的驻勤。",
    ]);

    //插入序号
    extra = extra.map((val, key) => {
      return key + 1 + "、 " + val;
    });

    extra = "操作提示：<br/>" + extra.join("<br/>");

    extra = <div className="pie-stat" dangerouslySetInnerHTML={{ __html: extra }} />;

    this.setState({ extra, state: newState });

  }

  //保全链接生成
  getOnlineInsBlbPreservationLink = (value) => {
    enterpriseInsComInsGetOnlineInsBlbPreservationLink(value)
      .then(response => {
        console.log(response, "response-保全链接生成-getOnlineInsBlbPreservationLink");
        let url = response.data; //返回的url
        console.log('保全信息的url');
        this.setState({ url });
      }, err => {
        console.log('err', err);
      });
  }
  //获取在线保险链接
  getOnlineInsBlbLink = (value) => {
    getOnlineInsBlbLink(value).then(response => {
      console.log(response, "response-获取在线保险链接-getOnlineInsBlbLink");
      let url = response.data; //返回的url
      this.setState({ url });
    }, err => {
      console.log(err, "err-获取在线保险链接-getOnlineInsBlbLink");
    });
  };
  createAttendance = () => {
    this
      .props
      .history
      .push(`/taskmanager/tasklist/taskDetail?id=${this.state.comTaskId + ""}&cursor=4`);
  }
  checkTask = () => {
    this
      .props
      .history
      .push(`/taskmanager/tasklist/taskDetail?id=${this.state.comTaskId + ""}&cursor=1`);
  }
  createTask = () => {
    this
      .props
      .history
      .push({ pathname: `/taskmanager/tasklist/newtask` });
  }

  render() {
    console.log(this.state.status);
    console.log(this.state.status === '2');
    console.log(this.state.personName);
    console.log(this.state.personName.length === 0);
    const actions_status2 = (
      <div>
        <Button onClick={this.createAttendance} type="primary">人员排班</Button>
        <Button onClick={this.checkTask}>查看驻勤</Button>
        <Button onClick={this.createTask}>继续创建</Button>
      </div>
    );
    const actions_status01 = (
      <div>
        {/* <Button type="primary">
          <a href={this.state.url || '#'}>立即投保</a>
        </Button> */}
        <Button type="primary">
          <a onClick={() => {
            this.props.history.push(
              `/insurancemanagement/enterpriseinsurance`
            );
          }}>立即投保</a>
        </Button>
        <Button onClick={this.createAttendance} type="primary">人员排班</Button>
        <Button onClick={this.checkTask}>查看驻勤</Button>
        <Button onClick={this.createTask}>继续创建</Button>
      </div>
    );

    return (
      <Card bordered={false}>
        <Breadcrumb>
          <Breadcrumb.Item>
            <Link to="/taskmanager/tasklist">
              驻勤列表
            </Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item>创建驻勤流程</Breadcrumb.Item>
        </Breadcrumb>

        <Result
          type="success"
          title="发布成功"
          description="驻勤已发布成功，并已通知给相关人员。您还可以进行以下操作："
          extra={this.state.extra}
          actions={this.state.status === '2' || this.state.personName.length === 0 ? actions_status2 : actions_status01}
          style={{
            marginTop: 48,
            marginBottom: 16
          }} />
      </Card>
    );
  }

}
