/*
 * Author: 黎永顺
 * name: 规则配置
 * Description:
 * Date: 2024/2/23
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaLocaleProvider, WeaTools, WeaTop } from "ecCom";
import { message, Modal } from "antd";
import * as API from "../../apis/ruleconfig";
import { conditions, payloadList, salaryApprovalConditions } from "./conditions";
import ProgressModal from "../../components/progressModal";
import { renderRuleForm } from "./form";
import { getConditionDomkeys } from "../../util";
import "./index.less";

const getKey = WeaTools.getKey;
const getLabel = WeaLocaleProvider.getLabel;

@inject("baseFormStore")
@observer
class RuleConfig extends Component {
  constructor(props) {
    super(props);
    this.state = { conditions: [], sysinfo: {}, progressVisible: false, progress: 50 };
    this.timer = null;
    this.handleDebounce = null;
  }

  componentDidMount() {
    const promise = this.init();
  }

  init = async () => {
    const [{ data: sysinfo }, { data: confCode }] = await Promise.all([API.sysinfo(), API.sysConfCodeRule({ code: "SHOW_SALARY_ACCT_APPROVAL" })]);
    const [{ data: matchRule }, { data: orderRule }, { data: ascOrDesc }, { data: rule }] =
      await Promise.all(_.map(payloadList, it => API.commonEnumList(it)));
    const optionsList = { matchRule, orderRule, ascOrDesc, rule };
    const conditonsSlice = confCode === "1" ? [...conditions, ...salaryApprovalConditions] : conditions;
    this.setState({
      sysinfo, conditions: _.map(conditonsSlice, item => ({
        ...item, title: getLabel(item.lanId, item.title),
        items: _.map(item.items, o => {
          o = { ...o, label: getLabel(o.lanId, o.label) };
          if (getKey(o) === "matchRule" || getKey(o) === "orderRule" || getKey(o) === "ascOrDesc" || getKey(o) === "rule") {
            return { ...o, options: _.map(optionsList[getKey(o)], g => ({ key: g.value, showname: g.defaultLabel })) };
          } else if (getKey(o) === "REPORT_ORGANIZATIN_TYPE") {
            return {
              ...o, options: [
                { key: "0", showname: getLabel(111, "核算时组织信息"), selected: true },
                { key: "1", showname: getLabel(111, "实时组织信息"), selected: false }
              ]
            };
          } else if (getKey(o) === "SALARY_DETAILS_REPORT_SHOW_TYPE") {
            return {
              ...o, options: [
                { key: "0", showname: getLabel(111, "定制列"), selected: true },
                { key: "1", showname: getLabel(111, "模板"), selected: false }
              ]
            };
          } else if (getKey(o) === "OPEN_APPLICATION_ENCRYPT") {
            return { ...o, viewAttr: sysinfo.showEncryptOperationButton === "true" ? 2 : 1 };
          } else if (getKey(o) === "taxDeclarationFunction") {
            return {
              ...o,
              viewAttr: (_.isNil(sysinfo.taxDeclarationFunction) || sysinfo.taxDeclarationFunction !== "0") ? 2 : 1
            };
          } else if (
            getKey(o) === "APPROVAL_CAN_MANUAL_FILE_STATUS" || getKey(o) === "APPROVAL_CAN_RE_CALC_STATUS" || getKey(o) === "APPROVAL_CAN_EDIT_RESULT_STATUS"
          ) {
            return {
              ...o,
              hide: sysinfo["SALARY_APPROVAL_STATUS"] === "0" || _.isNil(sysinfo["SALARY_APPROVAL_STATUS"])
            };
          } else if (getKey(o) === "TAX_DECLARATION_DATE_TYPE") {
            return {
              ...o, options: [
                { key: "0", showname: getLabel(111, "薪资所属月"), selected: true },
                { key: "1", showname: getLabel(111, "税款所属期"), selected: false }
              ]
            };
          }
          return { ...o };
        })
      }))
    }, async () => {
      const { baseFormStore: { form } } = this.props;
      form.initFormFields(this.state.conditions);
      await this.updateFormData();
    });
  };
  updateFormData = async () => {
    const { data: sysinfo } = await API.sysinfo();
    const { baseFormStore: { form } } = this.props;
    _.map(getConditionDomkeys(this.state.conditions), item => {
      if (item === "rule") {
        form.updateFields({ [item]: { value: sysinfo["matchEmployeeMode"] || "" } });
      } else if (item === "matchRule") {
        form.updateFields({ [item]: { value: sysinfo["salaryAcctEmployeeRule"] || "" } });
      } else if (item === "taxDeclarationFunction") {
        form.updateFields({ [item]: { value: sysinfo[item] === "0" ? "0" : (sysinfo[item] || "1") } });
      } else if (item === "REPORT_ORGANIZATIN_TYPE" || item === "SALARY_DETAILS_REPORT_SHOW_TYPE") {
        form.updateFields({ [item]: { value: sysinfo[item] === "0" ? "0" : (sysinfo[item] || "0") } });
      } else if (item === "taxAgentShowStatus" || item === "salaryShowStatus" || item === "adjustShowStatus") {
        form.updateFields({ [item]: { value: sysinfo[item] || "1" } });
      } else if (item === "OPEN_APPLICATION_ENCRYPT" || item === "SALARY_ACCT_SYNC_TYPE") {
        form.updateFields({ [item]: { value: _.isNil(sysinfo[item]) ? "1" : (sysinfo[item] || "") } });
      } else if (
        item === "APPROVAL_CAN_MANUAL_FILE_STATUS" || item === "APPROVAL_CAN_RE_CALC_STATUS" || item === "APPROVAL_CAN_EDIT_RESULT_STATUS"
      ) {
        form.updateFields({ [item]: { value: _.isNil(sysinfo[item]) ? "1" : (sysinfo[item] || "0") } });
      } else {
        form.updateFields({ [item]: { value: sysinfo[item] || "" } });
      }
    });
  };
  handleChange = (params) => {
    const key = _.keys(params)[0];
    const val = params[key].value;
    Modal.confirm({
      title: getLabel(131329, "信息确认"),
      content: (key === "taxDeclarationFunction" && val === "0") ? getLabel(544276, "关闭之后，将无法开启,确认要保存吗?") : getLabel(543854, "确认要保存吗?"),
      onOk: () => {
        switch (key) {
          case "orderRule":
          case "ascOrDesc":
            this.updateOrderRule();
            break;
          case "rule":
            this.saveMatchEmployeeModeRule();
            break;
          case "OPEN_APPLICATION_ENCRYPT":
            this.saveEncryptSetting();
            break;
          case "taxDeclarationFunction":
            this.operateTaxDeclarationFunction();
            break;
          case "matchRule":
            this.saveSalaryAcctEmployeeRule();
            break;
          case "WITHDRAW_TAX_DECLARATION":
          case "salaryArchiveDelete":
            const url = {
              WITHDRAW_TAX_DECLARATION: "saveWithDrawTaxDeclaration", salaryArchiveDelete: "saveArchiveDelete"
            };
            this.ruleSettings(key, url[key]);
            break;
          case "welBaseDiffByPerAndCom":
          case "welBaseAutoAdjust":
          case "salaryAcctFixedColumns":
          case "extEmpsWitch":
          case "taxAgentShowStatus":
          case "salaryShowStatus":
          case "adjustShowStatus":
          case "REPORT_ORGANIZATIN_TYPE":
          case "SALARY_DETAILS_REPORT_SHOW_TYPE":
          case "openSecondaryAccount":
          case "SALARY_APPROVAL_STATUS":
          case "APPROVAL_CAN_MANUAL_FILE_STATUS":
          case "APPROVAL_CAN_RE_CALC_STATUS":
          case "APPROVAL_CAN_EDIT_RESULT_STATUS":
          case "ATTENDANCE_SERIAL_COLLECTION_BTN":
          case "TAX_DECLARATION_DATE_TYPE":
          case "SHOT_EMP_BTN":
          case "SALARY_ACCT_SYNC_TYPE":
            if (!this.handleDebounce) {
              this.handleDebounce = _.debounce(() => {
                const confTitle = {
                  welBaseDiffByPerAndCom: getLabel(111, "福利档案基数区分个人和公司"),
                  welBaseAutoAdjust: getLabel(111, "福利档案导入基数不符合要求时自动调整为上限/下限"),
                  salaryAcctFixedColumns: getLabel(545791, "薪资核算固定列头数"),
                  extEmpsWitch: getLabel(544097, "开启非系统人员"),
                  taxAgentShowStatus: getLabel(111, "显示【个税扣缴义务人】信息"),
                  salaryShowStatus: getLabel(111, "显示工资单页签"),
                  adjustShowStatus: getLabel(111, "显示调薪记录页签"),
                  REPORT_ORGANIZATIN_TYPE: getLabel(111, "组织信息"),
                  SALARY_DETAILS_REPORT_SHOW_TYPE: getLabel(111, "薪资明细显示模式"),
                  openSecondaryAccount: getLabel(111, "启用主次身份"),
                  SALARY_APPROVAL_STATUS: getLabel(111, "是否开启薪资审批"),
                  APPROVAL_CAN_MANUAL_FILE_STATUS: getLabel(111, "开启审批的核算记录允许手动归档"),
                  APPROVAL_CAN_RE_CALC_STATUS: getLabel(111, "开启审批的核算记录允许重新核算"),
                  APPROVAL_CAN_EDIT_RESULT_STATUS: getLabel(111, "审批流程发起后允许修改核算数据"),
                  ATTENDANCE_SERIAL_COLLECTION_BTN: getLabel(111, "考勤引用是否采集班次数据"),
                  TAX_DECLARATION_DATE_TYPE: getLabel(111, "申报日期类型"),
                  SHOT_EMP_BTN: getLabel(111, "启用组织快照"),
                  SALARY_ACCT_SYNC_TYPE: getLabel(111, "是否采用线程池")
                };
                this.unifiedSettings(key, confTitle[key]);
                this.handleDebounce = null;
              }, 500);
            }
            this.handleDebounce();
            break;
          default:
            break;
        }
      },
      onCancel: () => this.updateFormData()
    });
  };
  /*
   * Author: 黎永顺
   * Description:排序规则-保存
   * Params:
   * Date: 2024/2/26
   */
  updateOrderRule = () => {
    const { baseFormStore: { form } } = this.props;
    const { orderRule, ascOrDesc } = form.getFormParams();
    API.updateOrderRule({ orderRule, ascOrDesc }).then(({ status, errormsg }) => {
      if (status) {
        message.success(getLabel(22619, "保存成功!"));
      } else {
        message.error(errormsg || getLabel(22620, "保存失败!"));
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description: 人员校验规则-人员字段保存
   * Params:
   * Date: 2024/2/26
   */
  saveMatchEmployeeModeRule = () => {
    const { baseFormStore: { form } } = this.props;
    const { rule } = form.getFormParams();
    API.saveMatchEmployeeModeRule({ rule }).then(({ status, errormsg }) => {
      if (status) {
        message.success(getLabel(22619, "保存成功!"));
      } else {
        message.error(errormsg || getLabel(22620, "保存失败!"));
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description: 薪资核算人员匹配规则-匹配规则
   * Params:
   * Date: 2024/2/26
   */
  saveSalaryAcctEmployeeRule = () => {
    const { baseFormStore: { form } } = this.props;
    const { matchRule: rule } = form.getFormParams();
    API.saveSalaryAcctEmployeeRule({ rule }).then(({ status, errormsg }) => {
      if (status) {
        message.success(getLabel(22619, "保存成功!"));
      } else {
        message.error(errormsg || getLabel(22620, "保存失败!"));
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description: 算税规则-系统算税设置
   * Params:
   * Date: 2024/2/26
   */
  operateTaxDeclarationFunction = () => {
    const { baseFormStore: { form } } = this.props;
    const { taxDeclarationFunction: operateTaxDeclaration } = form.getFormParams();
    API.operateTaxDeclarationFunction({ operateTaxDeclaration }).then(({ status, errormsg }) => {
      if (status) {
        message.success(getLabel(22619, "保存成功!"));
        const promise = this.init();
      } else {
        message.error(errormsg || getLabel(22620, "保存失败!"));
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description: 加密设置
   * Params:
   * Date: 2024/2/26
   */
  saveEncryptSetting = () => {
    const { baseFormStore: { form } } = this.props;
    const { OPEN_APPLICATION_ENCRYPT: isOpenEncrypt } = form.getFormParams();
    API.saveEncryptSetting({ isOpenEncrypt }).then(({ data, status, errormsg }) => {
      if (status) {
        const { isSuccess, progressId, msg } = data;
        if (!isSuccess) {
          message.error(errormsg || msg || getLabel(22620, "保存失败!"));
          return;
        }
        this.setState({ progressVisible: true, progress: 0 }, () => {
          let number = 1;
          this.timer && clearInterval(this.timer);
          this.timer = setInterval(() => {
            API.getEncryptProgress({ progressId }).then(({ status, data, errormsg }) => {
              const { progress_statue } = data;
              if (progress_statue === "success" && this.timer) {
                clearInterval(this.timer);
                this.timer = null;
                number = 1;
                this.setState({
                  progress: 100
                }, () => {
                  this.setState({
                    progressVisible: false
                  });
                });
                message.success(getLabel(22619, "保存成功!"));
              } else if (progress_statue === "in_progress" && this.timer) {
                if (this.state.progress >= 90) {
                  this.setState({
                    progress: this.state.progress + (0.001 * this.state.progress)
                  });
                } else {
                  this.setState({
                    progress: 10 * number
                  }, () => number++);
                }
              } else if (!status || (progress_statue === "fail" && this.timer)) {
                clearInterval(this.timer);
                this.timer = null;
                number = 1;
                this.setState({
                  progress: 100
                }, () => {
                  this.setState({
                    progressVisible: false
                  });
                });
                message.error(errormsg || getLabel(22620, "保存失败!"));
              }
            });
          }, 1000);
        });
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description: 规则设置
   * Params:
   * Date: 2024/2/26
   */
  ruleSettings = (key, urlName) => {
    const { baseFormStore: { form } } = this.props;
    const payload = { confValue: form.getFormParams()[key] };
    API[urlName](payload).then(({ status, errormsg }) => {
      if (status) {
        message.success(getLabel(22619, "保存成功!"));
      } else {
        message.error(errormsg || getLabel(22620, "保存失败!"));
      }
    });
  };
  unifiedSettings = (confKey, confTitle) => {
    const { baseFormStore: { form } } = this.props;
    let payload = {
      confKey, confValue: form.getFormParams()[confKey],
      module: "basic", title: confTitle
    };
    API.saveSysOperate(payload).then(({ status, errormsg }) => {
      if (status) {
        message.success(getLabel(22619, "保存成功!"));
        if (confKey === "SALARY_APPROVAL_STATUS") {
          this.setState({
            conditions: _.map(this.state.conditions, item => ({
              ...item, items: _.map(item.items, o => {
                if (
                  getKey(o) === "APPROVAL_CAN_MANUAL_FILE_STATUS" || getKey(o) === "APPROVAL_CAN_RE_CALC_STATUS" || getKey(o) === "APPROVAL_CAN_EDIT_RESULT_STATUS"
                ) {
                  return { ...o, hide: form.getFormParams()[confKey] === "0" };
                }
                return { ...o };
              })
            }))
          });
        }
      } else {
        message.error(errormsg || getLabel(22620, "保存失败!"));
      }
    });
  };

  render() {
    const { baseFormStore: { form } } = this.props;
    const { conditions, progressVisible, progress, sysinfo } = this.state;
    const ruleConditions = sysinfo.showEncryptOperationButton === "true" ? conditions :
      _.filter(conditions, o => o.title !== getLabel(543358, "加密规则"));
    return (
      <WeaTop
        title={<span>{getLabel(543355, "规则配置")}</span>} icon={<i className="icon-coms-Flow-setting"/>}
        iconBgcolor="#F14A2D" buttons={[]} className="ruleWrapper-layout"
      >
        <div className="ruleWrapper">{renderRuleForm(form, ruleConditions, this.handleChange)}</div>
        {/*加解密进度条*/}
        {
          progressVisible &&
          <ProgressModal title={getLabel(543360, "加密/解密中...")} visible={progressVisible} progress={progress}
                         onCancel={() => this.setState({ progressVisible: false, progress: 0 })}/>
        }
      </WeaTop>
    );
  }
}

export default RuleConfig;
