import React, { Component } from "react";
import { connect } from "dva";

import { Link } from 'dva/router';
import { gup } from '../../../utils/utils';
import {
  Alert,
  Form,
  Row,
  Col,
  Input,
  Table,
  message,
  Button,
  Modal,
  Checkbox,
  Upload,
  Icon,
  Tabs,
  Breadcrumb,
  Radio,
  Divider,
  Select
} from "antd";
import { formItemLayout, formLayout, formLayout1, formLayoutTable, formLayoutTable2, formLayout3 } from './formLayout';
import PSelect from '../../../components/Pro/PSelect';
import PFromUpload from '../../../components/Pro/PFromUpload';
import BTable from '../../../components/Pro/BTable';
import declare from '../../../utils/hoc/declare';
import ImageFormItem from './imageFormItem';
import { contract, infoReview, internReview } from "./columns";
import { qualify_applyInfo, qualify_selectProofList } from "../../../services/bkt/qualify"
import { trainInternInternLinePage, trainGradeApplyInfo, trainGradeApplyInfoCheck } from "../../../services/bkt/grade"
import { getBayBaseInfo, publicCommonFileFilePreview } from "../../../services/api"

const { TabPane } = Tabs;
@connect(state => ({
  profile: state.profile
}))
@Form.create()
@declare
export default class CertificateMessage extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      tab: '1',
      contractColumns: [],  //合同信息
      infoReviewColumns: [], //学习记录
      internReviewColumns: [], //实习记录
      checkStatus: 1,
      internModel: false,
      checkContent: "", //不合格原因
      info: {},
      selectProofList: [],  //学习记录列表
      internList: [], //实习记录列表
      internContent: "", //实习记录不合格原因
      personApplyId: this.props.history.location.query ? `${this.props.history.location.query.personApplyId}` : "",
      checkPerName: "",
      pageParm: { //实习记录表格参数
        pageSize: '10',
        pageNumber: '1',
      },
    };
  }

  componentWillMount() {
    this.__getDetailInfo(this.state.personApplyId)
    this.__getSelectProofList(this.state.personApplyId)
    this._getUserInfo()
    const tab = gup('tab');
    if (tab) {
      this.setState({
        tab
      });
    }
  }
  componentDidMount() {
    const contractColumns = contract.call(this);
    const infoReviewColumns = infoReview.call(this);
    const internReviewColumns = internReview.call(this);
    this.setState({
      contractColumns,
      infoReviewColumns,
      internReviewColumns
    });

  }
  // 获取操作人信息
  _getUserInfo = () => {
    getBayBaseInfo().then(res => {
      console.log(res)
      this.setState({
        checkPerName: res.data.name
      });
    })
  }
  //获取详情
  __getDetailInfo = (personApplyId) => {
    let { pageParm } = this.state
    trainGradeApplyInfo({ data: { personApplyId } }).then(res => {
      this.setState({
        info: res.data,
        pageParm: { ...pageParm, uid: res.data.uid }
      });
      this._getInternLine(res.data.uid)
    });
  }
  //获取学习记录
  __getSelectProofList = (personApplyId) => {
    qualify_selectProofList({ data: { personApplyId } }).then(res => {
      res.data.forEach((item, index) => {
        item.checkStatus = 1;
        item.number = index + 1;
      })
      this.setState({
        selectProofList: res.data
      })
    })
  }
  //获取实习记录
  _getInternLine = (uid) => {
    let page = {
      pageSize: '1000',
      pageNumber: '1',
    }
    trainInternInternLinePage({ ...page, data: { uid } }).then(res => {
      res.data.data.forEach(item => {
        item.checkStatus = "1"
        item.internContent = ""
      })
      this.setState({
        internList: res.data.data
      })
    });
  }
  //是否合格
  checkQualified = (e) => {
    if (e.target.value === 1) {
      this.setState({
        checkStatus: 1,
        checkContent: ""
      });
    } else {
      this.setState({
        checkStatus: 2
      });
    }
  }
  //学习记录是否合格
  handleProofListQualified = (record, e) => {
    const { selectProofList } = this.state
    selectProofList.forEach(item => {
      if (item.trackUserProofId === record.trackUserProofId) {
        item.checkStatus = e;
      }
    })
    this.setState({
      selectProofList
    })
  }
  //不合格理由
  handleCheckContent = (e) => {
    this.setState({
      checkContent: e.target.value
    });
  }
  //实习记录是否合格
  handleInternQualified = (record, e) => {
    const { internList } = this.state
    internList.forEach(item => {
      if (item.personInternLineId === record.personInternLineId) {
        item.checkStatus = e;
        item.internContent = "";
      }
    })
    if (e === "1") {
      this.setState({
        internModel: false,
        personInternLineId: record.personInternLineId,
        internList,
      })
    } else {
      this.setState({
        internModel: true,
        personInternLineId: record.personInternLineId,
        internList,
      })
    }
  }
  //修改不合格原因
  editInternContent = (internContent, record) => {
    this.setState({
      internModel: true,
      personInternLineId: record.personInternLineId,
      internContent,
    })
  }

  handleOk = () => {
    const { personInternLineId, internContent, internList } = this.state
    if (internContent == "") {
      message.error("请输入不合格原因");
      return;
    }
    internList.forEach(item => {
      if (item.personInternLineId === personInternLineId) {
        item.internContent = internContent
      }
    })
    this.setState({
      internList,
      internContent: "",
      internModel: false
    })
  }
  handleOnCancel = () => {
    const { personInternLineId, internContent, internList } = this.state
    let internContent2 = ""
    internList.forEach(item => {
      if (item.personInternLineId === personInternLineId) {
        if (!item.internContent && item.checkStatus === "2") {
          item.checkStatus = "1";
        }
      }
    })
    this.setState({
      internList,
      internContent: "",
      internModel: false
    })
    this.setState({ internModel: false, internContent: "" })
  }
  //提交
  __submit = () => {
    const { isQualified, checkContent, personApplyId, info, checkPerName, selectProofList, checkStatus, internList } = this.state
    if (checkStatus === 2 && !checkContent) {
      message.error("请填写不合格原因");
      return;
    }
    //学习记录的数据
    let data = selectProofList.map(item => {
      return {
        personApplyId,
        checkPerName,
        productTypeCode: 3,
        objectId: item.trackUserProofId,
        checkItem: 2,
        checkStatus: item.checkStatus,
        checkContent: ""
      }
    })
    //实习记录
    let internData = internList.map(item => {
      return {
        personApplyId,
        checkPerName,
        productTypeCode: 3,
        objectId: item.personInternLineId,
        checkItem: 3,
        checkStatus: item.checkStatus,
        checkContent: item.internContent
      }
    })
    //基本信息数据
    let data1 = {
      personApplyId,
      checkPerName,
      productTypeCode: 3,
      checkItem: 1,
      objectId: personApplyId,
      checkStatus: checkStatus,
      checkContent: checkContent
    }
    data.push(data1)
    data.push(...internData)
    console.log(data)
    trainGradeApplyInfoCheck({ data }).then(res => {
      if (res.retType === "0") {
        message.success("提交成功")
        this.props.history.push("/spotCheck/gradeRecord")
      }
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { state } = this
    const { info, selectProofList, personApplyId } = this.state
    const contractDataSource = []
    if (info.contractName) {
      contractDataSource.push(info)
    }

    return (
      <div style={{ paddingTop: '10px' }}>
        <Breadcrumb style={{ margin: '16px 0 8px 24px' }}>
          <Breadcrumb.Item>
            <Link to="/spotCheck/gradeMessage">保安员等级证考培信息抽查记录</Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item>信息审查</Breadcrumb.Item>
        </Breadcrumb>
        {/* <Tabs
          tabBarStyle={{ marginLeft: 24, marginRight: 24 }}
          defaultActiveKey={this.state.tab}
        >
          <TabPane forceRender
            tab={`保安员资格证考培信息抽查记录`}
            key="1"
          > */}
        <Form style={{ paddingRight: 15 }}>
          <div className="basic_container">
            {
              info.checkFailContent ?
                <>
                  <Divider style={{ paddingLeft: "15px" }} orientation="left">
                    <h3 style={{ fontWeight: 800, fontSize: "20px" }}>历史审核意见</h3>
                  </Divider>
                  <Row gutter={16}>
                    <Col span={21}>
                      <div style={{ marginLeft: "82px", fontSize: "16px", marginBottom: "30px", color: "red" }}>
                        {
                          info.checkFailContent ?
                            info.checkFailContent.map(item => {
                              return (
                                <div style={{ display: "flex" }}>
                                  <p style={{ whiteSpace: "nowrap", marginRight: "5px" }}>{item.date} | </p>
                                  <p>{item.content}</p>
                                </div>
                              )
                            }) : ""
                        }
                      </div>
                    </Col>
                  </Row>
                </> : ""
            }
            <Divider style={{ paddingLeft: "15px" }} orientation="left">
              <h3 style={{ fontWeight: 800, fontSize: "20px" }}>基本信息</h3>
            </Divider>
            <Row gutter={16}>
              <Col span={7}>
                <Form.Item {...formItemLayout} label="姓名">
                  {getFieldDecorator('fullname', {
                    initialValue: info.fullname
                  })(< Input placeholder="" maxLength={30} disabled={true} />
                  )}
                </Form.Item>
              </Col>
              <Col span={7}>
                <Form.Item {...formItemLayout} label="身份证号码">
                  {getFieldDecorator('identitynumber', {
                    initialValue: info.identitynumber
                  })(<Input placeholder="" maxLength={30} disabled={true} />)}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={7} >
                <Form.Item {...formItemLayout} label="手机号码">
                  {getFieldDecorator('mobile', {
                    initialValue: info.mobile
                  })(<Input placeholder="" maxLength={30} disabled={true} />)}
                </Form.Item>
              </Col>
              <Col span={7}>
                <Form.Item {...formItemLayout} label="户籍类型">
                  {getFieldDecorator('residentType', {
                    initialValue: info.residentType
                  })(<PSelect disabled style={{ width: '100%' }} type="residentType" />)}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={7} >
                <Form.Item {...formItemLayout} label="户籍所在地类型">
                  {getFieldDecorator('residentPlaceType', {
                    initialValue: info.residentPlaceType
                  })(<PSelect disabled style={{ width: '100%' }} type="residentPlaceType" />)}
                </Form.Item>
              </Col>
              <Col span={7} >
                <Form.Item {...formItemLayout} label="户籍地址">
                  {getFieldDecorator('householdAddress', {
                    initialValue: info.householdAddress
                  })(<Input.TextArea placeholder="" disabled={true} autosize={{ minRows: 1, maxRows: 3 }} />)}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={7}>
                <Form.Item {...formItemLayout} label="现住地址">
                  {getFieldDecorator('actualAddress', {
                    initialValue: info.actualAddress
                  })(<Input.TextArea placeholder="" disabled={true} autosize={{ minRows: 1, maxRows: 3 }} />)}
                </Form.Item>
              </Col>
              <Col span={7}>
                <Form.Item {...formItemLayout} label="本职业工作年限">
                  {getFieldDecorator('workYear', {
                    initialValue: info.workYear+"年"
                  })(<Input placeholder="" maxLength={30} disabled={true} />)}
                </Form.Item>
              </Col>
            </Row>
            <Divider style={{ paddingLeft: "15px" }} orientation="left">
              <h3 style={{ fontWeight: 800, fontSize: "20px" }}>证书证明照片信息</h3>
            </Divider>
            <Row gutter={16}>
              <Col span={8}>
                <Form.Item style={{ marginLeft: "150px" }} >
                  二寸免冠照
                {info.avatar ?
                    getFieldDecorator("avatar", {
                      initialValue: info.avatar
                    })(
                      <PFromUpload
                        disabled={true}
                        size={1}
                        disabled
                      />
                    ) : <div style={{ width: "104px", height: "104px", border: "1px dashed #ccc", paddingTop: "30px", textAlign: "center" }}>暂无</div>
                  }
                </Form.Item>
              </Col>
              <Col span={7}>
                <Form.Item>
                  身份证人像面
                {info.idCardNoFrontUrl ?
                    getFieldDecorator("idCardNoFrontUrl", {
                      initialValue: info.idCardNoFrontUrl
                    })(
                      <PFromUpload
                        disabled={true}
                        size={1}
                        disabled
                      />
                    ) : <div style={{ width: "104px", height: "104px", border: "1px dashed #ccc", paddingTop: "30px", textAlign: "center" }}>暂无</div>
                  }
                </Form.Item>
              </Col>
              <Col span={5}>
                <Form.Item >
                  身份证国徽面
                {info.idCardNoBackUrl ?
                    getFieldDecorator("idCardNoBackUrl", {
                      initialValue: info.idCardNoBackUrl
                    })(
                      <PFromUpload
                        disabled={true}
                        size={1}
                        disabled
                      />
                    ) : <div style={{ width: "104px", height: "104px", border: "1px dashed #ccc", paddingTop: "30px", textAlign: "center" }}>暂无</div>
                  }
                </Form.Item>
              </Col>
            </Row>

            <Divider style={{ paddingLeft: "15px" }} orientation="left">
              <h3 style={{ fontWeight: 800, fontSize: "20px" }}>合同信息</h3>
            </Divider>
            <Row gutter={16}>
              {/* <Table
                dataSource={contractDataSource} footer={null} columns={state.contractColumns}
              /> */}
              <Col span={7}>
                <Form.Item {...formItemLayout} label="合同名称">
                  {getFieldDecorator('contractName', {
                    initialValue: info.contractName
                  })(< Input placeholder="" maxLength={30} disabled={true} />
                  )}
                </Form.Item>
              </Col>
              <Col span={7} >
                <Form.Item {...formItemLayout} label="有效期">
                  <span>{info.effectStartDate}--{info.effectEndDate}</span>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={16}>
                <Form.Item style={{ marginLeft: "30px" }} {...formLayout3} label="合同文件">
                  <Button
                    onClick={() => {
                      if (this.state.info.contractUrl) {
                        publicCommonFileFilePreview({
                          url: this.state.info.contractUrl,
                          isLoad: '1'
                        })
                          .then(data => {
                            if (data.data) {
                              window.open(data.data);
                            }
                          });
                      } else {
                        notification.warning({
                          message: '该合同未上传附件！',
                          description: '请先上传合同文件，方可查看。'
                        });
                      }
                    }}
                  >
                    预览
                  </Button>
                  <span style={{ color: "#FF7370" }}>（备注：该保安人员不满足保安证/入职/录入时间满一年，需校验劳动合同生效时间是否满一年）</span>
                </Form.Item>

              </Col>
            </Row>
            <Divider style={{ paddingLeft: "15px" }} orientation="left">
              <h3 style={{ fontWeight: 800, fontSize: "20px" }}>人员基本信息审核意见</h3>
            </Divider>
            <Row gutter={16}>
              <Col span={12} >
                <Form.Item {...formItemLayout} label="学员基本信息是否合格">
                  <Radio.Group value={state.checkStatus} onChange={this.checkQualified}>
                    <Radio value={1}>合格</Radio>
                    <Radio value={2}>不合格</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col>
            </Row>
            {
              state.checkStatus === 1 ?
                "" :
                <Row gutter={16}>
                  <Col span={8} >
                    <Form.Item {...formItemLayout} label="不合格原因" required={true}>
                      <Input.TextArea onChange={this.handleCheckContent} value={state.checkContent} placeholder="输入不合格原因：如劳动合同不合格" rows={4} />
                    </Form.Item>
                  </Col>
                </Row>
            }
            <Divider style={{ paddingLeft: "15px" }} orientation="left">
              <h3 style={{ fontWeight: 800, fontSize: "20px" }}>学习记录</h3>
            </Divider>
            <Form.Item {...formLayoutTable} label="">
              <Table style={{ marginLeft: "100px" }}
                dataSource={selectProofList} footer={null} columns={state.infoReviewColumns}
                pagination={false}
              />
            </Form.Item>
            <Divider style={{ paddingLeft: "15px" }} orientation="left">
              <h3 style={{ fontWeight: 800, fontSize: "20px" }}>实习记录</h3>
            </Divider>
            <Form.Item {...formLayoutTable2} label="">

              <BTable
                style={{ marginTop: 20, marginLeft: 100 }}
                columns={state.internReviewColumns}
                url="trainInternInternLinePage"
                pageParm={state.pageParm}
                // forceUpdate={this.state.forceUpdate}
                // scroll={{ x: '2200px' }}
                pagination={{
                  showTotal: total => `总共 ${total} 条`
                }}
              // dateChange={
              // }
              />
            </Form.Item>
            <Row gutter={16}>
              <Col span={20}>
                <div className="sumbitButtom" style={{ textAlign: 'center' }}>
                  <Button style={{ margin: '0 20px' }}
                    onClick={() => {
                      this.props.history.push("/spotCheck/gradeMessage");
                    }}
                  >
                    取消
                      </Button>
                  <Button type="primary" style={{ margin: '0 20px' }}
                    onClick={this.__submit} disabled={state.personApplyId ? false : true}
                  >
                    提交
                      </Button>
                </div>
              </Col>
            </Row>
          </div>
        </Form>
        <Modal
          title="不合格原因"
          visible={state.internModel}
          onOk={this.handleOk}
          onCancel={this.handleOnCancel}
        >
          <Input.TextArea value={state.internContent} autoSize={{ minRows: 3, maxRows: 6 }} placeholder="填写示例：图片不符合要求或视频不符合要求"
            onChange={(e) => {
              this.setState({ internContent: e.target.value })
            }}
          />
        </Modal>
        {/* </TabPane>
        </Tabs> */}
      </div>
    );
  }
}
