import React, { PureComponent } from 'react';
import { connect } from 'dva';
import style from "styled-components";
import { Form, Input, Button, Radio, Cascader, Select, message } from 'antd';

import {
  enterpriseCompanyComBaseInfoGetComBaseInfoById,
  publicCommonDictGetDictByCodeTypes, systemPlatNewsVerificationCode,
  updateComBaseInfoById,
} from "../../../services/api";
import $nModal from '../../../utils/modal/nModal';
import PCascader from "../../../components/Pro/PCascader";
import bcx_utils from "../../../common/bcx_utils";


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

@connect(state => ({
  companyInfo: state.global.companyInfo
}))
@Form.create()
/**
 * 基础信息
 */
export default class InitialBasicInformation extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      // count: 0,
      companyInfo: {},//公司信息
      industryType: [],//行业类型
      economicType: [],//经济类型
      comType: [],//企业类型
      institutionType: [], //机构类型
      IsBranch: "",
      loading: false
    };

  }


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

  componentDidMount = () => {
    this.publicCommonDictGetDictByCodeTypes();
    // this.getDistrictData();
    /* //MSelect 和 form 结合使用，等待完善
     MSelect(["economicType", "comType", "institutionType"], (data) => {
       this.setState({PMSelect: data});
     });*/
  }
  /******************************ajax请求******************************/
  //获取企业信息
  enterpriseCompanyComBaseInfoGetComBaseInfoById = () => {
    enterpriseCompanyComBaseInfoGetComBaseInfoById({}).then(
      ({ data }) => {
        this.setState({ companyInfo: data });
      },
      (err) => {
        console.log(err);
      }
    );
  }
  //查询字典
  publicCommonDictGetDictByCodeTypes = () => {
    let tmp = { codeTypes: ["industryType", "economicType", "comType", "institutionType"] };
    publicCommonDictGetDictByCodeTypes(tmp).then(
      ({ data: { industryType, economicType, comType, institutionType } }) => {

        this.setState({ industryType, economicType, comType, institutionType });

        this.enterpriseCompanyComBaseInfoGetComBaseInfoById();
      },
      (err) => {
        console.log(err);
      }
    );
  }

  //修改企业基本信息
  updateComBaseInfoById = (ajaxUpdate, resolve) => {
    updateComBaseInfoById(ajaxUpdate).then(
      ({ msg }) => {
        // message.success(msg, 1.5, () => resolve());
        resolve();
        this.props.addStep();
      },
      (err = "") => {
        console.log(err);
      }
    );
  }

  /******************************相关事件******************************/

  //表单提交
  handleSubmit = (e) => {
    e.preventDefault();
    if(this.state.loading) return;
    this.setState({
      loading: true
    }, () => {
      this.props.form.validateFields((err, values) => {
        if (!err) {
          $nModal({
            title: '请准确核对信息',
            okText: "确认无误，提交",
            cancelText: '返回修改',
            content: <div style={{color:'orange'}}>
              企业名称、注册地址、是否为分/子公司信息提交后，企业将无法自行修改。只能通过公安备案许可服务，由公安审核通过后进行更新，请准确核对信息，确认无误后再提交。
            </div>,
            onOk: close => {
              close();
              const { address: [regProvince, regCity, regArea], workAddress: [workProvince, workCity, workArea] , workRegAddress, comType, economicType, isBranchCom, parentComName, parentComRep, parentComTel, regAddress, telePhone, parentComCerNo ,comName} = values;
              
              const { comId, industryType, institutionType } = this.state.companyInfo;
              const ajaxUpdate = {
                // comId,
                comName,
                telePhone,
                regProvince,
                regCity,
                regArea,
                regAddress,
                workProvince,
                workCity,
                workArea,
                economicType,
                industryType,
                comType,
                workAddress: workRegAddress,
                institutionType,
                isBranchCom,
                parentComName,
                parentComRep,
                parentComTel,
                parentComCerNo
              };
              updateComBaseInfoById(ajaxUpdate).then(res => {
                this.props.addStep();
                this.setState({
                  loading: false
                });
              }).catch(err => {
                console.log(err);
                this.setState({
                  loading: false
                });
              });
              // bcx_utils.preventRepeatAsync(callback => callback((resolve) => {
              //   console.log(resolve, 'resolveresolve');
              //   this.updateComBaseInfoById(ajaxUpdate, resolve);
              // }));
            }
          });
        }
        this.setState({
          loading: false
        });
      });
    });
  }

  //是否为公司
  onChangeIsBranch = (value) => {
    const companyInfo = this.state.companyInfo;
    companyInfo.isBranchCom = value;
    this.setState({ companyInfo });
  }
  /******************************render******************************/
  //经济类型
  renderEconomicType = () => {
    return this.state.economicType.map(val => (
      <Option
        value={val.codeValue + ""}
        key={val.codeValue}>{val.label}</Option>
    ));
  }
  //企业类型
  renderComType = () => {
    return this.state.comType.map(val => (
      <Option
        value={val.codeValue + ""}
        key={val.codeValue}>{val.label}</Option>
    ));
  }
  //行业类型
  renderIndustryType = () => {
    const { industryType } = this.state;
    const industryTypeItem = this.state.companyInfo.industryType || "";
    return industryType.find(val => val.codeValue === industryTypeItem).label;
  }
  //机构类型
  renderinstitutionType = () => {
    const { institutionType } = this.state;
    const institutionTypeItem = this.state.companyInfo.institutionType || "";
    const item = institutionType.find(val => val.codeValue === institutionTypeItem);
    return item?item.label: '';
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 6 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 12 },
      },
    };
    const {
      comName = "",
      economicType = "",
      comType = "",
      telePhone = "",
      regAddress = "",
      isBranchCom = "0",
      parentComName = "0",
      parentComCerNo = "0",
      parentComRep = "0",
      parentComTel = "0",
      regProvince = "",
      regCity = "",
      regArea = "",
      workProvince = "",
      workCity = "",
      workArea = "",
      workAddress = "",
    } = this.state.companyInfo;

    return (
      <Container>
        <header className="password-header">完善企业基础信息</header>
        {Object.keys(this.state.companyInfo).length !== 0 && (
          <Form onSubmit={this.handleSubmit} style={{ marginTop: 24 }}
          >
            <FormItem {...formItemLayout} label="企业名称">
              {getFieldDecorator('comName', {
                initialValue: comName,
                rules: [{
                  required: true, message: '请输入企业名称',
                }],
              })(
                <Input placeholder="请填写企业名称" maxLength={100} />
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="所属行业"
            >
              <span>{this.renderIndustryType()}</span>
            </FormItem>

            <FormItem {...formItemLayout} label="机构类型"
            >
              <span>{this.renderinstitutionType()}</span>
            </FormItem>

            <FormItem {...formItemLayout} label="经济类型"
            >
              {getFieldDecorator('economicType', {
                initialValue: economicType,
                rules: [{
                  required: true, message: '请输入',
                }],
              })(
                <Select placeholder="请选择">
                  {this.renderEconomicType()}
                </Select>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="企业类型"
            >
              {getFieldDecorator('comType', {
                initialValue: comType,
                rules: [{
                  required: true, message: '请选择',
                }],
              })(
                <Select placeholder="请选择">
                  {this.renderComType()}
                </Select>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="联系电话"
            >
              {getFieldDecorator('telePhone', {
                initialValue: telePhone,
                rules: [{
                  pattern: /^((0\d{2,3}-\d{7,8})|(1[0-9]{10}))$/,
                  message: '请输入正确手机号码或者固定电话，固定电话以-隔开',
                }, { required: true, message: '请输入联系电话' }],
              })(
                <Input placeholder="请输入手机号码" />
              )}
            </FormItem>


            <FormItem {...formItemLayout} label="注册地址"
            >
              {getFieldDecorator('address', {
                initialValue: [regProvince, regCity, regArea],
                rules: [{ type: 'array', required: true, message: '注册地址不能为空!' }],
              })(
                <PCascader placeholder="请选择" />
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="详细地址" colon={false} className="regAddress"
            >
              {getFieldDecorator('regAddress', {
                initialValue: regAddress,
                rules: [{
                  required: true, message: '请输入公司注册详细地址',
                }],
              })(
                <Input placeholder="请填写公司注册详细地址" maxLength={100} />
              )}
            </FormItem>

            {/* 办公地址 */}
            <FormItem {...formItemLayout} label="办公地址"
            >
              {getFieldDecorator('workAddress', {
                initialValue: [workProvince, workCity, workArea],
                rules: [{ type: 'array', required: true, message: '办公地址不能为空!' }],
              })(
                <PCascader placeholder="请选择" />
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="详细地址" colon={false} className="regAddress"
            >
              {getFieldDecorator('workRegAddress', {
                initialValue: workAddress,
                rules: [{
                  required: true, message: '请输入公司办公详细地址',
                }],
              })(
                <Input placeholder="请填写公司办公详细地址" maxLength={100} />
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="是否为分/子公司"
            >
              {getFieldDecorator('isBranchCom', {
                initialValue: isBranchCom,
                rules: [{
                  required: true, message: '请选择公司类型',
                }],
              })(
                // <Radio.Group onChange={this.onChangeIsBranch}>
                //   <Radio value="1">是</Radio>
                //   <Radio value="0">否</Radio>
                // </Radio.Group>
                <Select
                  placeholder="请选择公司类型"
                  onChange={this.onChangeIsBranch}
                >
                  <Option key="0" value="0">否</Option>
                  <Option key="1" value="1">分公司</Option>
                  <Option key="2" value="2">子公司</Option>
                </Select>
              )}
            </FormItem>


            {(isBranchCom === "1" || isBranchCom === '2') && (
              <div>
                <FormItem {...formItemLayout} label="总公司统一社会信用代码"
                >
                  {getFieldDecorator('parentComCerNo', {
                    initialValue: parentComCerNo || "",
                    rules: [{
                      required: true, message: '总公司统一社会信用代码',
                    }, {
                      pattern: /^[A-Za-z0-9]{1,20}$/, message: '请输入最大20个字符的名称'
                    }],
                  })(
                    <Input placeholder="请输入" maxLength={20} />
                  )}
                </FormItem>

                <FormItem {...formItemLayout} label="总公司名称"
                >
                  {getFieldDecorator('parentComName', {
                    initialValue: parentComName || "",
                    rules: [{
                      required: true, message: '总公司名称',
                    },
                    {
                      validator: (rule, value, callback) => {
                        // if (value && !/^[\u4e00-\u9fa5\（\）]{1,50}$/.test(value)) {
                        //   callback('请输入正确的总公司名称！');
                        // }
                        if (value && !/^\S{1,50}$/.test(value)) {
                          callback('请输入最大50个字符的名称');
                        } else if(value == this.props.companyInfo.comName) {
                          callback('输入的总公司名称不能和当前公司一致！');
                        } else {
                          callback();
                        }
                      }
                    },
                    // {
                    //   pattern: /^\S{1,50}$/, message: '请输入最大50个字符的名称'
                    // },
                      // {
                      //   pattern: /^[\u4e00-\u9fa5\（\）]{1,50}$/, message: '请输入最大50个字符的名称'
                      // }
                    ],
                  })(
                    <Input placeholder="请输入" maxLength={50} />
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="总公司法人"
                >
                  {getFieldDecorator('parentComRep', {
                    initialValue: parentComRep || "",
                    rules: [{
                      required: true, message: '请输入 总公司法人',
                    }],
                  })(
                    <Input placeholder="请输入" maxLength={10} />
                  )}
                </FormItem>

                <FormItem {...formItemLayout} label="总公司联系电话"
                >
                  {getFieldDecorator('parentComTel', {
                    initialValue: parentComTel || "",
                    rules: [{
                      pattern: /^((0\d{2,3}-\d{7,8})|(1[0-9]{10}))$/,
                      message: '请输入正确手机号码或者固定电话，固定电话以-隔开!',
                    },
                    {
                      required: true, message: '请输入总公司联系电话',
                    }],
                  })(
                    <Input placeholder="请输入" maxLength={13} />
                  )}
                </FormItem>
              </div>
            )}

            <FormItem {...formItemLayout} label=" " colon={false}
            >
              <Button style={{ marginRight: "8px" }} onClick={() => { this.props.preStep(); }}>返回上一步</Button>
              <Button className="submit" type="primary" htmlType="submit">确定并下一步</Button>
            </FormItem>
          </Form>
        )}
      </Container>
    );
  }
}

/*********************样式*************************** */
const Container = style.div`{
    .password-header{
        font-size: 20px;
        color: #333333;
        padding-bottom:16px;
        border-bottom:1px solid #e9e9e9;
    }
    .ant-btn-primary{
        background-color: #0F71FF;
    }
    .detailedAddress{
        .ant-form-item-required:before{
            content:" ";
        }
    }
}`;
