/**
 * @author  Xyz
 * 分公司管理-分公司详情
 */
import PDrawer from '../../../components/Pro/PDrawer';
import React from 'react';
import {
  Form,
  Input,
  Row, Col,
  Button,
  Modal,
  notification,
  DatePicker,
  Popover,
  Icon
} from 'antd';
import { formItemLayout1 } from './constants';
import { DrawHeader, Empty, DrawBottomBtns } from './styles';
import { OrganName } from './components';
import PCascader from '../../../components/Pro/PCascader';
import {
  RegNumber15,
  RegNumber18,
  RegString50,
  RegChinese100,
  RegChineseEnglish10,
  RegPhone11,
  RegPersonNo,
  RegString20,
  ChineseEnglish100,
  RegChineseEnglish100,
  RegNormal
} from '../../../constants/regexps';
import {
  enterpriseCompanyComBaseInfoGetComBaseInfoById,
  systemComBaseInfoSaveBranch,
  enterpriseCompanySendLegalAuthCode,
  getConfigComBranch
} from '../../../services/api';

import bcx_utils from '../../../common/bcx_utils';

const { TextArea } = Input;
const FormItem = Form.Item;
@Form.create()
export default class DrawBranchCompanyDetail extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      dataSource: {
        comName: "",
        chargePerName: "",
        chargePerPhone: "",
        // legalRepName: "",
        // legalRepPhone: "",
        comCerNo: "",
        regProvince: "",
        regCity: "",
        regArea: "",
        manageProvince: "",
        manageCity: "",
        manageArea: "",
        manageAddress: "",
        recordPolice: "",
        recordDate: "",
        regAddress: "",
        idCardNo: ""
      },
      comBranchId: "", //通过comBranchId判断是否是查看详情还是新增分公司
      codeTime: 0,  //短信验证码倒计时
    }
  }

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

  componentDidMount = () => {

  }

  componentWillReceiveProps = (nextProps, newState) => {
    if (!this.props.visible && nextProps.visible && nextProps.comBranchId.trim() !== "") {
      this.ajaxDetail(nextProps.comBranchId);
      this.setState({ comBranchId: nextProps.comBranchId });
    }
    if (!this.props.visible && nextProps.visible && nextProps.comBranchId.trim() === "") {
      this.setState({
        comBranchId: ''
      });
      this.resetForm();
    }
  }
  
  /******************************ajax请求******************************/
  //重置表单
  resetForm = () => {
    const dataSource = {
      comName: "",
      chargePerName: "",
      chargePerPhone: "",
      // legalRepName: "",
      // legalRepPhone: "",
      comCerNo: "",
      regProvince: "",
      regCity: "",
      regArea: "",
      manageProvince: "",
      manageCity: "",
      manageArea: "",
      manageAddress: "",
      recordPolice: "",
      recordDate: bcx_utils.currentData(),
      comBranchId: "",
      regAddress: "",
      idCardNo: "",
    };
    this.setState({ dataSource });
  }
  ajaxDetail = (comBranchId) => {
    enterpriseCompanyComBaseInfoGetComBaseInfoById({ comBranchId }).then(({ data = {} }) => {
      const dataSource = { ...this.state.dataSource };
      this.setState({ dataSource: { ...dataSource, ...data } });
    }, (err) => {
      console.log(err);
    });

  }

  /******************************相关事件******************************/
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {

        const ajaxParam = { ...values };
        const { comBranchId } = this.state;
        const { regProvince: [r1, r2, r3], 
          // manageProvince: [m1, m2, m3],
           recordDate } = ajaxParam;

        ajaxParam.regProvince = r1;
        ajaxParam.regCity = r2;
        ajaxParam.regArea = r3;

        // ajaxParam.manageProvince = m1;
        // ajaxParam.manageCity = m2;
        // ajaxParam.manageArea = m3;

        ajaxParam.recordDate = bcx_utils.formatData(ajaxParam.recordDate);

        if (comBranchId.trim() !== "") {
          ajaxParam.comBranchId = comBranchId;
        }
        bcx_utils.preventRA(resolve => {
          this.systemComBaseInfoSaveBranch(ajaxParam, resolve);
        });
      }
    });
  }
  //保存修改
  systemComBaseInfoSaveBranch = (ajaxParam, resolve) => {
    systemComBaseInfoSaveBranch(ajaxParam).then((data) => {
      this.props.updataTable();
      this.props.confirDrawer();
      this.props.success();
      resolve();
    }, (err) => {
      console.log(err);
      resolve();
    });
  }

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


  /******************************render******************************/

  render() {
    const { visible } = this.props;
    const { getFieldDecorator } = this.props.form;
    const {
      comName,
      chargePerName,
      chargePerPhone,
      // legalRepName,
      // legalRepPhone,
      comCerNo,
      manageProvince,
      manageCity,
      manageArea,
      manageAddress,
      regProvince,
      regCity,
      regArea,
      regAddress,
      recordPolice,
      recordDate,
      idCardNo,
    } = this.state.dataSource;
    return (
      <PDrawer
        // title="分公司详情"
        title={this.state.comBranchId?'分公司详情': '添加分公司'}
        visible={visible}
        okText={this.state.comBranchId==''?'开通': null}
        cancelText="返回"
        onCancel={this.closeDrawer}
        onOk={this.handleSubmit}
        destroyOnClose={true}
      >
        <div>
          <Form onSubmit={this.handleSubmit} style={{ width: 390, margin: "6px 0 81px 0" }}>
            <FormItem
              {...formItemLayout1}
              label="分公司名称"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('comName', {
                initialValue: comName,
                rules: [RegString50, {
                  required: true, message: RegString50.message,
                }],
              })(
                <Input style={{ width: 294 }} disabled={this.state.comBranchId == ''? false: true} />
              )}
            </FormItem>
            {/* <FormItem
              {...formItemLayout1}
              label="统一社会信用代码"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('comCerNo', {
                initialValue: comCerNo,
                rules: [RegNumber18, {
                  required: true, message: RegNumber18.message,
                }],
              })(
                <Input style={{ width: 294 }} placeholder="请输入" disabled={this.state.comBranchId == ''? false: true} />
              )}
            </FormItem> */}
            <FormItem
              {...formItemLayout1}
              label="注册地址"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('regProvince', {
                initialValue: [regProvince, regCity, regArea],
                rules: [{
                  required: true, message: '请选择!',
                }],
              })(
                <PCascader onChange={value => {
                  const [ provinceId = ''] = value;
                  if(!provinceId) {
                    return;
                  }
                  getConfigComBranch({provinceId}).then(res => {
                    
                    // setFieldsValue
                    // 0：不需要  1：需要备案
                    const { isNeedPoliceRecord } = res.data;
                    
                    // 需要备案
                    if(isNeedPoliceRecord == '1') {
                      // 该省份无法直接创建分公司，请访问【业务】-【备案许可申报】进行设立分公司备案后，系统自动创建分公司。
                      this.props.form.setFieldsValue({regProvince: []});
                      Modal.error({
                        title: '该省份无法直接创建分公司，请访问【业务】-【备案许可申报】进行设立分公司备案后，系统自动创建分公司。'
                      })
                    }
                  });
                }} style={{ width: 294 }} placeholder="请选择" disabled={this.state.comBranchId == ''? false: true} />
              )}
            </FormItem>
            <Empty>
              <FormItem
                {...formItemLayout1}
                label=""
                style={{ marginTop: 24,}}
              >
                {getFieldDecorator('regAddress', {
                  initialValue: regAddress,
                  rules: [RegNormal, {
                    required: true, message: RegNormal.message,
                  }],
                })(
                  <TextArea autosize={{ minRows: 1, maxRows: 3 }} style={{ width: 294, maxWidth:294 }} placeholder="请填写公司注册详细地址" disabled={this.state.comBranchId == ''? false: true} />
                )}
              </FormItem>
            </Empty>

            {/* <FormItem
              {...formItemLayout1}
              label="经营地址"
              style={{marginTop: 24}}
            >
              {getFieldDecorator('manageProvince', {
                initialValue: [manageProvince, manageCity, manageArea],
                rules: [{
                  required: true, message: '请选择',
                }]
              })(
                <PCascader style={{width: 294}} placeholder="请选择" disabled={this.state.comBranchId == ''? false: true}/>
              )}
            </FormItem>
            <Empty>
              <FormItem
                {...formItemLayout1}
                label=""
                style={{ marginTop: 24 }}
              >
                {getFieldDecorator('manageAddress', {
                  initialValue: manageAddress,
                  rules: [RegNormal, {
                    required: true, message: RegNormal.message,
                  }],
                })(
                  <Input style={{ width: 294 }} placeholder="请填写公司注册详细地址" disabled={this.state.comBranchId == ''? false: true} />
                )}
              </FormItem>
            </Empty> */}
            <FormItem
              {...formItemLayout1}
              label="负责人"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('chargePerName', {
                initialValue: chargePerName,
                rules: [ChineseEnglish100, {
                  required: true, message: ChineseEnglish100.message,
                }],
              })(
                <Input style={{ width: 294 }} placeholder="请输入" disabled={this.state.comBranchId == ''? false: true} />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="负责人身份证号"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('idCardNo', {
                initialValue: idCardNo,
                rules: [RegPersonNo, {
                  required: true, message: RegPersonNo.message,
                }],
              })(
                <Input style={{ width: 294 }} placeholder="请输入" disabled={this.state.comBranchId == ''? false: true} />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout1}
              label="负责人手机号"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('chargePerPhone', {
                initialValue: chargePerPhone,
                rules: [RegPhone11, {
                  required: true, message: RegPhone11.message,
                }],
              })(
                this.state.comBranchId?<Input placeholder="请输入" disabled={this.state.comBranchId == ''? false: true} />:
                <Row type="flex" justify="space-between">
                  <Col span={20} style={{width: 294}}>
                    <Input style={{ width: '100%' }} placeholder="请输入" disabled={this.state.comBranchId == ''? false: true} />
                  </Col>
                  {/* <Col span={2}>
                    <Button 
                      type="primary"
                      disabled={this.state.codeTime > 0? true: false}
                      onClick={() => {
                        const phone = this.props.form.getFieldValue('chargePerPhone');
                        if(this.state.codeTime <= 0){
                          if(!RegPhone11.pattern.test(phone)) {
                            return notification.error({
                              message: '请输入正确的手机号'
                            });
                          }
                          enterpriseCompanySendLegalAuthCode({phone}).then(() => {
                            clearInterval(this.timer);
                            this.setState({
                              codeTime: 59
                            });
                            this.timer = setInterval(() => {
                              this.setState({
                                codeTime: --this.state.codeTime
                              });
                            }, 1000);
                          });
                        }
                    }}>
                    {(() => {
                      if(this.state.codeTime > 0) {
                        return `${this.state.codeTime}秒后重试`;
                      }else {
                        return '获取验证码';
                      }
                    })()}
                    </Button>
                  </Col> */}
                </Row>
              )}
            </FormItem>
            {/* {
              !this.state.comBranchId&&<FormItem
              {...formItemLayout1}
              label="手机验证码"
              style={{ marginTop: 24 }}
            >
              {getFieldDecorator('code', {
                rules: [{
                  required: true, message: '请输入短信验证码',
                }],
              })(
                <Input style={{ width: 294 }} placeholder="请输入" disabled={this.state.comBranchId == ''? false: true} />
              )}
            </FormItem>
            } */}
            
            
            {/* <FormItem
              {...formItemLayout1}
              label="备案公安机关名称"
              style={{marginTop: 24}}
            >
              {getFieldDecorator('recordPolice', {
                initialValue: recordPolice,
                rules: [RegString20, {
                  required: true, message: RegString20.message,
                }],
              })(
                <Input style={{width: 294}} placeholder="请输入" disabled={this.state.comBranchId == ''? false: true}/>
              )}
              <Popover content={OrganName} trigger="hover" placement="topRight">
                <div style={{color: "#D9D9D9", position: "absolute", top: "-11px", right: "-28px", width: "22px"}}>
                  <Icon type="exclamation-circle"/>
                </div>
              </Popover>
            </FormItem> */}
            {/* <FormItem
              {...formItemLayout1}
              label="备案日期"
              style={{marginTop: 24}}
            >
              {getFieldDecorator('recordDate', {
                initialValue: moment(recordDate, 'YYYY-MM-DD'),
                rules: [{
                  required: true, message: 'Please input your E-mail!',
                }],
              })(
                <DatePicker style={{width: 294}} disabled={this.state.comBranchId == ''? false: true}/>
              )}
            </FormItem> */}
          </Form>
        </div>
      </PDrawer>
    );
  }
}
