/*
 * Author: 黎永顺
 * name: 规则配置
 * Description:
 * Date: 2022-09-19 18:15:32
 */
import React, { Component } from "react";
import {
  WeaCheckbox,
  WeaFormItem,
  WeaInputNumber,
  WeaLocaleProvider,
  WeaNewScroll,
  WeaSearchGroup,
  WeaSelect,
  WeaTop
} from "ecCom";
import { message, Modal } from "antd";
import * as API from "../../apis/ruleconfig";
import "./index.less";
import ProgressModal from "../../components/progressModal";

const { getLabel } = WeaLocaleProvider;

export default class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      matchRuleOptions: [], orderOptions: [], ascOptions: [], employeeOptions: [],
      saveParams: {
        orderRule: "",
        ascOrDesc: "",
        rule: "",
        enctry: "1",
        operateTaxDeclaration: "1",
        matchRule: "",
        confValue: "0",
        withDrawTaxDeclaration: "0",
        extEmpsWitch: "0",
        salaryAcctFixedColumns: 0,
        welBaseDiffByPerAndCom: "0",
        welBaseAutoAdjust: "0"
      },
      showEncryptOperationButton: "",
      progressVisible: false,
      progress: 50
    };
  }

  async componentDidMount() {
    const { saveParams } = this.state;
    const [
      matchRuleEnum, orderRuleEnum, ascOrDescEnum, matchEmployeeModeEnum,
      // orderRules, codeRule, appSettings,
      sysInfo
    ] = await Promise.all([
      this.matchRuleEnum(), this.orderRuleEnum(), this.ascOrDescEnum(), this.matchEmployeeModeEnum(),
      // this.sysOrderRule(), this.sysConfCodeRule(), this.queryAppsetting(),
      this.sysinfo()
    ]);
    const matchRuleOptions = _.map(matchRuleEnum.data, it => ({ key: it.value, showname: it.defaultLabel }));
    const orderOptions = _.map(orderRuleEnum.data, it => ({ key: it.value, showname: it.defaultLabel }));
    const ascOptions = _.map(ascOrDescEnum.data, it => ({ key: it.value, showname: it.defaultLabel }));
    const employeeOptions = _.map(matchEmployeeModeEnum.data, it => ({ key: it.value, showname: it.defaultLabel }));
    const {
      data: {
        ascOrDesc = "", orderRule = "", showEncryptOperationButton, matchEmployeeMode: rule = "",
        taxDeclarationFunction: operateTaxDeclaration = "1", salaryArchiveDelete: confValue,
        salaryAcctEmployeeRule: matchRule, WITHDRAW_TAX_DECLARATION: withDrawTaxDeclaration = "0",
        OPEN_APPLICATION_ENCRYPT: enctry = "1", extEmpsWitch = "0", salaryAcctFixedColumns = "0",
        welBaseDiffByPerAndCom = "0", welBaseAutoAdjust = "0"
      }
    } = sysInfo;
    // const { data: { ascOrDesc, orderRule } } = orderRules;
    // const { data: rule } = codeRule;
    // const {
    //   data: {
    // showEncryptOperationButton,
    // isOpenEncrypt: enctry
    // isOpenTaxDeclaration: operateTaxDeclaration,
    // salaryAcctEmployeeRule: matchRule,
    // salaryArchiveDelete: confValue,
    // withDrawTaxDeclaration
    //   }
    // } = appSettings;
    this.setState({
      matchRuleOptions, orderOptions, ascOptions, employeeOptions,
      showEncryptOperationButton,
      saveParams: {
        ...saveParams,
        ascOrDesc, orderRule, rule, enctry, matchRule, confValue, withDrawTaxDeclaration, salaryAcctFixedColumns,
        extEmpsWitch, operateTaxDeclaration: (operateTaxDeclaration && operateTaxDeclaration !== "0") ? "1" : "0",
        welBaseDiffByPerAndCom, welBaseAutoAdjust
      }
    });
  }

  sysinfo = () => {
    return API.sysinfo();
  };

  sysOrderRule = () => {
    return API.sysOrderRule();
  };
  sysConfCodeRule = () => {
    return API.sysConfCodeRule({ code: "matchEmployeeMode" });
  };
  queryAppsetting = () => {
    return API.queryAppsetting();
  };
  matchRuleEnum = () => {
    const payload = {
      enumClass: "com.engine.salary.sys.enums.SalaryAcctEmployeeRuleEnum"
    };
    return API.commonEnumList(payload);
  };
  orderRuleEnum = () => {
    const payload = {
      enumClass: "com.engine.salary.sys.enums.OrderRuleEnum"
    };
    return API.commonEnumList(payload);
  };
  ascOrDescEnum = () => {
    const payload = {
      enumClass: "com.engine.salary.sys.enums.AscOrDescEnum"
    };
    return API.commonEnumList(payload);
  };
  matchEmployeeModeEnum = () => {
    const payload = {
      enumClass: "com.engine.salary.sys.enums.MatchEmployeeModeEnum"
    };
    return API.commonEnumList(payload);
  };
  updateOrderRule = () => {
    API.updateOrderRule(_.pick(this.state.saveParams, ["orderRule", "ascOrDesc"]))
      .then(({ status, errormsg }) => {
        if (status) {
          message.success(getLabel(22619, "保存成功!"));
        } else {
          message.error(errormsg || getLabel(22620, "保存失败!"));
        }
      });
  };
  saveMatchEmployeeModeRule = () => {
    API.saveMatchEmployeeModeRule(_.pick(this.state.saveParams, ["rule"])).then(({ status, errormsg }) => {
      if (status) {
        message.success(getLabel(22619, "保存成功!"));
      } else {
        message.error(errormsg || getLabel(22620, "保存失败!"));
      }
    });
  };
  saveSalaryAcctEmployeeRule = () => {
    API.saveSalaryAcctEmployeeRule({ rule: this.state.saveParams.matchRule })
      .then(({ status, errormsg }) => {
        if (status) {
          message.success(getLabel(22619, "保存成功!"));
        } else {
          message.error(errormsg || getLabel(22620, "保存失败!"));
        }
      });
  };
  operateTaxDeclarationFunction = () => {
    API.operateTaxDeclarationFunction(_.pick(this.state.saveParams, ["operateTaxDeclaration"]))
      .then(({ status, errormsg }) => {
        if (status) {
          message.success(getLabel(22619, "保存成功!"));
        } else {
          message.error(errormsg || getLabel(22620, "保存失败!"));
        }
      });
  };
  saveEncryptSetting = () => {
    API.saveEncryptSetting({ isOpenEncrypt: this.state.saveParams.enctry })
      .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);
          });
        }
      });
  };
  saveArchiveDelete = () => {
    API.saveArchiveDelete(_.pick(this.state.saveParams, ["confValue"]))
      .then(({ status, errormsg }) => {
        if (status) {
          message.success(getLabel(22619, "保存成功!"));
        } else {
          message.error(errormsg || getLabel(22620, "保存失败!"));
        }
      });
  };
  saveSysOperate = (payload) => {
    API.saveSysOperate({ ...payload })
      .then(({ status, errormsg }) => {
        if (status) {
          message.success(getLabel(22619, "保存成功!"));
        } else {
          message.error(errormsg || getLabel(22620, "保存失败!"));
        }
      });
  };
  withDrawTaxDeclaration = () => {
    API.saveWithDrawTaxDeclaration({ confValue: _.pick(this.state.saveParams, ["withDrawTaxDeclaration"]).withDrawTaxDeclaration })
      .then(({ status, errormsg }) => {
        if (status) {
          message.success(getLabel(22619, "保存成功!"));
        } else {
          message.error(errormsg || getLabel(22620, "保存失败!"));
        }
      });
  };

  handleChange = (key, val) => {
    const { saveParams } = this.state;
    Modal.confirm({
      title: getLabel(131329, "信息确认"),
      content: (key === "operateTaxDeclaration" && val === "0") ? getLabel(111, "关闭之后，将无法开启,确认要保存吗?") : getLabel(111, "确认要保存吗?"),
      onOk: () => {
        this.setState({
          saveParams: {
            ...saveParams,
            [key]: val
          }
        }, () => {
          switch (key) {
            case "orderRule":
            case "ascOrDesc":
              this.updateOrderRule();
              break;
            case "rule":
              this.saveMatchEmployeeModeRule();
              break;
            case "matchRule":
              this.saveSalaryAcctEmployeeRule();
              break;
            case "operateTaxDeclaration":
              this.operateTaxDeclarationFunction();
              break;
            case "enctry":
              this.saveEncryptSetting();
              break;
            case "confValue":
              this.saveArchiveDelete();
              break;
            case "withDrawTaxDeclaration":
              this.withDrawTaxDeclaration();
              break;
            case "extEmpsWitch":
              this.saveSysOperate({
                title: getLabel(111, "开启非系统人员"),
                module: "basic", confKey: key,
                confValue: val
              });
              break;
            case "salaryAcctFixedColumns":
              this.saveSysOperate({
                title: getLabel(111, "薪资核算固定列头数"),
                module: "basic", confKey: key,
                confValue: !_.isNil(val) ? val.toString() : "0"
              });
              break;
            case "welBaseDiffByPerAndCom":
            case "welBaseAutoAdjust":
              this.saveSysOperate({
                title: key === "welBaseDiffByPerAndCom" ?
                  getLabel(111, "福利档案基数区分个人和公司") :
                  getLabel(111, "福利档案导入基数不符合要求时自动调整为上限/下限"),
                module: "basic", confKey: key,
                confValue: val
              });
              break;
            default:
              break;
          }
        });
      },
      onCancel: () => {
        this.setState({
          saveParams: {
            ...saveParams,
            [key]: saveParams[key]
          }
        });
      }
    });
  };

  render() {
    const {
      saveParams,
      matchRuleOptions,
      orderOptions,
      ascOptions,
      employeeOptions,
      showEncryptOperationButton
    } = this.state;
    const {
      orderRule,
      ascOrDesc,
      rule,
      enctry,
      operateTaxDeclaration,
      matchRule,
      confValue,
      withDrawTaxDeclaration,
      extEmpsWitch,
      salaryAcctFixedColumns,
      welBaseDiffByPerAndCom,
      welBaseAutoAdjust
    } = saveParams;
    return (
      <div className="ruleWrapper">
        <WeaTop
          title={<span>{getLabel(543355, "规则配置")}</span>}
          icon={<i className="icon-coms-Flow-setting"/>}
          iconBgcolor="#F14A2D"
          buttons={[]}
        />
        <WeaNewScroll height={`calc(100% - 46px)`}>
          <WeaSearchGroup title={getLabel(543356, "排序规则")} showGroup center>
            <WeaFormItem label={getLabel(15512, "排序字段")} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
              <WeaSelect options={orderOptions} value={orderRule}
                         onChange={val => this.handleChange("orderRule", val)}
              />
            </WeaFormItem>
            <WeaFormItem label={getLabel(543351, "正序/倒序")} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
              <WeaSelect options={ascOptions} value={ascOrDesc}
                         onChange={val => this.handleChange("ascOrDesc", val)}
              />
            </WeaFormItem>
          </WeaSearchGroup>
          <WeaSearchGroup title={getLabel(543357, "人员校验规则")} showGroup center>
            <WeaFormItem label={getLabel(543352, "人员字段")} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
              <WeaSelect options={employeeOptions} value={rule}
                         onChange={val => this.handleChange("rule", val)}
              />
            </WeaFormItem>
          </WeaSearchGroup>
          {
            showEncryptOperationButton === "true" &&
            <WeaSearchGroup title={getLabel(543358, "加密规则")} showGroup center>
              <WeaFormItem label={getLabel(526997, "加密设置")} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
                <WeaCheckbox display="switch" value={enctry}
                             onChange={val => this.handleChange("enctry", val)}/>
              </WeaFormItem>
            </WeaSearchGroup>
          }
          <WeaSearchGroup title={getLabel(111, "算税规则")} showGroup center>
            <WeaFormItem label={getLabel(111, "系统算税")} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
              <WeaCheckbox display="switch" value={operateTaxDeclaration}
                           disabled={!operateTaxDeclaration || operateTaxDeclaration === "0"}
                           onChange={val => this.handleChange("operateTaxDeclaration", val)}/>
            </WeaFormItem>
            <WeaFormItem label={getLabel(111, "撤回申报表")} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
              <WeaCheckbox display="switch" value={withDrawTaxDeclaration}
                           onChange={val => this.handleChange("withDrawTaxDeclaration", val)}/>
            </WeaFormItem>
          </WeaSearchGroup>
          <WeaSearchGroup title={getLabel(538004, "薪资档案")} showGroup center>
            <WeaFormItem label={getLabel(111, "允许删除档案")} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
              <WeaCheckbox display="switch" value={confValue}
                           onChange={val => this.handleChange("confValue", val)}/>
            </WeaFormItem>
          </WeaSearchGroup>
          <WeaSearchGroup title={getLabel(111, "福利档案基数")} showGroup center>
            <WeaFormItem label={getLabel(111, "区分个人和公司")} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
              <WeaCheckbox display="switch" value={welBaseDiffByPerAndCom}
                           onChange={val => this.handleChange("welBaseDiffByPerAndCom", val)}/>
            </WeaFormItem>
            <WeaFormItem label={getLabel(111, "导入基数自动调整上/下限")} labelCol={{ span: 8 }}
                         wrapperCol={{ span: 16 }}>
              <WeaCheckbox display="switch" value={welBaseAutoAdjust}
                           onChange={val => this.handleChange("welBaseAutoAdjust", val)}/>
            </WeaFormItem>
          </WeaSearchGroup>
          <WeaSearchGroup title={getLabel(111, "薪资核算人员匹配规则")} showGroup center>
            <WeaFormItem label={getLabel(111, "匹配规则")} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
              <WeaSelect options={matchRuleOptions} value={matchRule}
                         onChange={val => this.handleChange("matchRule", val)}
              />
            </WeaFormItem>
          </WeaSearchGroup>
          <WeaSearchGroup title={getLabel(111, "薪资核算固定列头数")} showGroup center>
            <WeaFormItem label={getLabel(111, "固定数")} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
              <WeaInputNumber min={0} value={salaryAcctFixedColumns}
                              onChange={v => this.setState({
                                saveParams: { ...saveParams, salaryAcctFixedColumns: v }
                              })}
                              onBlur={val => this.handleChange("salaryAcctFixedColumns", val)}
              />
            </WeaFormItem>
          </WeaSearchGroup>
          <WeaSearchGroup title={getLabel(111, "非系统人员")} showGroup center>
            <WeaFormItem label={getLabel(111, "开启非系统人员")} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
              <WeaCheckbox display="switch" value={extEmpsWitch}
                           onChange={val => this.handleChange("extEmpsWitch", val)}/>
            </WeaFormItem>
          </WeaSearchGroup>
          {
            this.state.progressVisible &&
            <ProgressModal
              title={getLabel(543360, "加密/解密中...")}
              visible={this.state.progressVisible}
              onCancel={() => {
                this.setState({ progressVisible: false, progress: 0 });
              }}
              progress={this.state.progress}
            />
          }
        </WeaNewScroll>
      </div>
    );
  }
}

export const Select = payload => {
  const {
    label,
    onChange,
    value,
    options = [],
    viewAttr = 3,
    detailtype = 1,
    multiple = false,
    showSearch = false
  } = payload;
  return (
    <WeaFormItem label={label} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
      <WeaSelect options={multiple ? options : [...options]} viewAttr={viewAttr}
                 detailtype={detailtype}
                 value={value}
                 multiple={multiple}
                 showSearch={showSearch}
                 optionFilterProp="children"
                 style={multiple ? { width: 600 } : {}}
                 onChange={(selected, showName) => onChange({ type: label, selected, showName })}/>
    </WeaFormItem>
  );
};
