
/*
 * Creator:     ML
 * CreatDate:   2019-11-23
 * descripts：  卡类型 卡号 读卡 组合 样式
 * 组件说明：适用于卡类型卡号作为搜索条件时使用 卡类型是否默认/补0/输入模式等走配置
 * xx:参照选择的卡类型配置的
 * 组件功能：1.选择框 是否默认选中 xx 是否默认 2.输入框placeHolder 提示信息 xx 输入模式 卡号长度 是否补0  3.读卡按钮使能，xx 输入模式 4.toolTips 悬浮框根据卡类型格式验证
 *  */
import React from 'react';
import { Form, Row, Col, Input, Select, Button, DatePicker, Modal, Table, Icon, Pagination, message, Spin, Steps, Divider, Tooltip } from 'antd';
import './style/cardType.less';
import { Util } from 'tools/index';
import { $http } from 'containers/config/https';
import ReadCard from '.././readcard/ReadCard';

//组件const
const { Search } = Input;
const Option = Select.Option;
const FormItem = Form.Item;
const CardTypeRead = Form.create()(
  class CardTypeRead extends React.Component {
    constructor(props) {
      var date = new Date()
      super(props);
      this.state = {
        patCardTypeID: "",
        initCardDr: "",
        nowRead: "",
        idCardCode: "",
        cardLength: "",
        replenishZero: "",
        repariFeeFlag: "",
        nowCost: "",
        nowInv: "",
        autoCreateCardNo: ""
      };
    }

    componentWillReceiveProps (nextProps) {

    }
    componentDidMount = () => {
      this.getCardType()
    }
    //获取卡类型
    getCardType () {
      var params = {
        params: [{
          cardTypeFlag: '1',//卡类型
        }]
      }
      $http.post('urlDeault', this, {
        code: "03030005",
        data: params,
        success: function (res) {
          if (res.errorCode == '0') {
            this.setState({
              baseParms: res,
            })
            res.cardType.map((item, i) => {
              if (item.defaultFlag == "Y") {
                this.setState({
                  patCardTypeID: item.id,
                  initCardDr: item.id,
                  nowRead: item.readMode,
                  cardLength: item.cardLength && item.cardLength != "" ? item.cardLength + "位," : "",
                  idCardCode: item.code,
                  cardLengthInput: item.cardLength,
                  replenishZero: item.replenishZero,
                  repariFeeFlag: item.repariFeeFlag,
                  nowCost: item.cardCost,
                  nowInv: item.invFlag,
                  autoCreateCardNo: item.autoCreateCardNo,
                })
                this.props.form.setFieldsValue({ cardTypeID: item.id })
                this.props.getValue(item.id, this.props.form.getFieldValue('cardNo'))
              }
            })
          }
        }
      });
    }
    //选择卡类型id
    handleSelectCard = (id) => {
      this.props.form.setFieldsValue({ cardNo: undefined })
      if (id) {
        for (var i = 0; i < this.state.baseParms.cardType.length; i++) {
          this.state.baseParms.cardType && this.state.baseParms.cardType.map((item) => {
            if (id == item.id) {
              this.setState({
                patCardTypeID: id,
                initCardDr: item.id,
                nowRead: item.readMode,
                idCardCode: item.code,
                cardLength: item.cardLength && item.cardLength != "" ? item.cardLength + "位," : "",
                replenishZero: item.replenishZero,
                repariFeeFlag: item.repariFeeFlag,
                nowCost: item.cardCost,
                nowInv: item.invFlag,
                autoCreateCardNo: item.autoCreateCardNo,
              }, () => {
                this.props.getValue(this.props.form.getFieldValue('cardTypeID'), this.props.form.getFieldValue('cardNo'))
              })
            }
          })

        }
      }
      else {
        this.setState({
          patCardTypeID: "",
          initCardDr: "",
          nowRead: "",
          idCardCode: "",
          cardLength: "",
          nowCost: "",
          nowInv: "",
          replenishZero: "",
          repariFeeFlag: "",
          autoCreateCardNo: "",
        })
        this.props.getValue("", this.props.form.getFieldValue('cardNo'))
      }
    }
    //补0配置
    handleLength = (n) => {
      this.cardTip()
      if (this.state.replenishZero == "Y" && parseInt(this.state.cardLength) && parseInt(this.state.cardLength) > 0 && this.props.form.getFieldValue('cardNo') && this.props.form.getFieldValue('cardNo').length > 0) {
        let No = this.props.form.getFieldValue('cardNo') && this.props.form.getFieldValue('cardNo') ? this.props.form.getFieldValue('cardNo') && this.props.form.getFieldValue('cardNo') : ''
        let length = parseInt(this.state.cardLength)
        let num = (Array(length).join(0) + No).slice(-length)
        this.props.form.setFieldsValue({ cardNo: num })
        this.props.getValue(this.props.form.getFieldValue('cardTypeID'), this.props.form.getFieldValue('cardNo'))
      }
      if (n && n == "1") {
        if (this.props.getQuery && this.props.getQuery) this.props.getQuery()
      }
    }
    cardTip = () => {
      // debugger
      this.props.form.validateFields(['cardNo',], (errors, values) => {
        // debugger
        if (errors == null) {
          // debugger
          return
        }
        if (!errors) {
          // debugger
          this.setState({
            cardNoVisible: false
          })
        } else {
          // debugger
          this.setState({
            cardNoVisible: true,
            cardNoMessage: errors.cardNo.errors[0].message,
          })
          setTimeout(() => {
            this.setState({
              cardNoVisible: false
            })
          }, 1500)
        }
      });
    }
    //选择建卡类型 格式验证
    validFunction = (rule, value, callback) => {
      //身份证 18位  就诊卡 银医卡 条形码 根据配置合理提示 不根据固定的卡类型做判断 根据配置项是否可补0以及卡号长度进行检测 区分身份证 code == 12
      const { idCardCode, replenishZero, cardLength } = this.state
      //控制选择建卡和卡操作选择绑卡id 正确提示 及 校验
      // console.log("cardLengthCard", cardLengthCard)
      let diffLength = cardLength
      let diffCode = idCardCode
      if (diffCode == '02') {
        var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 " };
        if (!value || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(value)) {

          callback('身份证号格式错误'); // 校验未通过
          return;
        }
        else if (!city[value.substr(0, 2)]) {

          callback('身份证号格式错误'); // 校验未通过
          return;
        }
        else {
          //18位身份证需要验证最后一位校验位
          if (value.length == 18) {
            value = value.split('');
            //∑(ai×Wi)(mod 11)
            //加权因子
            var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
            //校验位
            var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
            var sum = 0;
            var ai = 0;
            var wi = 0;
            for (var i = 0; i < 17; i++) {
              ai = value[i];
              wi = factor[i];
              sum += ai * wi;
            }
            var last = parity[sum % 11];
            //最后一位不区分大小写
            if (value[17] == 'x') value[17] = value[17].toUpperCase();
            if (parity[sum % 11] != value[17]) {

              callback('身份证号格式错误'); // 校验未通过
              return;
            } else {
            }
          }
        }
        callback();
      }
      if (replenishZero == "N" && parseInt(diffLength) > 0 && diffCode != '02') {
        let length = parseInt(diffLength)
        var reg = new RegExp('^\\d{' + length + '}$')
        if (!reg.test(value)) {
          callback('该卡号长度不正确，请输入有效卡号'); // 校验未通过
          return;
        } else {
        }
      }
      // if (replenishZero == "Y" && parseInt(diffLength) > 0) {
      //     let length = parseInt(diffLength)
      //     var reg = new RegExp("^\\d{" + length + "}$");
      //     if (!reg.test(value)) {
      //         callback('该卡号无效，请输入有效卡号,数字可自动补0'); // 校验未通过
      //         return;
      //     } else {
      //     }
      // }
      if (replenishZero == "N" && !parseInt(diffLength) > 0) {
        if (!/^[0-9]*$/.test(value)) {
          callback('请输入任意数字'); // 校验未通过
          return;
        } else {
        }
      }
      callback();
    }
    //点击读卡
    handleCardReading = () => {
      this.setState({
        parms: {}
      })
      const { initCardDr } = this.state
      this.readCard.ReadCard(initCardDr, "R", (json) => {
        // console.log(json)
        //读卡完成 信息回显
        this.props.form.setFieldsValue({ cardNo: json.cardNo, cardTypeID: json.cardTypeID })
        this.setState({
          initCardDr: json.cardTypeID,
          cardNoVisible: false
        }, () => {
          this.props.getValue(this.props.form.getFieldValue('cardTypeID'), this.props.form.getFieldValue('cardNo'))
        })
      })
    }
    //输入时
    handlePatCardNo = (e) => {
      // console.log(e.target.value)
      if (e.target) {
        this.setState({
          patCardNo: e.target.value
        }, () => {
          this.props.getValue(this.props.form.getFieldValue('cardTypeID'), this.state.patCardNo)
        })
      } if (e.target.value.length == "0") {
        this.props.getValue(this.props.form.getFieldValue('cardTypeID'), "")
      }
    }

    render () {
      const { getFieldDecorator } = this.props.form;
      const { baseParms, nowRead, replenishZero, cardLength, autoCreateCardNo, initCardDr, cardNo } = this.state;
      const mesIcon = <Icon type="exclamation-circle" />
      let card = []
      baseParms && baseParms.cardType.map(item => {
        card.push(<Option key={item.id}
          onClick={() => this.handleSelectCard(item.id)}
          value={item.id}
          role={item.descripts + '^' + item.descriptsSPCode}
          title={item.descripts}>
          {item.descripts}
        </Option>)
      })
      return (
        <div className="cardTypeReadDom">
          <div>
            <Col span={this.props.n && this.props.n ? this.props.n : (this.props.type == 'update' ? 7 : 2)} style={{ padding: "0" }}>
              <FormItem>
                {getFieldDecorator('cardTypeID', {
                  initialValue: this.props.sendInfo && this.props.sendInfo ? this.props.sendInfo.credTypeID : initCardDr,
                  rules: [{ required: false, message: '请选择卡类型' }],
                })(
                  <Select onChange={this.handleSelectCard} allowClear
                    optionFilterProp="role"
                    showSearch placeholder='请选择卡类型'>
                    {card}
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={this.props.m && this.props.m ? this.props.m : (this.props.type == 'update' ? 12 : 4)} className="cardNoDom"
              style={{ padding: "0 0 0 4px", marginLeft: this.props.type == 'update' ? 10 : '' }}>
              <Tooltip getPopupContainer={() => document.querySelector('.cardNoDom')} overlayStyle={{ zIndex: 999, }} overlayClassName="toolTipDom cardNo" title={<div className="titleIcon">{mesIcon}<span >{this.state.cardNoMessage}</span></div>} visible={this.state.cardNoVisible}>
                <FormItem >
                  {getFieldDecorator('cardNo', {
                    validateTrigger: [""],
                    initialValue: this.props.sendInfo && this.props.sendInfo ? this.props.sendInfo.credNo : undefined,
                    rules: [{ required: false, message: '' },
                    { validator: autoCreateCardNo != "Y" ? this.validFunction : "" },],
                    getValueFromEvent: (event) => {
                      return this.state.idCardCode == '02' ? event.target.value.replace(/[^\d|Xx]/g, '') : event.target.value.replace(/\D/g, '')
                    },
                  })(
                    <Input
                      value={this.state.patCardNo}
                      onChange={(e) => this.handlePatCardNo(e)}
                      style={{ borderRight: "0", borderRadius: "4px 0px 0px 4px" }}
                      onPressEnter={() => this.handleLength("1")}
                      onBlur={() => this.handleLength()}
                      maxLength={cardLength && cardLength != "" ? parseInt(cardLength) : 99}
                      disabled={nowRead == 'R' && autoCreateCardNo != "Y"}
                      placeholder={
                        nowRead == 'R' && autoCreateCardNo != "Y" ? '请点击读卡' :
                          (nowRead == "" && replenishZero == "Y" && autoCreateCardNo != "Y" ? cardLength + '刷卡/输入或点击读卡（卡号可自动补零）'
                            : (nowRead == "" && replenishZero == "N" && autoCreateCardNo != "Y" ? cardLength + '刷卡/输入或点击读卡'
                              : (nowRead == 'I' && replenishZero == "Y" && autoCreateCardNo != "Y" ? cardLength + '输入卡号（卡号可自动补零）'
                                : (nowRead == 'I' && replenishZero == "N" && autoCreateCardNo != "Y" ? cardLength + '输入卡号'
                                  : (autoCreateCardNo == "Y" ? "输入卡号" : ""
                                  )))))
                      }
                    />
                  )}
                </FormItem>
              </Tooltip>
            </Col>
            <Col span={1} style={{ padding: "0", }}>
              <Form.Item>
                <Button style={{ borderRadius: "0px 4px 4px 0px" }} disabled={nowRead == "I" || autoCreateCardNo == "Y"} type={nowRead == 'I' || autoCreateCardNo == "Y" ? "" : "primary"} onClick={this.handleCardReading}>
                  读卡
                </Button>
              </Form.Item>
            </Col>
          </div>
          <ReadCard ref={r => this.readCard = r} />
        </div>
      );
    }
  })
export default CardTypeRead
