/*
 * Author: 黎永顺
 * name: 二次验证密码设置
 * Description:
 * Date: 2023/7/7
 */
import React, { Component } from "react";
import { WeaDialog, WeaFormItem, WeaLocaleProvider, WeaSearchGroup } from "ecCom";
import { WeaSwitch } from "comsMobx";
import { condition, loginCondition } from "./pwdCondtion";
import { Button, message } from "antd";
import { RSAEcrypt } from "../../util/RSAUtil";
import { checkPassword, getPasswordForm, saveSecondaryPwd } from "../../apis/mySalaryBenefits";
import "./index.less";

const getLabel = WeaLocaleProvider.getLabel;

class PassSetDialog extends Component {
  constructor(props) {
    super(props);
    this.state = {
      src: (window.ecologyContentPath || "") + "/weaver/weaver.file.MakeValidateCode?notneedvalidate=1&isView=1&validatetype=0&validatenum=4",
      num: 0,
      isPassLoginPassword: false
    };
  }

  componentDidMount() {
    this.props.form.initFormFields(loginCondition);
    this.props.form.initFormFields(condition);
  }

  getSearchs = (form, condition) => {
    const { isFormInit } = form, formParams = form.getFormParams();
    let group = [];
    isFormInit && condition && condition.map(c => {
      let items = [];
      c.items.map(fields => {
        items.push({
          com: (
            <WeaFormItem
              label={`${fields.label}`} labelCol={{ span: `${fields.labelcol}` }}
              wrapperCol={{ span: `${fields.fieldcol}` }} error={form.getError(fields)}
              tipPosition="bottom"
            >
              {
                fields.domkey[0] === "validatecode" ?
                  <div className="validatecodeWrapper">
                    <WeaSwitch fieldConfig={fields} form={form} formParams={formParams}/>
                    <img
                      style={{ height: 30, cursor: "pointer" }}
                      src={this.state.src}
                      onClick={() => {
                        this.setState({ num: this.state.num + 1 }, () => {
                          this.setState({ src: `${window.ecologyContentPath || ""}/weaver/weaver.file.MakeValidateCode?notneedvalidate=1&isView=1&validatetype=0&validatenum=4&seriesnum_=${this.state.num}` });
                        });
                      }}
                      alt=""
                    />
                  </div>
                  : <WeaSwitch fieldConfig={fields} form={form} formParams={formParams}/>
              }
            </WeaFormItem>),
          colSpan: 1
        });
      });
      group.push(
        <WeaSearchGroup
          col={1} needTigger={false} title={c.title}
          showGroup={c.defaultshow} items={items}
        />);
    });
    return group;
  };
  saveSecondaryPassword = async () => {
    const { openRSA } = await getPasswordForm();
    const { isPassLoginPassword } = this.state;
    const { form } = this.props;
    const { secondaryPwd1, secondaryPwd2, validatecode, password } = form.getFormParams();
    if (isPassLoginPassword) {
      if (!validatecode || !secondaryPwd1 || !secondaryPwd2) {
        message.error(getLabel(518702, "必要信息不完整，红色*为必填项！"));
        return;
      }
      if (secondaryPwd1 !== secondaryPwd2) {
        message.error(getLabel(504376, "密码确认不正确！"));
        return;
      }
    } else {
      if (!password) {
        message.error(getLabel(518702, "必要信息不完整，红色*为必填项！"));
        return;
      }
    }
    const params = isPassLoginPassword ? { secondaryPwd1, secondaryPwd2 } : { password };
    RSAEcrypt(openRSA, params).then(RSAParam => {
      isPassLoginPassword ?
        saveSecondaryPwd({ ...RSAParam, validatecode }).then(({ sign, message: msg }) => {
          if (sign === "1") {
            message.success(msg);
            this.props.onCancel();
            form.resetForm();
          } else {
            message.warning(msg);
            this.setState({ num: this.state.num + 1 }, () => {
              this.setState({ src: `${window.ecologyContentPath || ""}/weaver/weaver.file.MakeValidateCode?notneedvalidate=1&isView=1&validatetype=0&validatenum=4&seriesnum_=${this.state.num}` });
            });
          }
        }) :
        checkPassword({ ...RSAParam }).then(({ result }) => {
          if (result) {
            this.setState({ isPassLoginPassword: true });
            form.resetForm();
          } else {
            message.error(getLabel(504343, "登录密码错误"));
          }
        });
    });
  };

  render() {
    const { isPassLoginPassword } = this.state;
    return (
      <WeaDialog
        onCancel={this.props.onCancel}
        title={isPassLoginPassword ? getLabel(504332, "二次验证密码设置") : getLabel(504331, "请先输入登录密码")}
        visible={this.props.visible}
        initLoadCss className="pwdSetWrapper" hasScroll buttons={[
        <Button type="primary" size="small" onClick={this.saveSecondaryPassword}>{getLabel(537558, "保存")}</Button>
      ]}
      >
        {
          isPassLoginPassword ?
            this.getSearchs(this.props.form, condition) :
            this.getSearchs(this.props.form, loginCondition)
        }
      </WeaDialog>
    );
  }
}

export default PassSetDialog;
