import React from 'react';
import moment from 'moment';
import "moment/locale/zh-cn";
import {
  Form,
  Input,
  Button,
  DatePicker,
  Popover,
  Icon,
  Select,
  InputNumber
} from 'antd';
import { formItemLayout1 } from './constants';
import { DrawHeader, Empty, DrawBottomBtns, DrawTitle, ImageDontDelete } from './styles';
import { OrganName } from './components';
import PCascader from '../../../components/Pro/PCascader';
import PFromUpload from '../../../components/Pro/PFromUpload';
import PDrawer from '../../../components/Pro/PDrawer';
import {
  enterpriseCompanyComBaseInfoGetComBaseInfoById,
  publicCommonDictGetDictByCodeTypes,
  enterpriseCompanyGetComIndustryinfo,
  enterpriseCompanyComIndustryGetComBranchIndustryInfoByComId,
} from '../../../services/api';

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;

const dateFormat = 'YYYY-MM-DD';

@Form.create()
export default class DrawChildCompanyIdentification extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      dataSource: {
        legalRepName: "",//法定代表人
        nationality: "",//国籍/地区
        legalRepPhone: "",//手机号
        idCardType: "",//证件类型
        idCardNo: "",//证件号
        regAmount: "",//注册资金（万元）
        fixedAssets: "",//固定资产
        annualTurnover: "",//年营业额
        annualProfitTax: "",//年利率
        comCerType: "",//企业证件类型
        comCerNo: "",//证件号
        comCerUrl: "",// 证件扫描件
      },
      codeTypes: {
        nationality: [],//国籍
        idCardType_bak: [],//证件类型
        conf_association: [],//所属行业保安协会
        conf_safeRange: [],//安全范围
        conf_manpowerLevel: [],//人力防范等级
        conf_armedLevel: [],//武装押运等级
        conf_safeTechLevel: [],//安全技术防范等级
        conf_riskLevel: [],//风险评估等级
        comCerType: [],//企业证件类型
      },
      industryInfo: [],// 行业资质
      showIndustry: false,//是否展示特殊字段信息,
      specialArray: [],//特殊字段信息
      comId: '', //特殊字段接口请求参数
      institutionType: '',//企业基础信息，企业机构类型
    };
  }

  /******************************生命周期******************************/

  componentDidMount = () => {
    this.publicCommonDictGetDictByCodeTypes();
  }
  componentWillReceiveProps = (nextProps, newState) => {
    if (nextProps.visible && !this.props.visible && nextProps.comId) {
      this.ajaxDetail(nextProps.comId);
      this.enterpriseCompanyGetComIndustryinfo(nextProps.comId);

    }
  }

  /******************************ajax请求******************************/
  // 查询详情
  ajaxDetail = (comBranchId) => {
    enterpriseCompanyComBaseInfoGetComBaseInfoById({ comBranchId })
      .then(
        (data) => {
          console.log("子公司基础信息", data);
          const { dataSource } = this.state.dataSource;
          this.setState({
            dataSource: { ...dataSource, ...data.data },
            comId: data.data.comId,
            institutionType: data.data.institutionType
          }, () => {
            console.log('企业信息-认证申请-获得企业机构特殊信息-comId', this.state.comId);

            //分公司、子公司通过ID获得企业行业信息-获得企业机构特殊信息
            enterpriseCompanyComIndustryGetComBranchIndustryInfoByComId({
              comId: this.state.comId,
              institutionType: this.state.institutionType
            }).then(
              (res) => {
                console.log("分公司、子公司通过ID获得企业行业信息", res);
                if (res.data && res.data.length) {
                  const tmp = res.data.map((val, i) => {
                    if (val.fieldType && val.fieldType === '4') {
                      val.fieldOptions = val.fieldOptions
                        ? val.fieldOptions.split(',')
                        : [];
                    }
                    if (val.fieldType && val.fieldType === '5') {
                      val.fieldOptions = val.fieldOptions
                        ? val.fieldOptions.split(',')
                        : [];
                      val.fieldValue = val.fieldValue
                        ? val.fieldValue.split(',')
                        : [];
                    }
                    return Object.assign({}, val, {
                      key: i + 1
                    });
                  });
                  console.log('tmp---------tmp', tmp);

                  this.setState({
                    specialArray: tmp,
                    showIndustry: true
                  });
                }
              },
              (err) => {
                console.log("分公司、子公司通过ID获得企业行业信息", err);
              }
            );
          });
        }
      )
      .catch(
        (err) => {
          console.log(err);
        }
      );
  }

  //类型查询
  publicCommonDictGetDictByCodeTypes = () => {
    const codeTypes = "nationality,idCardType_bak,conf_association,conf_safeRange,conf_manpowerLevel,conf_armedLevel,conf_safeTechLevel,conf_riskLevel,comCerType";
    publicCommonDictGetDictByCodeTypes({ codeTypes }).then(({ data = {} }) => {
      this.setState({ codeTypes: data });
    }, (err) => {
      console.log(err);
    });
  }

  //企业信息-认证申请-行业资质查询
  enterpriseCompanyGetComIndustryinfo = (comId) => {
    enterpriseCompanyGetComIndustryinfo({ comId }).then(
      ({ data }) => {
        console.log("industryInfo", data);
        if (!data || data.length === 0) {
          return;
        }
        this.setState({
          industryInfo: data
        });
        console.log(data);
      },
      (err) => {
        console.log(err);
      }
    );
  }

  /******************************相关事件******************************/
  /****
  * 特殊字段
  */
  showSpecialFields = () => {
    const arr = this.state.specialArray.map((value, index) => {
      return (
        <div key={index} style={{ marginTop: "24px" }}>
          {this.renderMap(
            value.fieldType,
            value.fieldName,
            value.fieldCode,
            parseInt(value.isRequired, 10),
            value.fieldValue,
            value.maxLength,
            value.fieldOptions,
            value.scriptFunction
          )}
        </div>
      );
    });
    return arr;
  };

  renderMap = (
    fieldType,
    fieldName,
    fieldCode,
    isRequired,
    fieldValue,
    maxLength,
    fieldOptions,
    scriptFunction
  ) => {
    const { getFieldDecorator } = this.props.form;

    if (fieldType === '1') {
      return (
        <FormItem {...formItemLayout1} label={fieldName}>
          {getFieldDecorator(`${fieldCode}`, {
            initialValue: fieldValue || '',
            rules: [
              {
                required: isRequired,
                message: `请输入${fieldName}`
              }
            ]
          })(
            <Input
              disabled
              placeholder="请输入"
              maxLength={maxLength}
            />
          )}
        </FormItem>
      );
    } else if (fieldType === '2') {
      let max;
      if (maxLength) {
        max = Number(1 + new Array(parseInt(maxLength, 10) + 1).join('0')) - 1;
      } else {
        max = 999999;
      }
      return (
        <FormItem {...formItemLayout1} label={fieldName}>
          {getFieldDecorator(`${fieldCode}`, {
            initialValue: fieldValue || '',
            rules: [
              {
                required: isRequired,
                message: `请输入${fieldName}`
              }
            ]
          })(
            <InputNumber disabled min={1} max={max} maxLength={maxLength} />
          )}
        </FormItem>
      );
    } else if (fieldType === '3') {
      return (
        <FormItem {...formItemLayout1} label={fieldName}>
          {getFieldDecorator(`${fieldCode}`, {
            initialValue: fieldValue ? moment(fieldValue, dateFormat) : null,
            rules: [
              {
                required: isRequired,
                message: `请选择${fieldName}`
              },
              {
                validator: (rule, value, callback) => {
                  const moment = require('moment');
                  scriptFunction
                    ? eval(`${scriptFunction}`)(rule, value, callback)
                    : callback();
                }
              }
            ]
          })(
            <DatePicker
              disabled
              placeholder="请选择"
              style={{ width: '100%' }}
            />
          )}
        </FormItem>
      );
    } else if (fieldType === '4') {
      return (
        <FormItem {...formItemLayout1} label={fieldName}>
          {getFieldDecorator(`${fieldCode}`, {
            initialValue: fieldValue || '',
            rules: [
              {
                required: isRequired,
                message: `请选择${fieldName}`
              }
            ]
          })(
            <Select
              disabled
              placeholder="请选择"
              className="sls-style"
            >
              <Option value=" ">请选择</Option>
              {fieldOptions.map((val, i) => {
                return (
                  <Option key={i} value={val.split(':')[0] + ''}>
                    {val.split(':')[1]}
                  </Option>
                );
              })}
            </Select>
          )}
        </FormItem>
      );
    } else if (fieldType === '5') {
      return (
        <FormItem {...formItemLayout1} label={fieldName}>
          {getFieldDecorator(`${fieldCode}`, {
            initialValue: fieldValue || '',
            rules: [
              {
                required: isRequired,
                message: `请选择${fieldName}`
              }
            ]
          })(
            <Select
              mode="multiple"
              style={{ width: '100%' }}
              placeholder="请选择"
              disabled
            >
              {fieldOptions.map((val, i) => {
                return (
                  <Option key={i} value={val.split(':')[0] + ''}>
                    {val.split(':')[1]}
                  </Option>
                );
              })}
            </Select>
          )}
        </FormItem>
      );
    } else if (fieldType === '8') {
      return (
        <FormItem {...formItemLayout1} label={fieldName}>
          {getFieldDecorator(`${fieldCode}`, {
            initialValue: fieldValue || '',
            rules: [
              {
                required: isRequired,
                message: `请选择${fieldName}`
              }
            ]
          })(<PFromUpload num={1} disabled />)}
          {/* <span>每张不超过:8M,格式为:jpg，jpeg，png</span> */}
        </FormItem>
      );
    } else if (fieldType === '9') {
      return (
        <FormItem {...formItemLayout1} label={fieldName}>
          {getFieldDecorator(`${fieldCode}`, {
            initialValue: fieldValue ? moment(fieldValue, dateFormat) : null,
            rules: [
              {
                required: isRequired,
                message: `请选择${fieldName}`
              }
            ]
          })(
            <DatePicker
              disabled
              placeholder="请选择"
              style={{ width: '100%' }}
            />
          )}
        </FormItem>
      );
    } else if (fieldType === '10') {
      return (
        <FormItem {...formItemLayout1} label={fieldName}>
          {getFieldDecorator(`${fieldCode}`, {
            initialValue: fieldValue || '',
            rules: [
              {
                // required: isRequired, message: `请选择${fieldName}`,
                required: isRequired,
                message: `请输入${fieldName}`
              }
            ]
          })(
            <TextArea
              disabled
              rows={3}
              placeholder={`请输入${fieldName}`}
              maxLength={maxLength}
            />
          )}
        </FormItem>
      );
    }
  };

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {

      }
    });
  }

  closeDrawer = () => {
    this.props.closeDrawer();
  }


  /******************************render******************************/
  renderOption = (options) => {
    if (options.length === 0) {
      return;
    }
    return options.map(
      (val, key) => (
        <Option
          value={val.codeValue}
          key={key}>
          {val.label}
        </Option>
      ));
  }

  render() {
    const { visible } = this.props;
    const { getFieldDecorator } = this.props.form;
    const {
      legalRepName,
      nationality,
      legalRepPhone,
      idCardType,
      idCardNo,
      regAmount,
      fixedAssets,
      annualTurnover,
      annualProfitTax,
      comCerType,
      comCerNo,
      comCerUrl

    } = this.state.dataSource;

    const codeTypes = this.state.codeTypes;
    const { industryInfo, showIndustry } = this.state;

    //保安服务许可证号
    const findsecurityLicenseNum = () => {
      const result = industryInfo.find(val => val.fieldCode.trim() === "conf_securityLicenseNum");
      if (!result) {
        return "";
      } else {
        return result.fieldValue;
      }
    };
    //安保范围
    const findSelectValue = (name) => {
      const result = industryInfo.find(val => val.fieldCode.trim() === name);
      if (!result) {
        return [];
      }
      if (result.fieldValue === "") {
        return [];
      }
      return result.fieldValue.split(',');
    };
    //上传保安服务许可证
    const findSecurityLicenseUrl = () => {
      const result = industryInfo.find(val => val.fieldCode.trim() === "conf_securityLicenseUrl");
      if (!result) {
        return "";
      } else {
        return result.fieldValue;
      }
    };


    return (
      <PDrawer
        title="认证信息"
        visible={visible}
        okText={null}
        cancelText="返回"
        onCancel={this.closeDrawer}
        destroyOnClose={true}
      >
        <div>
          <Form onSubmit={this.handleSubmit} style={{ width: 390, margin: "6px 0 81px 0" }}>
            {/* <DrawTitle>法定代表人/负责人</DrawTitle> */}
            <DrawTitle>法定代表人</DrawTitle>
            <FormItem
              {...formItemLayout1}
              // label="法定代表人/负责人姓名"
              label="法定代表人"
              style={{ marginTop: 24 }}
            >
              <Input style={{ width: 294 }} disabled={true} value={legalRepName} />
            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="国籍/地区"
              style={{ marginTop: 24 }}
            >
              <Select disabled={true} value={nationality}>
                {this.renderOption(codeTypes.nationality)}
              </Select>
            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="手机号"
              style={{ marginTop: 24 }}
            >
              <Input style={{ width: 294 }} disabled={true} value={legalRepPhone} />

            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="证件类型"
              style={{ marginTop: 24 }}
            >
              <Select disabled={true} value={idCardType}>
                {this.renderOption(codeTypes.idCardType_bak)}
              </Select>
            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="证件号"
              style={{ marginTop: 24 }}
            >
              <Input style={{ width: 294 }} disabled={true} value={idCardNo} />
            </FormItem>
            <DrawTitle>
              注册信息
            </DrawTitle>
            <FormItem
              {...formItemLayout1}
              label="注册资金（万元）"
              style={{ marginTop: 24 }}
            >
              <Input style={{ width: 294 }} disabled={true} value={regAmount} />
            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="固定资产（万元）"
              style={{ marginTop: 24 }}
            >
              <Input style={{ width: 294 }} disabled={true} value={fixedAssets} />
            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="年营业额（万元）"
              style={{ marginTop: 24 }}
            >
              <Input style={{ width: 294 }} disabled={true} value={annualTurnover} />
            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="年利率（万元）"
              style={{ marginTop: 24 }}
            >
              <Input style={{ width: 294 }} disabled={true} value={annualProfitTax} />
            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="证件类型"
              style={{ marginTop: 24 }}
            >
              <Select disabled={true} value={comCerType}>
                {this.renderOption(codeTypes.comCerType)}
              </Select>
            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="证件号"
              style={{ marginTop: 24 }}
            >
              <Input style={{ width: 294 }} disabled={true} value={comCerNo} />

            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="证件扫描件"
              style={{ marginTop: 24 }}
            >
              <ImageDontDelete>
                <PFromUpload num={1} value={comCerUrl} disabled />
              </ImageDontDelete>
            </FormItem>

            {showIndustry && (
              <div>
                <DrawTitle>
                  资质信息
                </DrawTitle>

                {this.showSpecialFields()}

                {/* <FormItem
                  {...formItemLayout1}
                  label="所属行业保安协会"
                  style={{ marginTop: 24 }}
                >
                  <Select disabled={true} value={findSelectValue("conf_association")}>
                    {this.renderOption(codeTypes.conf_association)}
                  </Select>
                </FormItem>
                <FormItem
                  {...formItemLayout1}
                  label="安保范围"
                  style={{ marginTop: 24 }}
                >
                  <Select disabled={true} value={findSelectValue("conf_safeRange")}>
                    {this.renderOption(codeTypes.conf_safeRange)}
                  </Select>
                </FormItem>
                <FormItem
                  {...formItemLayout1}
                  label="人力防范等级"
                  style={{ marginTop: 24 }}
                >
                  <Select disabled={true} value={findSelectValue("conf_manpowerLevel")}>
                    {this.renderOption(codeTypes.conf_manpowerLevel)}
                  </Select>

                </FormItem>
                <FormItem
                  {...formItemLayout1}
                  label="武装押运等级"
                  style={{ marginTop: 24 }}
                >
                  <Select disabled={true} value={findSelectValue("conf_armedLevel")}>
                    {this.renderOption(codeTypes.conf_armedLevel)}
                  </Select>
                </FormItem>
                <FormItem
                  {...formItemLayout1}
                  label="安全技术防范等级"
                  style={{ marginTop: 24 }}
                >
                  <Select disabled={true} value={findSelectValue("conf_safeTechLevel")}>
                    {this.renderOption(codeTypes.conf_safeTechLevel)}
                  </Select>

                </FormItem>
                <FormItem
                  {...formItemLayout1}
                  label="保安服务许可证号"
                  style={{ marginTop: 24 }}
                >
                  <Input style={{ width: 294 }} disabled={true} value={findsecurityLicenseNum()} />

                </FormItem>
                <FormItem
                  {...formItemLayout1}
                  label="保安服务许可证"
                  style={{ marginTop: 24 }}
                >
                  <ImageDontDelete>
                    <PFromUpload num={1} disabled={true} value={findSecurityLicenseUrl()} />
                  </ImageDontDelete>
                </FormItem> */}
              </div>
            )}
          </Form>
        </div>
      </PDrawer>
    );
  }
}
