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 PFromUpload from '../../../components/Pro/PFromUpload';
import {
  publicCommonDictGetDictByCodeTypes, //公共信息
  //systemPerCerBaseInfoFind,//编辑证书-查看证书-展示当前证书信息
  systemPerCerBaseInfoGet, //编辑证书-查看证书-展示当前证书信息-完整模板
  systemPerCerBaseInfoUpdate //编辑证书-修改-保存用户证书
  //systemConfigPerCerInfoFindListByPercertype,//新增证书-查看证书特殊信息字段；编辑证书-查看已创建证书特殊信息字段和字段值
} 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 EditCertificateDrawer extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      perId: '',
      editCertificateOpen: this.props.visiable, //抽屉
      currentId: 0, //当前ID
      perCerType: this.props.perCerType || [], //证书类型
      // perCerlevel: [],//证书等级
      //certificateType: '1',
      //specialFields: [],
      // editList: this.props.editList,
      // editSpecialArray: this.props.editSpecialArray,
      editList: {
        perCerType: '', //证书类型
        cerNo: '', //证书编号
        licenceOrg: '', //发证机关
        licenceOrgNo: '', //发证机关编号
        licenceDate: '' //发证日期
        //cerNo:'',//证书类型
      },
      editSpecialArray: []
    };
  }
  /******************************生命周期******************************/

  componentDidMount = () => {
    // this.getAllType(); //获取所有类型
    // this.getSpecialFields();//特殊字段
    //this.showCertificateInfo(this.state.currentId);//查看证书
  };
  componentWillReceiveProps(props) {
    this.setState({
      editCertificateOpen: props.visiable,
      perId: props.perId,
      perCerType: props.perCerType
    });
    if (!!props.visiable) {
      if (
        props.currentId !== this.state.currentId ||
        this.state.editCertificateOpen !== props.visiable
      ) {
        this.setState({ currentId: props.currentId }, () => {
          if (props.currentId !== 0) {
            // this.showCertificateInfo(props.currentId);//查看证书
            systemPerCerBaseInfoGet({ perCerId: this.state.currentId }).then(
              res => {
                // res.data.list = JSON.parse(res.data.list).map((item)=>{
                //   console.log(item);
                //   item.fieldValue && item.fieldValue === 'Invalid data'? item.fieldValue = '' : '';
                //   return item;
                // });
                this.setState({
                  editList: res.data,
                  editSpecialArray: JSON.parse(res.data.list)
                });
              },
              err => {
                console.log('查看当前证书-错误信息', err);
              }
            );
          }
        });
      }
    }
  }
  /******************************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);
  //   });
  // }

  //查看证书
  // showCertificateInfo = (perCerId) => {
  //   // const perCerId = this.state.currentId;
  //   systemPerCerBaseInfoGet({ perCerId }).then((res) => {
  //     this.setState(
  //       {
  //         editList: res.data,
  //         editSpecialArray: JSON.parse(res.data.list),
  //       }
  //     );
  //   }, (err) => {
  //     console.log('查看当前证书-错误信息', err);
  //   });
  // }

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

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

  renderMap = (
    fieldType,
    fieldName,
    fieldCode,
    isRequired,
    fieldValue,
    maxLength,
    dictList,
    perCerSpecialInfoId
  ) => {
    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}`, {
            initialValue: fieldValue || '',
            rules: [
              {
                required: isRequired,
                message: `请输入${fieldName}`
              },
              perCerSpecialInfoId === 520658738273583100
                ? { pattern: /^[^\u4e00-\u9fa5]+$/, message: '不能输入中文' }
                : ''
            ]
          })(<Input disabled={this.props.isCheck} placeholder='请输入' maxLength={maxLength} />)}
        </FormItem>
      );
    } else if (fieldType === '4') {
      //保安员等级证
      return (
        <FormItem {...formItemLayout} label={fieldName}>
          {getFieldDecorator(`${fieldCode}`, {
            // initialValue: fieldValue || '',
            initialValue: this.state.editList.perCerLevel || '',
            rules: [
              {
                required: isRequired,
                message: `请选择${fieldName}`
              }
            ]
          })(
            <Select disabled={this.props.isCheck} 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}`, {
            initialValue:
              fieldValue && fieldValue !== undefined
                ? moment(fieldValue, dateFormat)
                : null,
            rules: [
              {
                required: isRequired,
                message: `请选择${fieldName}`
              }
            ]
          })(<DatePicker disabled={this.props.isCheck} placeholder='请选择' style={{ width: '100%' }} />)}
          {/* <span>{console.log(fieldValue)}</span> */}
        </FormItem>
      );
    }
  };

  //表单提交
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const perCerId = this.state.currentId; //人员ID
        let list = [];
        if (values) {
          for (let [k, v] of Object.entries(values)) {
            this.state.editSpecialArray.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.editSpecialArray;
        }
        list = JSON.stringify(list);

        const { perId } = this.state.perId; //人员ID
        const obj = {
          perId,
          perCerId,
          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;
        systemPerCerBaseInfoUpdate(obj).then(
          res => {
            if (res.retType === '0') {
              this.setState({ editCertificateOpen: false });
              this.props.refreshList();
            }
          },
          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
          title='证书编辑'
          // overlayColor="rgba(0, 0, 0,0)"
          placement='right'
          visible={this.state.editCertificateOpen}
          // noTouchClose
          width={600}
          // zIndex={999}
          // className="drawer-box"
          onChange={editCertificateOpen => {
            this.props.onChange(editCertificateOpen);
            this.setState({ editCertificateOpen });
          }}
          onClose={() => this.setState({ editCertificateOpen: 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='证书类型'>
                  {getFieldDecorator('perCerType', {
                    initialValue: this.state.editList.perCerType,
                    rules: [{ required: true, message: '请选择证书类型!' }]
                  })(
                    <Select disabled className='sls-style'>
                      {this.renderCertificateType()}
                    </Select>
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label='证书编号'>
                  {getFieldDecorator('cerNo', {
                    initialValue: this.state.editList.cerNo,
                    rules: [
                      {
                        required: true,
                        message: '请输入证书编号'
                      },
                      {
                        // pattern: /^([A-Za-z0-9])|(.){6,20}$/,
                        pattern: /.{6,50}$/,
                        message: '格式错误！'
                        // pattern: /^[^\u4e00-\u9fa5]+$/,
                        // message: '不能输入中文！'
                      }
                    ]
                  })(<Input disabled={this.props.isCheck} placeholder='请输入' maxLength={20} />)}
                </FormItem>
                <FormItem {...formItemLayout} label='发证机关:'>
                  {getFieldDecorator('licenceOrg', {
                    initialValue: this.state.editList.licenceOrg,
                    rules: [
                      {
                        required: true,
                        message: '请输入发证机关'
                      }
                      //   , {
                      //   validator: this.checkPhone
                      // }
                    ]
                  })(<Input disabled={this.props.isCheck} placeholder='请输入' maxLength={20} />)}
                </FormItem>
                <FormItem {...formItemLayout} label='发证机关编号'>
                  {getFieldDecorator('licenceOrgNo', {
                    initialValue: this.state.editList.licenceOrgNo,
                    rules: [
                      {
                        required: false,
                        message: '请输入发证机关编号'
                      },
                      {
                        pattern: /^([A-Za-z0-9])|(.){6,20}$/,
                        message: '格式错误！'
                      }
                    ]
                  })(<Input disabled={this.props.isCheck} placeholder='请输入' maxLength={20} />)}
                </FormItem>
                <FormItem {...formItemLayout} label='发证日期'>
                  {getFieldDecorator('licenceDate', {
                    initialValue: this.state.editList.licenceDate
                      ? moment(this.state.editList.licenceDate, dateFormat)
                      : null,
                    rules: [
                      {
                        type: 'object',
                        required: true,
                        message: '请选择证书发证日期'
                      }
                    ]
                  })(
                    <DatePicker
                      disabled={this.props.isCheck}
                      placeholder='请选择证书发证日期'
                      style={{ width: '100%' }}
                    />
                  )}
                </FormItem>
                {this.showSpecialFields()}
                {this.state.editList.electronCerUrl &&
                  <FormItem
                    {...formItemLayout}
                    label="电子证书二维码"
                  // help="每张不超过:8M,格式为:jpg，jpeg，png"
                  >
                    {getFieldDecorator('electronicCertificate', {
                      initialValue: this.state.editList.qrCodeUrl,
                      rules: [
                        {
                          // required: true,
                          message: '请上传电子证书'
                        }
                      ]
                    })(
                      <PFromUpload
                        num={1}
                        disabled={true}
                      />
                    )}
                    {
                      this.state.editList.electronCerUrl && <a target="_blank" href={this.state.editList.electronCerUrl}>在线查看电子证书</a>
                    }
                    {
                      !this.state.editList.electronCerUrl && <span>没有查询到相关电子证书</span>
                    }
                  </FormItem>
                }
              </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
                style={{
                  marginRight: 8
                }}
                onClick={() => this.setState({ editCertificateOpen: false })}
              >
                取消
              </Button>
              <Button
                disabled={this.props.isCheck}
                type='primary'
                htmlType='submit'
                onClick={this.handleSubmit}
              >
                确认修改
              </Button>
            </div>
          </div>
        </Drawer>
      </Box>
    );
  }
}

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

const Box = style.div`{
  .drawer-content{
    margin-top:28px;
  }
}`;
