import React, { PureComponent } from 'react';
// import { connect } from 'dva';
import style from 'styled-components';
import {
  Input,
  Button,
  Form,
  Select,
  Card,
  Row,
  Col,
  Icon,
  Modal,
  DatePicker,
  message,
  Drawer
} from 'antd';
// import Drawer from 'react-motion-drawer';
import moment from 'moment';
import "moment/locale/zh-cn";

import {
  publicCommonDictGetDictByCodeTypes, //公共信息
  systemConfigPerCerInfoFindListByPercertype, //新增证书-查看证书特殊信息字段
  systemPerCerBaseInfoSave //新增证书-保存
} from '../../../services/api';

const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
// const RadioGroup = Radio.Group;
const { TextArea } = Input;
const dateFormat = 'YYYY-MM-DD';
message.config({
  top: 100,
  right: 5,
  duration: 2
});

// @connect(state => ({ profile: state.profile }))
@Form.create()

// 新增证书-抽屉
export default class NewCertificateDrawer extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      newCertificateOpen: this.props.visiable, //抽屉
      perCerType: this.props.perCerType || [], //证书类型
      // perCerlevel: [],//证书等级
      certificateType: '1',
      specialFields: [],
      perId: '',
      // currentDate: new Date().toLocaleDateString()
      currentDate: moment().format('YYYY-MM-DD')
    };
  }
  /******************************生命周期******************************/

  componentDidMount = () => {
    // this.getAllType(); //获取所有类型
    // this.getSpecialFields();//特殊字段
  };
  componentWillReceiveProps(props) {
    this.setState(
      {
        newCertificateOpen: props.visiable,
        perId: props.perId,
        perCerType: props.perCerType
      }
    );
  }
  /******************************ajax请求******************************/
  //获得公共信息
  getAllType = () => {
    publicCommonDictGetDictByCodeTypes({ codeTypes: [' perCerType'] }).then(
      res => {
        //判断获取数据是否为空
        if (res.data) {
          const allTypeData = res.data;
          this.setState({
            perCerType: allTypeData.perCerType
            // perCerlevel: allTypeData.perCerlevel,
          });
        }
      }
    );
  };

  //新增证书-查看证书特殊信息字段
  getSpecialFields = () => {
    const perCerType = this.state.certificateType;
    systemConfigPerCerInfoFindListByPercertype({ perCerType }).then(
      res => {
        if (res.data) {
          this.setState({
            specialFields: res.data
          });
        }
      },
      err => {
        console.log('新增特殊字段-错误信息', err);
      }
    );
  };

  /******************************相关事件******************************/
  changeCertificateType = value => {
    if (value) {
      this.setState({
        specialFields: [],
        certificateType: value
      });
      systemConfigPerCerInfoFindListByPercertype({ perCerType: value }).then(
        res => {
          if (res.data) {
            this.setState({
              specialFields: res.data
            });
          }
        },
        err => {
          console.log('新增特殊字段-错误信息', err);
        }
      );
    }
  };

  showFixedFields = () => {
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 12
        },
        md: {
          span: 10
        }
      }
    };
    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        <FormItem {...formItemLayout} label='证书编号'>
          {getFieldDecorator('cerNo', {
            rules: [
              {
                required: true,
                message: '请输入证书编号'
              },
              {
                // pattern: /^([A-Za-z0-9])|(.){6,20}$/,
                pattern: /.{6,50}$/,
                message: '格式错误！'
                // pattern: /^[^\u4e00-\u9fa5]+$/,
                // message: '不能输入中文！'
              }
            ]
          })(<Input placeholder='请输入' maxLength={20} />)}
        </FormItem>
        <FormItem {...formItemLayout} label='发证机关:'>
          {getFieldDecorator('licenceOrg', {
            rules: [
              {
                required: true,
                message: '请输入发证机关'
              }
              //   , {
              //   validator: this.checkPhone
              // }
            ]
          })(<Input placeholder='请输入' maxLength={20} />)}
        </FormItem>
        <FormItem {...formItemLayout} label='发证机关编号'>
          {getFieldDecorator('licenceOrgNo', {
            rules: [
              {
                required: false,
                message: '请输入发证机关编号'
              },
              {
                // pattern: /^([A-Za-z0-9])|(.){6,20}$/,
                // message: '格式错误！'
                pattern: /^[^\u4e00-\u9fa5]+$/,
                message: '不能输入中文！'
              }
            ]
          })(<Input placeholder='请输入' maxLength={20} />)}
        </FormItem>
        <FormItem {...formItemLayout} label='发证日期'>
          {getFieldDecorator('licenceDate', {
            rules: [
              {
                type: 'object',
                required: true,
                message: '请选择证书发证日期'
              }
            ]
          })(
            <DatePicker
              format={dateFormat}
              placeholder='请选择证书发证日期'
              style={{ width: '100%' }}
            />
          )}
        </FormItem>
      </div>
    );
  };

  showSpecialFields = () => {
    const arr = this.state.specialFields.map((value, index) => {
      return (
        <div key={index}>
          {this.renderMap(
            value.fieldType,
            value.fieldName,
            value.fieldCode,
            value.isRequired,
            value.maxLength,
            value.dictList
          )}
        </div>
      );
    });
    return arr;
  };

  renderMap = (
    fieldType,
    fieldName,
    fieldCode,
    isRequired,
    maxLength,
    dictList
  ) => {
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 12
        },
        md: {
          span: 10
        }
      }
    };
    const { getFieldDecorator } = this.props.form;

    if (fieldType === '1') {
      //持枪证
      return (
        <FormItem {...formItemLayout} label={fieldName}>
          {getFieldDecorator(`${fieldCode}`, {
            rules: [
              {
                required: isRequired,
                message: `请输入${fieldName}`
              }
            ]
          })(<Input placeholder='请输入' maxLength={maxLength} />)}
        </FormItem>
      );
    } else if (fieldType === '4') {
      //保安员等级证
      return (
        <FormItem {...formItemLayout} label={fieldName}>
          {getFieldDecorator(`${fieldCode}`, {
            rules: [
              {
                required: isRequired,
                message: `请选择${fieldName}`
              }
            ]
          })(
            <Select placeholder='请选择' className='sls-style'>
              {/* <Option value=' '>请选择</Option> */}
              {/* {this.renderCertificateLevel()} */}
              {dictList.map((val, i) => {
                return (
                  <Option key={i} value={val.codeValue + ''}>
                    {val.label}
                  </Option>
                );
              })}
            </Select>
          )}
        </FormItem>
      );
    } else if (fieldType === '9') {
      //保安员资格证
      return (
        <FormItem {...formItemLayout} label={fieldName}>
          {getFieldDecorator(`${fieldCode}`, {
            rules: [
              {
                required: isRequired,
                message: `请选择${fieldName}`
              }
            ]
          })(
            <DatePicker
              format={dateFormat}
              placeholder='请选择'
              style={{ width: '100%' }}
            />
          )}
        </FormItem>
      );
    }
  };

  //表单提交
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { perId } = this.state.perId; //人员ID
        let list = [];
        if (values) {
          for (let [k, v] of Object.entries(values)) {
            this.state.specialFields.map(val => {
              if (val.fieldCode === k) {

                if (typeof v === 'object') {
                  v = moment(v).format(dateFormat);
                  val.fieldValue = v;
                } else {
                  val.fieldValue = v;
                }
              }
              return true;
            });
          }
          list = this.state.specialFields;
        }


        /**
         *后端校验，字段是动态的不确定值，以后可能还有其他证书类型。
         */
        const timeArr = list
          .filter(v => v.fieldType === '9')
          .map(v => v.fieldValue);
        const time = new Date(
          values.licenceDate ? values.licenceDate.format('YYYY-MM-DD') : ''
        ).getTime(); //发证日期

        // var sTime = new Date(list[1].fieldValue).getTime(); // 开始日期
        // var eTime = new Date(list[2].fieldValue).getTime(); // 结束日期
        const sTime = new Date(timeArr[0]).getTime(); // 开始日期
        const eTime = new Date(timeArr[1]).getTime(); // 结束日期
        const cTime = new Date(this.state.currentDate).getTime(); // 当前日期

        const { certificateType } = this.state;
        if (time > cTime) {
          message.error('发证时间不能大于当前日期');
        } else if (eTime > cTime && certificateType !== '3') {
          message.error('培训结束时间不能大于当前日期');
        } else if (sTime > eTime) {
          if (certificateType !== '3') {
            message.error('培训开始日期不能大于结束日期');
          } else {
            message.error('有效期开始日期不能大于结束日期');
          }
        } else {
          list = JSON.stringify(list);

          const obj = {
            perId,
            perCerType: values.perCerType ? values.perCerType : '', //证书类型
            cerNo: values.cerNo ? values.cerNo : '', //证书编号
            licenceOrg: values.licenceOrg ? values.licenceOrg : '', //发证机关
            licenceOrgNo: values.licenceOrgNo ? values.licenceOrgNo : '', //发证机关编号
            licenceDate: values.licenceDate
              ? values.licenceDate.format('YYYY-MM-DD')
              : '', //发证日期
            //perCerLevel: values.perCerLevel ? values.perCerLevel : '',//证书等级
            list
          };
          obj.perId = this.state.perId;
          systemPerCerBaseInfoSave(obj).then(
            res => {
              if (res.retType === '0') {
                this.setState({ newCertificateOpen: false });
                this.props.refreshList();
                const { setFieldsValue } = this.props.form;
                setFieldsValue({
                  perCerType: '', //证书类型
                  cerNo: '', //证书编号
                  licenceOrg: '', //发证机关
                  licenceOrgNo: '', //发证机关编号
                  licenceDate: '' //发证日期
                });
                const listArray = JSON.parse(list);
                const newListArray = [];
                for (const value of listArray) {
                  newListArray.push(value.fieldCode);
                }
                for (let i = 0; i < newListArray.length; i++) {
                  setFieldsValue({
                    [newListArray[i]]: ''
                  });
                }
              }
            },
            error => {
              console.log('错误信息-新增证书：', error);
            }
          );
        }
      }
    });
  };
  //证书类型
  renderCertificateType = () => {
    return this.state.perCerType.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ''}>
          {val.label}
        </Option>
      );
    });
  };

  //证书等级
  // renderCertificateLevel = () => {
  //   return this.state.perCerlevel.map((val, key) => {
  //     return <Option key={key} value={val.codeValue + ""}>{val.label}</Option>;
  //   });
  // };

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

  render() {
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 12
        },
        md: {
          span: 10
        }
      }
    };
    const { getFieldDecorator } = this.props.form;

    return (
      <Box>
        <Drawer
          // overlayColor='rgba(0, 0, 0,0)'
          placement='right'
          visible={this.state.newCertificateOpen}
          title='新增证书'
          // noTouchClose
          width={600}
          // zIndex={999}
          // className="drawer-box"
          onChange={newCertificateOpen => {
            this.props.onChange(newCertificateOpen);
            this.setState({ newCertificateOpen });
          }}
          onClose={() => this.setState({ newCertificateOpen: false })}
          destroyOnClose
          style={{
            height: 'calc(100% - 55px)',
            overflow: 'auto',
            paddingBottom: 53
          }}
        >
          {/* <div className="drawer"> */}
          <div>
            {/* <div className="drawer-header">新增证书</div> */}
            {/* <div className="drawer-content"> */}
            <div>
              <Form onSubmit={this.handleSubmit}>
                <FormItem
                  {...formItemLayout}
                  label='证书类型'
                  extra={
                    <span style={{ color: 'red' }}>
                      每种证书类型仅可添加一次，若您的证书有升级或变更信息，请进行编辑。
                    </span>
                  }
                >
                  {getFieldDecorator('perCerType', {
                    rules: [{ required: true, message: '请选择证书类型!' }]
                  })(
                    <Select
                      onChange={this.changeCertificateType}
                      placeholder='请选择证书类型'
                      className='sls-style'
                    >
                      {this.renderCertificateType()}
                    </Select>
                  )}
                </FormItem>
                {this.showFixedFields()}
                {this.showSpecialFields()}
              </Form>
            </div>
            {/* <div className='drawer-footer'> */}
            <div
              style={{
                position: 'absolute',
                zIndex: 1,
                bottom: 0,
                width: '100%',
                borderTop: '1px solid #e8e8e8',
                padding: '10px 16px',
                textAlign: 'right',
                left: 0,
                background: '#fff',
                borderRadius: '0 0 4px 4px'
              }}
            >
              <Button
                onClick={() => this.setState({ newCertificateOpen: false })}
                style={{
                  marginRight: 8
                }}
              >
                取消
              </Button>
              <Button
                type='primary'
                htmlType='submit'
                onClick={this.handleSubmit}
              >
                确认新增
              </Button>
            </div>
          </div>
        </Drawer>
      </Box>
    );
  }
}

/************************样式************************/

const Box = style.div`{
  .drawer-content{
    margin-top:28px;
  }
  .ant-calendar-picker{
    width:100%;
  }
}`;
