import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _inherits from "@babel/runtime/helpers/inherits";
import _createSuper from "@babel/runtime/helpers/createSuper";
import { __decorate } from "tslib";
import React, { Component } from 'react';
import ConfigContext from '../../../es/config-provider/ConfigContext';
import { observer } from 'mobx-react';
import { action, observable, runInAction } from 'mobx';
import autobind from '../_util/autobind';
import { $l } from '../locale-context';
import DataSet from '../data-set/DataSet';
import message from '../message';
import { FieldType } from '../data-set/enum';
import Form from '../form/Form';
import ObserverSelectBox from '../select-box/SelectBox';
import Option from '../option/Option';
import ObserverTextField from '../text-field/TextField';
import Button from '../button/Button';
import VerifySlider from './VerifySlider';
import CountDownButton from './CountDownButton';
import { ButtonColor } from '../button/enum';
import { ValueChangeAction } from '../text-field/enum';

var SecretFieldView = /*#__PURE__*/function (_Component) {
  _inherits(SecretFieldView, _Component);

  var _super = _createSuper(SecretFieldView);

  function SecretFieldView(props, context) {
    var _this;

    _classCallCheck(this, SecretFieldView);

    _this = _super.call(this, props, context);
    runInAction(function () {
      _this.setFlag('verify');

      _this.setVerifyTypeObj();

      _this.setFormDs();

      _this.setCaptchaKey('');

      _this.setCaptcha('');

      _this.setValidate(true);
    });
    return _this;
  }

  _createClass(SecretFieldView, [{
    key: "prefixCls",
    get: function get() {
      var context = this.context;
      return context.getProPrefixCls('secret-field');
    } // 滑块拖到最右

  }, {
    key: "handleSuccess",
    value: function handleSuccess() {
      var _this2 = this;

      var context = this.context,
          formDs = this.formDs; // 发送信息以获取验证码

      var secretFieldFetchVerifyCode = context.getConfig('secretFieldFetchVerifyCode');

      if (secretFieldFetchVerifyCode) {
        var countDown = this.props.countDown;
        var type = formDs && formDs.current && formDs.current.get('verifyType');
        secretFieldFetchVerifyCode(type).then(function (res) {
          if (res.success) {
            message.success(res.message);

            _this2.setCaptchaKey(res.captchaKey); // 验证码倒计时


            countDown.start();
            countDown.setVerifyType(type);
          } else {
            message.error(res.message);
          }

          setTimeout(function () {
            _this2.setFlag('verify');
          }, 500);
        })["catch"](function (_e) {
          return _this2.setFlag('verify');
        });
      }
    } // 下一步

  }, {
    key: "handleGoToEdit",
    value: function handleGoToEdit() {
      var _this3 = this;

      var context = this.context; // 编辑-校验验证码，返回原始值

      var secretFieldQueryData = context.getConfig('secretFieldQueryData');

      if (secretFieldQueryData) {
        var _this$props = this.props,
            name = _this$props.name,
            _this$props$token = _this$props.token,
            token = _this$props$token === void 0 ? '' : _this$props$token;
        var captchaKey = this.captchaKey,
            captcha = this.captcha,
            formDs = this.formDs;
        var current = formDs && formDs.current;
        var type = current && current.get('verifyType');
        var params = {
          type: type,
          _token: token,
          fieldName: name,
          captchaKey: captchaKey,
          captcha: captcha,
          action: 'edit'
        };
        secretFieldQueryData(params).then(function (res) {
          if (res && res.failed) {
            // 校验失败
            return;
          }

          if (current) {
            // 编辑-返回原始数据
            current.set(name, res);
          }

          _this3.setFlag('edit');
        });
      } else {
        this.setFlag('edit');
      }
    } // 确定可查看

  }, {
    key: "handleQuery",
    value: function handleQuery() {
      var _this$props2 = this.props,
          name = _this$props2.name,
          _this$props2$token = _this$props2.token,
          token = _this$props2$token === void 0 ? '' : _this$props2$token,
          onChange = _this$props2.onChange,
          modal = _this$props2.modal,
          record = _this$props2.record; // 查看-校验验证码，返回原始值

      var captchaKey = this.captchaKey,
          captcha = this.captcha,
          context = this.context,
          formDs = this.formDs;
      var secretFieldQueryData = context.getConfig('secretFieldQueryData');
      var type = formDs && formDs.current && formDs.current.get('verifyType');
      var params = {
        type: type,
        _token: token,
        fieldName: name,
        captchaKey: captchaKey,
        captcha: captcha,
        action: 'query'
      };

      if (secretFieldQueryData) {
        return secretFieldQueryData(params).then(function (res) {
          if (res && res.failed) {
            // 校验失败
            return;
          } // 查看-返回原始数据


          if (onChange) {
            if (res) {
              onChange(res);
            } else {
              onChange('');
            }
          }

          if (modal) {
            modal.close();

            if (record) {
              record.setState("_secretField_queryFlag_".concat(name), true);
            }
          }
        });
      }
    } // 正则string处理

  }, {
    key: "generatePattern",
    value: function generatePattern(pattern) {
      if (pattern instanceof RegExp) {
        return pattern;
      }

      var begin = pattern.startsWith('^') ? '' : '^';
      var end = pattern.endsWith('$') ? '' : '$';
      return new RegExp("".concat(begin).concat(pattern).concat(end));
    } // 确定修改

  }, {
    key: "handleEdit",
    value: function handleEdit() {
      var _this$props3 = this.props,
          name = _this$props3.name,
          _this$props3$token = _this$props3.token,
          token = _this$props3$token === void 0 ? '' : _this$props3$token,
          onChange = _this$props3.onChange,
          modal = _this$props3.modal,
          pattern = _this$props3.pattern,
          required = _this$props3.required;
      var context = this.context,
          formDs = this.formDs;
      var editValue = formDs && formDs.current && formDs.current.get(name);

      if (pattern) {
        var newPattern = this.generatePattern(pattern);

        if (newPattern.test(editValue) === false) {
          // 正则校验不通过
          this.setValidate(false);
          return;
        }
      }

      if (required && !editValue) {
        return;
      } // 接口查询重置值


      var secretFieldSaveData = context.getConfig('secretFieldSaveData');
      var params = {
        _token: token,
        fieldName: name,
        value: editValue
      };

      if (secretFieldSaveData) {
        return secretFieldSaveData(params).then(function (res) {
          // 校验失败
          if (res && res.failed) {
            return;
          } // 编辑-返回修改数据


          if (onChange) {
            if (res) {
              onChange(res);
            } else if (!res) {
              onChange('');
            }
          }

          if (modal) {
            modal.close();
          }
        });
      }
    } // 取消

  }, {
    key: "handleCancel",
    value: function handleCancel() {
      // 清空formDs值
      // 关闭弹窗
      var modal = this.props.modal;

      if (modal) {
        modal.close();
      }
    }
  }, {
    key: "setFormDs",
    value: function setFormDs() {
      var _this$props4 = this.props,
          name = _this$props4.name,
          label = _this$props4.label,
          pattern = _this$props4.pattern,
          required = _this$props4.required,
          countDown = _this$props4.countDown;
      var verifyTypeObj = this.verifyTypeObj;
      var getConfig = this.context.getConfig;
      var verifyType = countDown.verifyType;
      var initData = [];
      var verifyValue = ''; // 传入验证方式时，设置初始值

      if (verifyType) {
        verifyTypeObj.forEach(function (item) {
          if (item.type === verifyType) {
            verifyValue = item.value;
          }
        });
      }

      if (verifyTypeObj.length > 0) {
        initData = [{
          'verifyType': verifyType || verifyTypeObj[0].type,
          'verifyNumber': verifyType ? verifyValue : verifyTypeObj[0].value || ''
        }];
      }

      this.formDs = new DataSet({
        autoCreate: true,
        data: initData,
        fields: [{
          name: 'verifyType',
          type: FieldType.string,
          label: $l('SecretField', 'verify_type')
        }, {
          name: 'verifyNumber',
          type: FieldType.string,
          label: $l('SecretField', 'verify_value')
        }, {
          name: 'verifyCode',
          type: FieldType.string,
          label: $l('SecretField', 'verify_code')
        }, {
          name: name,
          type: FieldType.string,
          label: label,
          pattern: pattern,
          required: required
        }],
        events: {
          update: this.handleFormUpdate
        }
      }, {
        getConfig: getConfig
      });
    }
  }, {
    key: "setCaptchaKey",
    value: function setCaptchaKey(value) {
      this.captchaKey = value;
    }
  }, {
    key: "setCaptcha",
    value: function setCaptcha(value) {
      this.captcha = value;
    }
  }, {
    key: "setValidate",
    value: function setValidate(value) {
      this.validate = value;
    }
  }, {
    key: "setFlag",
    value: function setFlag(value) {
      this.flag = value;
    }
  }, {
    key: "setVerifyTypeObj",
    value: function setVerifyTypeObj() {
      var context = this.context; // 从配置项获取验证方式

      var secretFieldTypesConfig = context.getConfig('secretFieldTypes');

      if (secretFieldTypesConfig) {
        this.verifyTypeObj = secretFieldTypesConfig();
      } else {
        this.verifyTypeObj = [];
      }
    }
  }, {
    key: "handleFormUpdate",
    value: function handleFormUpdate(_ref) {
      var name = _ref.name,
          value = _ref.value;
      var verifyTypeObj = this.verifyTypeObj; // 修改验证方式时，自动填充验证号码

      if (verifyTypeObj.length > 0 && name === 'verifyType') {
        var current = this.formDs && this.formDs.current;

        if (current) {
          verifyTypeObj.forEach(function (item) {
            if (item.type === value) {
              current.set('verifyNumber', item.value);
            }
          });
        }
      }

      if (name === 'verifyCode') {
        this.setCaptcha(value);
      }
    }
  }, {
    key: "handleVerifySliderCancel",
    value: function handleVerifySliderCancel() {
      this.setFlag('verify');
    }
  }, {
    key: "handleClickButton",
    value: function handleClickButton() {
      this.setFlag('slider');
    }
  }, {
    key: "render",
    value: function render() {
      var flag = this.flag,
          captcha = this.captcha,
          verifyTypeObj = this.verifyTypeObj,
          prefixCls = this.prefixCls,
          validate = this.validate,
          formDs = this.formDs;
      var _this$props5 = this.props,
          readOnly = _this$props5.readOnly,
          label = _this$props5.label,
          name = _this$props5.name,
          countDown = _this$props5.countDown,
          restrict = _this$props5.restrict;
      var count = countDown.count;
      return /*#__PURE__*/React.createElement("div", {
        className: "".concat(prefixCls, "-modal")
      }, flag !== 'slider' && /*#__PURE__*/React.createElement(Form, {
        className: "".concat(prefixCls, "-modal-form"),
        dataSet: this.formDs,
        columns: 4,
        labelWidth: "auto"
      }, flag === 'verify' && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(ObserverSelectBox, {
        name: "verifyType",
        colSpan: 4,
        disabled: count
      }, verifyTypeObj && verifyTypeObj.map(function (item) {
        return /*#__PURE__*/React.createElement(Option, {
          value: item.type,
          key: item.type
        }, item.name);
      })), /*#__PURE__*/React.createElement(ObserverTextField, {
        name: "verifyNumber",
        colSpan: 4,
        disabled: true
      }), /*#__PURE__*/React.createElement(ObserverTextField, {
        name: "verifyCode",
        colSpan: 3,
        valueChangeAction: ValueChangeAction.input
      }), /*#__PURE__*/React.createElement(CountDownButton, {
        onClick: this.handleClickButton,
        countDown: countDown,
        verifyNumber: formDs.current.get('verifyNumber')
      }), /*#__PURE__*/React.createElement("td", {
        className: "".concat(prefixCls, "-modal-btns"),
        colSpan: 4
      }, /*#__PURE__*/React.createElement(Button, {
        onClick: this.handleCancel
      }, $l('SecretField', 'cancel')), readOnly ? /*#__PURE__*/React.createElement(Button, {
        onClick: this.handleQuery,
        className: "".concat(prefixCls, "-modal-raised-btn"),
        disabled: !captcha,
        color: ButtonColor.primary
      }, $l('SecretField', 'ok_btn')) : /*#__PURE__*/React.createElement(Button, {
        onClick: this.handleGoToEdit,
        className: "".concat(prefixCls, "-modal-raised-btn"),
        disabled: !captcha,
        color: ButtonColor.primary
      }, $l('SecretField', 'next_step')))), flag === 'edit' && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(ObserverTextField, {
        name: name,
        colSpan: 4,
        restrict: restrict
      }), /*#__PURE__*/React.createElement("td", {
        colSpan: 4,
        className: "".concat(prefixCls, "-modal-edit-btns")
      }, !validate && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("p", {
        className: "".concat(prefixCls, "-modal-validate")
      }, $l('SecretField', 'type_mismatch', {
        label: label
      })), /*#__PURE__*/React.createElement("br", null)), /*#__PURE__*/React.createElement(Button, {
        onClick: this.handleCancel
      }, $l('SecretField', 'cancel')), /*#__PURE__*/React.createElement(Button, {
        onClick: this.handleEdit,
        color: ButtonColor.primary
      }, $l('SecretField', 'ok_btn'))))), flag === 'slider' && /*#__PURE__*/React.createElement(VerifySlider, {
        onCancel: this.handleVerifySliderCancel,
        onSuccess: this.handleSuccess
      }));
    }
  }], [{
    key: "contextType",
    get: function get() {
      return ConfigContext;
    }
  }]);

  return SecretFieldView;
}(Component);

SecretFieldView.displayName = 'SecretFieldView';

__decorate([autobind], SecretFieldView.prototype, "handleSuccess", null);

__decorate([autobind], SecretFieldView.prototype, "handleGoToEdit", null);

__decorate([autobind], SecretFieldView.prototype, "handleQuery", null);

__decorate([autobind], SecretFieldView.prototype, "handleEdit", null);

__decorate([autobind], SecretFieldView.prototype, "handleCancel", null);

__decorate([observable], SecretFieldView.prototype, "formDs", void 0);

__decorate([action], SecretFieldView.prototype, "setFormDs", null);

__decorate([observable], SecretFieldView.prototype, "captchaKey", void 0);

__decorate([action], SecretFieldView.prototype, "setCaptchaKey", null);

__decorate([observable], SecretFieldView.prototype, "captcha", void 0);

__decorate([action], SecretFieldView.prototype, "setCaptcha", null);

__decorate([observable], SecretFieldView.prototype, "validate", void 0);

__decorate([action], SecretFieldView.prototype, "setValidate", null);

__decorate([observable], SecretFieldView.prototype, "flag", void 0);

__decorate([action], SecretFieldView.prototype, "setFlag", null);

__decorate([observable], SecretFieldView.prototype, "verifyTypeObj", void 0);

__decorate([action], SecretFieldView.prototype, "setVerifyTypeObj", null);

__decorate([autobind], SecretFieldView.prototype, "handleFormUpdate", null);

__decorate([autobind], SecretFieldView.prototype, "handleVerifySliderCancel", null);

__decorate([autobind], SecretFieldView.prototype, "handleClickButton", null);

SecretFieldView = __decorate([observer], SecretFieldView);
export default SecretFieldView;
//# sourceMappingURL=SecretFieldView.js.map
