import React, { PureComponent } from "react";
import {
  Button,
  Avatar,
  Timeline,
  Row,
  Col,
  Drawer,
  Popover,
  Modal
} from "antd";
import "./ApprovalList.less";
import {
  getApproveAttendLeaveApply,
  getApproveAttendOvertimeApply,
  getApproveAttendRemedyApply,
  getApproveTaskLeaveApply,
  getApproveTaskRemedyApply,
  getTaskAdjustDetail
} from "../../../services/api";

const attendanceLeave = ["请假类型", "开始时间", "结束时间", "时长(小时)"]; //考勤请假
const attendanceSupplement = ["补卡日期", "补卡轮次", "补卡类型"]; //考勤补卡
const tackLeave = ["所属任务","请假类型","开始时间","结束时间","时长(小时)"]; //任务请假
const tackSupplement = ["所属任务", "补卡日期", "补卡轮次", "补卡类型"]; //任务补卡
const overtime = ["开始时间", "结束时间", "时长(小时)"]; //加班
const substitite = ["所属任务", "调班日期", "调班班次"]; //代班

//审批状态图标
const approvedIcon = require("../../../assets/images/approved.png"); //审批通过
const approvingIcon = require("../../../assets/images/approving.png"); //审批中
const notapprovedIcon = require("../../../assets/images/notapproved.png"); //审批不通过
const measuredbackIcon = require("../../../assets/images/measuredback.png"); //已撤销

export default class EditExamination extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      openEdit: this.props.visible,
      approvalValue: [],
      approvalInfo: "", //审批详情数据
      approveType: "", //审批类型
      processData: [], //审批流程的数据
      approveStatus: "", //审批状态 0、审批中 1、审批通过 2、审批不通过 3、已撤销
      resonModalVisible: false, //审批事由图片预览
      resonPhotoUrl: "", //点击对应的事由图片
      ccList: [],  //抄送列表
      acceptPerList: [] //代班列表
    };
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      openEdit: nextProps.visible,
      approveType: nextProps.approveType,
      approveStatus: nextProps.approveStatus
    });
    
    if (this.state.openEdit !== nextProps.visible) {
      if (nextProps.approvalId === 0 || nextProps.approvalId === undefined) { 
        return;
        // this.setState({
        //   approvalValue: []
        // });
      }else {
        console.log(nextProps);
        this.possDate(nextProps.approvalId, nextProps.approveType);
      }
    }
  }

  // componentWillUnmount(){
  //   this.setState = (state,callback)=>{
  //     return;
  //   };
  // }
  possDate = (approvalId, approveType) => {
    if (approveType === "11") {
      //考勤请假
      this.renderDate(
        getApproveAttendLeaveApply,
        approvalId,
        attendanceLeave,
        "leaveType",
        "startTime",
        "endTime",
        "leaveLongTime"
      );
    } else if (approveType === "15") {
      //考勤补卡
      this.renderDate(
        getApproveAttendRemedyApply,
        approvalId,
        attendanceSupplement,
        "dates",
        "rotationContent",
        "remedyMatter"
      );
    } else if (approveType === "51") {
      //任务请假
      this.renderDate(
        getApproveTaskLeaveApply,
        approvalId,
        tackLeave,
        "taskName",
        "leaveType",
        "startTime",
        "endTime",
        "leaveLongTime"
      );
    } else if (approveType === "52") {
      //任务补卡
      this.renderDate(
        getApproveTaskRemedyApply,
        approvalId,
        tackSupplement,
        "taskName",
        "dates",
        "rotationContent",
        "remedyMatter"
      );
    } else if (approveType === "14") {
      //加班
      this.renderDate(
        getApproveAttendOvertimeApply,
        approvalId,
        overtime,
        "startTime",
        "endTime",
        "overtime"
      );
    } else if(approveType === "53") { //任务代班
      this.renderDate(
        getTaskAdjustDetail,
        approvalId,
        substitite,
        "taskName",
        "dates",
        "shiftName"
      );
      // getTaskAdjustDetail({ approveApplyId: approvalId }).then(response => {
      //   // const approvalValue = ["所属任务", "调班日期", "调班班次"]
      //   const approvalValue = [
      //     { title: '所属任务', value: response.data}
      //   ]
      //   this.setState({
      //     approvalInfo: response.data.taskAdjustDetail,
      //     processData: response.data.processList,
      //     ccList: response.data.ccList
      //   });
      // });
    }else {
      //清除上一个成功留下的数据
      if (this.state.approvalValue !== "") {
        this.setState({
          approvalInfo: ""
        });
        const approvalValue = [...this.state.approvalValue];
        approvalValue.map(item => {
          item.value = "";
        });
        this.setState({
          approvalValue,
          processData: []
        });
      }
    }
  };

  //获取审批详情的数据
  renderDate = (
    getApproveDetailData,
    approvalId,
    list,
    data1,
    data2,
    data3,
    data4 = "",
    data5 = ""
  ) => {
    const approvalInfoData = [];
    list.map(item => {
      const obj = { title: item, value: "" };
      approvalInfoData.push(obj);
    });
    getApproveDetailData({ approveApplyId: approvalId }).then(
      response => {
        this.setState({
          approvalInfo: response.data,
          processData: response.data.aalpList?response.data.aalpList:response.data.acceptPerList,
          ccList: response.data.ccList?response.data.ccList: [],
          acceptPerList: response.data.acceptPerList?response.data.acceptPerList: []
        });
        approvalInfoData[0].value = response.data[data1];
        approvalInfoData[1].value = response.data[data2];
        approvalInfoData[2].value = response.data[data3];
        if (data4 !== "") {
          approvalInfoData[3].value = response.data[data4];
        }
        if (data5 !== "") {
          approvalInfoData[4].value = response.data[data5];
        }
        this.setState({
          approvalValue: approvalInfoData
        });
      },
      err => {
        console.log("获取审批详情数据失败" + err);
        //清除上一个成功留下的数据
        if (this.state.approvalValue !== "") {
          this.setState({
            approvalInfo: ""
          });
          const approvalValue = [...this.state.approvalValue];
          approvalValue.map(item => {
            item.value = "";
          });
          this.setState({
            approvalValue,
            processData: [],
            ccList: [],
            acceptPerList: []
          });
        }
      }
    );
  };

  //审批信息（事由字段以上的数据）
  approveInfomation = () => {
    return this.state.approvalValue.map((item, index) => {
      //所属任务是占一行
      if (item.title === "所属任务") {
        return (
          <Col span={24} key={index}>
            <Col span={4}>{item.title}：</Col>
            <Col span={20}>{item.value}</Col>
          </Col>
        );
      } else {
        return (
          <Col span={12} key={index}>
            <Col span={8}>{item.title}：</Col>
            <Col span={16}>{item.value}</Col>
          </Col>
        );
      }
    });
  };

  //审批信息中事由的图片
  resonPhoto = pictureUrl => {
    if (pictureUrl) {
      const pictureUrlArray = pictureUrl.split(",");
      return pictureUrlArray.map((item, index) => {
        return (
          <Col span={4} key={index}>
            <Avatar
              shape="square"
              size={55}
              src={item}
              style={{
                border: "2px solid rgb(240, 240, 243)",
                cursor: "pointer"
              }}
              onClick={() => {
                this.setState({
                  resonModalVisible: true,
                  resonPhotoUrl: item
                });
              }}
            />
          </Col>
        );
      });
    }
  };

  //审批信息中考勤补卡类型下的证明人字段
  witness = reterenceList => {
    return (
      <Col span={24}>
        <Col span={4}>证明人：</Col>
        <Col span={20}>
          {reterenceList
            ? reterenceList.map((item, index) => {
                return (
                  <Col span={4} key={index}>
                    <Avatar size={40} src={item.portraitUrl} icon="user" />
                    <Popover content={item.name} trigger="hover">
                      <p
                        style={{
                          width: "53px",
                          textAlign: "center",
                          whiteSpace: "nowrap",
                          textOverflow: "ellipsis",
                          overflow: "hidden",
                          marginLeft: "-5px"
                        }}
                      >
                        {item.name}
                      </p>
                    </Popover>
                  </Col>
                );
              })
            : ""}
        </Col>
      </Col>
    );
  };

  //审批流程的时间轴
  timeLine = () => {
    const colorText = ["#008000", "#FF9900", "#e55858", "#999999", "#fff"]; //同意，审批中，不同意，撤销，默认的颜色
    const backgroundColor = ["#E6FEE2", "#FFEEF0", "#FFEEF0", "#e0dfdf", "fff"]; //同意，审批中，不同意，撤销，白色
    return this.state.processData.map((item, index) => {
      //portraitUrl 是头像图片
      //pictureUrl 是内容图片
      const pictureUrl =
        item.pictureUrl? item.pictureUrl.split(",") : '';
      return (
        <Timeline.Item color="blue" key={index}>
          <span className="title">{item.stepName}</span>
          <Row className="title-content">
            <Col
              span={11}
              style={{
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap"
              }}
            >
              <Avatar
                size={40}
                style={{ marginRight: "10px" }}
                src={item.portraitUrl}
                icon="user"
              />
              <Popover content={item.name} trigger="hover">
                <span>{item.name}</span>
              </Popover>
            </Col>
            <Col span={5} style={{ lineHeight: "40px" }}>
              <span
                className="statusType"
                style={{
                  background:
                    index === 0
                      ? ""
                      : item.approvalAction === "同意"
                      ? backgroundColor[0]
                      : item.approvalAction === "审批中"
                      ? backgroundColor[1]
                      : item.approvalAction === "不同意"
                      ? backgroundColor[2]
                      : item.approvalAction === "撤销"
                      ? backgroundColor[3]
                      : item.approvalAction === null ? '':'',
                  color:
                    item.approvalAction === "同意"
                      ? colorText[0]
                      : item.approvalAction === "审批中"
                      ? colorText[1]
                      : item.approvalAction === "不同意"
                      ? colorText[2]
                      : item.approvalAction === "撤销"
                      ? colorText[3]
                      : colorText[4]
                }}
              >
                {/* 前端增加审批中状态 */}
                {index === 0 ? (
                  ""
                ) : item.approvalAction !== "" ? (
                  item.approvalAction
                ) : this.state.processData[index - 1].approvalAction !== "" &&
                  this.state.processData[index - 1].approvalAction !==
                    "不同意" &&
                  this.state.processData[index - 1].approvalAction !==
                    "撤销" ? (
                  <span
                    className="statusType"
                    style={{ color: colorText[1], background: "#FFEEF0" }}
                  >
                    审批中
                  </span>
                ) : (
                  ""
                )}
              </span>
            </Col>
            <Col span={8} style={{ lineHeight: "40px" }}>
              {/* 第一条数据跟撤销的字段请求createTime */}
              {index === 0
                ? item.createTime
                : item.approvalAction === "撤销"
                ? item.createTime
                : item.updateTime}
            </Col>
          </Row>
          <div className="content">
            <p>{item.approveContent}</p>
            <p>
              {pictureUrl !== ''
                ? pictureUrl.map((data, index) => {
                    return (
                      <Avatar
                        shape="square"
                        size={55}
                        style={{
                          marginRight: "10px",
                          border: "2px solid rgb(240, 240, 243)",
                          cursor: "pointer"
                        }}
                        src={data}
                        key={index}
                        onClick={() => {
                          this.setState({
                            resonModalVisible: true,
                            resonPhotoUrl: data
                          });
                        }}
                      />
                    );
                  })
                : ""}
            </p>
          </div>
        </Timeline.Item>
      );
    });
  };

  hideModal = () => {
    this.setState({
      openEdit: false
    });
  };

  render() {
    const { approvalInfo, approveType, approveStatus } = this.state;
    // const color = ["#FF9900", "#008000", "#FE5500", "#999999"]; //审核中，审核通过，审核不通过，撤销
    return (
      <div>
        <Drawer
          overlayColor="rgba(0, 0, 0,0)"
          placement="right"
          visible={this.state.openEdit}
          title="审批详情"
          width={600}
          zIndex={11}
          destroyOnClose
          closable={false}
          onChange={openEdit => {
            this.props.onChange(openEdit);
            this.setState({ openEdit });
          }}
          onClose={() => {
            this.setState({
              openEdit: false
            });
          }}
        >
          <div className="examination-detail">
            <div style={{ position: "relative" }}>
              <img
                className="approvalStatus"
                style={{ width: "100px", height: "85px" }}
                src={
                  approveStatus === "0"
                    ? approvingIcon
                    : approveStatus === "1"
                    ? approvedIcon
                    : approveStatus === "2"
                    ? notapprovedIcon
                    : measuredbackIcon
                }
              />

              <h3>审批信息</h3>
              <div className="examination-info">
                <Row>
                  <Col span={12}>
                    <Col span={8}>审批单号：</Col>
                    <Col span={16}>{approvalInfo.approveApplyId}</Col>
                  </Col>
                  <Col span={12}>
                    <Col span={8}>发起人：</Col>
                    <Col span={16}>{approvalInfo.name}</Col>
                  </Col>
                  {
                    approvalInfo.approveGroupName&&<Col span={12}>
                      <Col span={8}>审批组：</Col>
                      <Col span={16}>{approvalInfo.approveGroupName}</Col>
                    </Col>
                  }
                  {
                    approvalInfo.approveType&&<Col span={12}>
                      <Col span={8}>审批类型：</Col>
                      <Col span={16}>{approvalInfo.approveType}</Col>
                    </Col>
                  }
                  
                  {this.approveInfomation()}
                  {/* 事由字段 */}
                  <Col span={24}>
                    <Col span={4}>事由：</Col>
                    <Col span={20}>
                      <div>
                        <p>{approvalInfo.reason}</p>
                        {this.resonPhoto(approvalInfo.pictureUrl)}
                      </div>
                    </Col>
                  </Col>
                  {/* 考勤补卡多一个证明人样式*/}
                  {approveType === "15"
                    ? this.witness(approvalInfo.aarrList)
                    : ""}
                </Row>
              </div>
              <h3>审批流程</h3>
              <Timeline>{this.timeLine()}</Timeline>
              {this.state.ccList.length>0&&<h3>抄送</h3>}
              <ul style={{marginBottom: 40, listStyle: 'none', overflow: 'hidden'}}>
                {this.state.ccList.map(item => {
                  return (
                    <li style={{width: '25%',textAlign: 'center',  float: 'left'}}>
                    <Avatar
                      size={40}
                      src={item.portraitUrl}
                      style={{ marginRight: "10px" }}
                      icon="user"
                    />
                    <p>{item.name}</p>
                  </li>
                  );
                })}
              </ul>
              {this.state.acceptPerList.length>0&&<h3>调给谁</h3>}
              <ul style={{marginBottom: 40, listStyle: 'none', overflow: 'hidden'}}>
                {this.state.acceptPerList.map(item => {
                  return (
                    <li style={{width: '25%',textAlign: 'center',  float: 'left'}}>
                    <Avatar
                      size={40}
                      src={item.portraitUrl}
                      style={{ marginRight: "10px" }}
                      icon="user"
                    />
                    <p>{item.name}</p>
                  </li>
                  );
                })}
              </ul>
            </div>
            <div className="footer">
              <Button onClick={this.hideModal} style={{ marginRight: 8 }}>
                返回
              </Button>
            </div>
          </div>
        </Drawer>
        <Modal
          visible={this.state.resonModalVisible}
          onCancel={() => {
            this.setState({ resonModalVisible: false });
          }}
          footer={null}
          width={650}
        >
          <img
            src={this.state.resonPhotoUrl}
            style={{ width: "600px", height: "500px" }}
          />
        </Modal>
      </div>
    );
  }
}
