import React, { Component } from 'react';
import { connect } from 'dva';
import { Form, Input, Select, Button, Modal, message, Cascader,Alert } from 'antd';

import {
  enterpriseCompanyComBaseInfoGetComBaseInfoById,
  updateComBaseInfoById,
  publicCommonDictGetDictByCodeTypes,
  // getDistrictData,
  getDistrictChineseData,
  systemComVaseInfoGet,
  selectComAdmin,
  systemPlatNewsSendVerificationCode,
  systemPlatNewsVerificationCode
} from '../../../services/api';
import PCascader from '../../../components/Pro/PCascader';

import './Company.less';

const store = require('store');

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

@connect(state => ({
  companyInfo: state.global.companyInfo,
  currentUser: state.user.currentUser.userName
}))
@Form.create()
export default class Information extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      // comId: this.props.location.query.trackid || '',   // 公司ID
      comId: '',
      areas: [], //地区
      submit: false,
      loading: false,
      companyInformationData: {
        comName: '', //公司名字
        telePhone: '', //公司电话
        fax: '', //公司传真
        regProvince: '', //注册地所在省份
        regCity: '', //注册地所在城市
        regArea: '', //注册地所在区/县
        regAddress: '', //公司具体地址
        isBranchCom: '0', //是否分公司
        parentComName: '', //总公司名称
        parentComCerNo: '', //总公司统一社会信用代码
        parentComRep: '', //总公司法人
        parentComTel: '', //总公司联系电话
        economicType: '', //经济类型
        industryType: '', //行业类型
        comType: '', //企业类型
        institutionType: '', //机构类型
        residences: '' //省市区
      },
      economicType: [], //经济类型
      industryType: [], //行业类型
      comType: [], //企业类型
      institutionType: [], //机构类型
      isBranch: '0',
      areaAddress: ['', '', ''], //注册地址
      workAddress: ['', '', ''],  //办公地址
      // workAddress: ['', '', ''],  //办公地址
      administratorRelative: {
        administrator: '', // 管理员名字
        phoneValue: '', // 管理员电话
        openValidAdminModal: false,
        phoneValueHiddenMiddle: '', // 带*号的管理员手机号
        hasValidCode: false, // 管理员手机验证码
        isValidCode: false, // 管理员手机验证码是否正确
        countDownNoPhone: 60 // 管理员手机验证码倒计时
      }
    };
  }

  //省市区
  // getDistrict = () => {
  //   getDistrictData().then(data => {
  //     let areas = data.data.map(val => {
  //       return {
  //         value: val.regionId,
  //         label: val.regionName,
  //         children: val.childs.map(valChild => {
  //           return {
  //             value: valChild.regionId,
  //             label: valChild.regionName,
  //             children: valChild.childs.map(valChildChild => {
  //               return {
  //                 value: valChildChild.regionId,
  //                 label: valChildChild.regionName
  //               };
  //             })
  //           };
  //         })
  //       };
  //     });
  //     this.setState({
  //       areas: areas
  //     });
  //   });
  // };

  componentDidMount() {
    this.companyInformationGet(); //是否有信息返回
    // this.getDistrict(); //省市区选择
    this.getComAdmin(); // 获得企业管理员  -->用于判断是否是主管理员，提交的时候做弹窗  ive
    this.getDictionaryData(); //获取所有所需要字典数据
  }

  // 通过id获取基本信息
  companyInformationGet() {
    enterpriseCompanyComBaseInfoGetComBaseInfoById({}).then(async data => {
      //判断获取数据是否为空
      let resultData = data.data;
      if (resultData) {
        // 注册地址
        const province = resultData.regProvince;
        
        const city = resultData.regCity;
        
        const area = resultData.regArea;
        // 工作地址
        const { workProvince, workCity, workArea } = resultData;
        this.setState({
          companyInformationData: resultData,
          isBranch: resultData.isBranchCom,
          // areaAddress: arr,
          // workAddress: workArr
          areaAddress: [province, city, area],
          workAddress: [workProvince, workCity, workArea]
        });
      }
    });
  };
  //获取所有所需要字典数据
  getDictionaryData = () => {
    publicCommonDictGetDictByCodeTypes({
      codeTypes: ['economicType', 'industryType', 'comType', 'institutionType']
    }).then(data => {
      //判断获取数据是否为空
      if (data.data) {
        this.setState({
          economicType: data.data.economicType, //获得经济类型
          industryType: data.data.industryType, //获得行业类型
          comType: data.data.comType, //获得企业类型
          institutionType: data.data.institutionType //获得机构类型
        });
      }
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    this.setState({ submit: true });
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // 验证管理员身份
        if (
          this.props.currentUser !==
            this.state.administratorRelative.phoneValue &&
          (!this.state.administratorRelative.hasValidCode ||
            !this.state.administratorRelative.isValidCode)
        ) {
          this.setState({
            administratorRelative: {
              ...this.state.administratorRelative,
              openValidAdminModal: true
            }
          });
          return;
        }

        const regData = ['regProvince', 'regCity', 'regArea', 'comId'];
        const regValue = [
          values.address[0],
          values.address[1],
          values.address[2],
          this.state.comId
        ];
        for (let i = 0; i < regData.length; i++) {
          let key = regData[i];
          let regval = regValue[i] || '0';
          values[key] = regval.toString();
        }
        delete values.address;

        values.workProvince = values.workAddressArr[0];
        values.workCity = values.workAddressArr[1];
        values.workArea = values.workAddressArr[2];
        // Reflect.deleteProperty(values, workAddressArr);
        delete values.workAddressArr;
        this.setState({ loading: true });
        updateComBaseInfoById({ ...values }).then(data => {
          // message.success('提交成功！');

          if (store.get('saas') !== undefined) {
            // systemComVaseInfoGet({}).then(
            //   response => {
                const companyInfo = Object.assign({}, this.props.companyInfo);
                // companyInfo.comName = response.data.comName;
                companyInfo.comName = values.comName;
                this.props.dispatch({
                  type: 'global/companyInfo',
                  payload: companyInfo
                });
            //   },
            //   errs => {
            //     console.log('企业信息-基础信息-保存公司名称', errs);
            //   }
            // );
          }

          this.setState({
            companyInformationData: values,
            loading: false
          });
        });
      } else {
        message.error('提交失败！');
        this.setState({ loading: false });
      }
    });
  };
  callback = key => {
    console.log(key);
  };

  //验证名称类，限制不能全角输入
  checkFullWidth = (rule, value, callback) => {
    if (value && !/^\S{0,50}$/.test(value)) {
      callback('请输入正确的公司名称！');
    } else {
      callback();
    }
  };

  //验证手机号码
  checkPhone = (rule, value, callback) => {
    if (value && !/^((0\d{2,3}-\d{7,8})|(1[0-9]{10}))$/.test(value)) {
      callback('请输入正确的联系号码！');
    } else {
      callback();
    }
  };

  //验证传真
  checkFax = (rule, value, callback) => {
    if (value && !/^((0\d{2,3}-\d{7,8})|(1[0-9]{10}))$/.test(value)) {
      callback('请输入正确的传真号码！');
    } else {
      callback();
    }
  };

  //验证固定号码
  checkLandlinePhone = (rule, value, callback) => {
    if (value && !/^((0\d{2,3}-\d{7,8})|(1[0-9]{10}))$/.test(value)) {
      callback('请输入正确的联系电话！');
    } else {
      callback();
    }
  };

  //经济类型选择
  renderEconomic = () => {
    return this.state.economicType.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ''}>
          {val.label}
        </Option>
      );
    });
  };

  //行业类型选择
  renderIndustry = () => {
    return this.state.industryType.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ''}>
          {val.label}
        </Option>
      );
    });
  };

  //企业类型选择
  renderCompany = () => {
    return this.state.comType.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ''}>
          {val.label}
        </Option>
      );
    });
  };

  //机构类型选择
  renderInstitution = () => {
    return this.state.institutionType.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ''}>
          {val.label}
        </Option>
      );
    });
  };

  //是否是分公司选择
  onChangeIsBranch = value => {
    this.setState({
      isBranch: value
    });
  };

  checkDetailedAddress = (rule, value, callback) => {
    if (value && !/^[A-Za-z0-9\u4e00-\u9fa5]+$/.test(value)) {
      callback('请输入正确的地址！');
    } else {
      callback();
    }
  };

  checkParentComName = (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();
    }
  };

  checkParentComCerNo = (rule, value, callback) => {
    if (value && !/^[A-Za-z0-9]{1,20}$/.test(value)) {
      callback('请输入正确的总公司统一社会信用代码！');
    } else {
      callback();
    }
  };

  checkParentComRep = (rule, value, callback) => {
    if (value && !/^[A-Za-z\u4e00-\u9fa5]+$/.test(value)) {
      callback('请输入正确的总公司法人！');
    } else {
      callback();
    }
  };

  // 管理员身份验证码弹窗确认事件
  handleValidAdminModalOk = e => {
    this.props.form.validateFields((err, values) => {
      if (!values['adminValidCode']) {
        this.props.form.setFields({
          adminValidCode: {
            value: values.user,
            errors: [new Error('请输入验证码')]
          }
        });
        return false;
      }
      if (!err) {
        systemPlatNewsVerificationCode({
          mobile: this.state.administratorRelative.phoneValue,
          code: values['adminValidCode']
        }).then(
          () => {
            this.setState(
              {
                administratorRelative: {
                  ...this.state.administratorRelative,
                  isValidCode: true,
                  openValidAdminModal: false
                }
              },
              () => {
                this.handleSubmit(e);
              }
            );
          },
          error => {
            console.log('验证码是否正确-error:', error);
            // message.error('请填写正确的验证码信息');
          }
        );
      }
    });
  };

  // 管理员身份验证码弹窗取消事件
  handleValidAdminModalCancel = () => {
    this.setState({
      administratorRelative: {
        ...this.state.administratorRelative,
        openValidAdminModal: false
      }
    });
  };

  //获得企业管理员
  getComAdmin = () => {
    // 获取管理员电话号码 名字 perid username
    selectComAdmin({}).then(data => {
      let phoneValueHiddenMiddle = data.data[0].userName;
      phoneValueHiddenMiddle = phoneValueHiddenMiddle.replace(
        /(\d{3})\d{4}(\d{4})/,
        '$1****$2'
      );
      //判断获取数据是否为空
      this.setState({
        administratorRelative: {
          ...this.state.administratorRelative,
          administrator: data.data[0].name,
          phoneValue: data.data[0].userName, // 我也不知道为啥叫这个名字，反正后台这个字段是电话
          phoneValueHiddenMiddle
        }
      });
    });
  };

  // 获取管理员验证码按钮逻辑
  getAdminValidCodeButton = () => {
    const disableStyle = {
      background: '#f7f7f7',
      marginLeft: 16,
      borderColor: '#d9d9d9'
    };

    // 验证通过,没有获取
    if (!this.state.administratorRelative.hasValidCode) {
      return (
        <Button
          type='primary'
          style={{ marginLeft: 16 }}
          className='getCaptcha'
          onClick={this.getAdminValidCode}
        >
          验证
        </Button>
      );
      //验证通过,正在获取
    } else {
      this.timerCountForAdminValidCode();
      return (
        <Button
          type='primary'
          className='getValid'
          style={disableStyle}
          disabled
        >
          {this.state.administratorRelative.countDownNoPhone}
          S后重新发送
        </Button>
      );
    }
  };

  // 获取管理员验证码
  getAdminValidCode = () => {
    systemPlatNewsSendVerificationCode({
      mobile: this.state.administratorRelative.phoneValue
    }).then(
      res => {
        if (res.retType === '0') {
          this.setState({
            administratorRelative: {
              ...this.state.administratorRelative,
              hasValidCode: true,
              isValidCode: false
            }
          });
        }
      },
      err => {
        console.log('获取验证码错误信息:', err);
      }
    );
  };

  // 管理员验证码倒计时
  timerCountForAdminValidCode = () => {
    //防止重复计算
    if (this.state.administratorRelative.countDownNoPhone !== 60) {
      return;
    }

    this.countDownTimeForAdminValidCode = setInterval(() => {
      if (this.state.administratorRelative.countDownNoPhone > 0) {
        this.setState(prevState => ({
          administratorRelative: {
            ...this.state.administratorRelative,
            countDownNoPhone:
              prevState.administratorRelative.countDownNoPhone - 1
          }
        }));
        if (this.state.administratorRelative.countDownNoPhone === 0) {
          this.setState({
            administratorRelative: {
              ...this.state.administratorRelative,
              countDownNoPhone: 60,
              hasValidCode: false
            }
          });
          clearInterval(this.countDownTimeForAdminValidCode);
        }
      } else {
        clearInterval(this.countDownTimeForAdminValidCode);
      }
    }, 1000);
  };

  render() {
    const { submitting } = this.props;
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 }
      }
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 }
      }
    };

    const formItemLayoutMore = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
        md: { span: 16 }
      }
    };

    return (
      <div>
         {/* <Alert
          message={
            <div>
              <div>
                部分企业信息无法直接修改，若您需要修改的，请到
                <span style={{ color: '#40a9ff' }}>【备案许可申报】</span>页面，选择
                <span style={{ color: '#f90' }}>保安服务（培训）许可证项目变更审核</span>
                进行变更。
              </div>
            </div>
          }
          type='warning'
          showIcon
          style={{ marginBottom: '15px' }}
        /> */}
        <Form onSubmit={this.handleSubmit} style={{ marginTop: 24 }}>
          <FormItem {...formItemLayout} label='公司名称'>
            {getFieldDecorator('comName', {
              initialValue: this.state.companyInformationData.comName,
              rules: [
                {
                  required: true,
                  message: '请输入公司名称'
                },
                {
                  validator: this.checkFullWidth
                }
              ]
            })(<Input disabled={this.state.companyInformationData.industryType === '01'} placeholder='请输入' maxLength={50} />)}
          </FormItem>
          <FormItem {...formItemLayout} label='联系电话'>
            {getFieldDecorator('telePhone', {
              initialValue: this.state.companyInformationData.telePhone,
              rules: [
                {
                  required: true,
                  message: '请输入联系电话'
                },
                {
                  validator: this.checkLandlinePhone
                }
              ]
            })(<Input placeholder='请输入' maxLength={13} />)}
          </FormItem>
          <FormItem {...formItemLayout} label='传真'>
            {getFieldDecorator('fax', {
              initialValue: this.state.companyInformationData.fax,
              rules: [
                {
                  validator: this.checkFax
                }
              ]
            })(<Input placeholder='请输入' maxLength={13} />)}
          </FormItem>
          <FormItem {...formItemLayout} label='注册地址'>
            {getFieldDecorator('address', {
              // initialValue:[110000],
              initialValue: this.state.areaAddress,
              rules: [
                { type: 'array', required: true, message: '注册地址不能为空!' }
              ]
            })(
              // <Cascader
              //   disabled
              //   options={this.state.areas}
              //   placeholder='请选择'
              // />
              <PCascader disabled placeholder="请选择"/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label=' '
            colon={false}
            className='detailedAddress'
          >
            {getFieldDecorator('regAddress', {
              initialValue: this.state.companyInformationData.regAddress,
              rules: [
                {
                  required: true,
                  message: '请输入公司注册详细地址'
                }
              ]
            })(
              <TextArea
                rows={3}
                placeholder='请填写公司注册详细地址'
                maxLength={100}
                disabled={this.state.companyInformationData.industryType === '01'}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='办公地址'>
            {getFieldDecorator('workAddressArr', {
              // initialValue:[110000],
              initialValue: this.state.workAddress,
              rules: [
                { type: 'array', required: true, message: '办公地址不能为空!' }
              ]
            })(
              // <Cascader
              //   options={this.state.areas}
              //   placeholder='请选择'
              // />
              <PCascader placeholder="请选择"/>
            )}
          </FormItem>
          <FormItem className='detailedAddress' colon={false} {...formItemLayout} label=' '>
            {getFieldDecorator('workAddress', {
              initialValue: this.state.companyInformationData.workAddress,
              rules: [
                {
                  required: true,
                  message: '请输入办公地址'
                },
                {
                  validator: (rule, value, callback) => {
                    if (value && !/^\S{0,100}$/.test(value)) {
                      callback('请输入正确的办公地址！');
                    } else {
                      callback();
                    }
                  }
                }
              ]
            })(<TextArea 
                rows={3}
                // disabled={this.state.companyInformationData.industryType === '01'}
                placeholder='请输入'
                maxLength={50}
              />)}
          </FormItem>
          <FormItem {...formItemLayout} label='经济类型'>
            {getFieldDecorator('economicType', {
              initialValue: this.state.companyInformationData.economicType,
              rules: [{ required: true, message: '请选择经济类型' }]
            })(<Select placeholder='请选择'>{this.renderEconomic()}</Select>)}
          </FormItem>
          <FormItem {...formItemLayout} label='行业类型'>
            {getFieldDecorator('industryType', {
              initialValue: this.state.companyInformationData.industryType,
              rules: [{ required: true, message: '请选择行业类型' }]
            })(
              <Select placeholder='请选择' disabled>
                {this.renderIndustry()}
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='公司类型'>
            {getFieldDecorator('comType', {
              initialValue: this.state.companyInformationData.comType,
              rules: [{ required: true, message: '请选择公司类型' }]
            })(<Select placeholder='请选择'>{this.renderCompany()}</Select>)}
          </FormItem>
          <FormItem {...formItemLayout} label='机构类型'>
            {getFieldDecorator('institutionType', {
              initialValue: this.state.companyInformationData.institutionType,
              rules: [{ required: true, message: '请选择机构类型' }]
            })(
              <Select placeholder='请选择' disabled>
                {this.renderInstitution()}
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='是否为分/子公司'>
            {getFieldDecorator('isBranchCom', {
              initialValue: this.state.companyInformationData.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>
          {this.state.isBranch === '1' || this.state.isBranch === '2' ? (
            <FormItem {...formItemLayout} label='总公司名称'>
              {getFieldDecorator('parentComName', {
                initialValue: this.state.companyInformationData.parentComName,
                rules: [
                  {
                    required: true,
                    message: '请输入总公司名称'
                  },
                  {
                    validator: this.checkParentComName
                  }
                ]
              })(<Input placeholder='请输入' maxLength={50} />)}
            </FormItem>
          ) : (
            ''
          )}
          {this.state.isBranch === '1' || this.state.isBranch === '2' ? (
            <FormItem {...formItemLayout} label='总公司统一社会信用代码'>
              {getFieldDecorator('parentComCerNo', {
                initialValue: this.state.companyInformationData.parentComCerNo,
                rules: [
                  {
                    required: true,
                    message: '请输入总公司统一社会信用代码'
                  },
                  {
                    validator: this.checkParentComCerNo
                  }
                ]
              })(<Input placeholder='请输入' maxLength={20} />)}
            </FormItem>
          ) : (
            ''
          )}
          {this.state.isBranch === '1' || this.state.isBranch === '2' ? (
            <FormItem {...formItemLayout} label='总公司法人'>
              {getFieldDecorator('parentComRep', {
                initialValue: this.state.companyInformationData.parentComRep,
                rules: [
                  {
                    required: true,
                    message: '请输入总公司法人'
                  },
                  {
                    validator: this.checkParentComRep
                  }
                ]
              })(<Input placeholder='请输入' maxLength={10} />)}
            </FormItem>
          ) : (
            ''
          )}
          {this.state.isBranch === '1' || this.state.isBranch === '2' ? (
            <FormItem {...formItemLayout} label='总公司联系电话'>
              {getFieldDecorator('parentComTel', {
                initialValue: this.state.companyInformationData.parentComTel,
                rules: [
                  {
                    required: true,
                    message: '请输入总公司联系电话'
                  },
                  {
                    validator: this.checkPhone
                  }
                ]
              })(<Input placeholder='请输入' maxLength={13} />)}
            </FormItem>
          ) : (
            ''
          )}
          <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
            {/*loading={this.state.loading}*/}
            <Button type='primary' style={{ marginLeft: 8 }} htmlType='submit'>
              提交
            </Button>
          </FormItem>
        </Form>
        <Modal
          title='管理员确认'
          visible={this.state.administratorRelative.openValidAdminModal}
          onOk={this.handleValidAdminModalOk}
          onCancel={this.handleValidAdminModalCancel}
        >
          <Form>
            <FormItem {...formItemLayoutMore} label='姓名' className='code_yan'>
              <Input
                className='set-input'
                disabled
                value={this.state.administratorRelative.administrator}
              />
            </FormItem>
            <FormItem
              {...formItemLayoutMore}
              label='手机号码'
              className='code_yan'
            >
              <div style={{ display: 'flex' }}>
                <Input
                  className='set-input'
                  disabled
                  value={
                    this.state.administratorRelative.phoneValueHiddenMiddle
                  }
                  style={{ flex: 1 }}
                />
                {this.getAdminValidCodeButton()}
              </div>
            </FormItem>
            <FormItem
              {...formItemLayoutMore}
              label='验证码'
              className='code_yan'
            >
              {getFieldDecorator('adminValidCode', {
                rules: [
                  {
                    message: '请输入手机验证码！'
                  },
                  {
                    validator: this.checkPhoneCodeVlue
                  }
                ]
              })(
                <div>
                  <Input
                    placeholder='请输入手机验证码'
                    maxLength={6}
                    id='code_a5'
                    onChange={this.codeChangeFour}
                  />
                  <p
                    id='code_p5'
                    style={{
                      marginBottom: 0,
                      color: 'red',
                      display: 'none',
                      fontSize: '14px',
                      lineHeight: '1.5',
                      marginTop: '2px'
                    }}
                  >
                    错误
                  </p>
                </div>
              )}
            </FormItem>
          </Form>
        </Modal>
      </div>
    );
  }
}
