/*
 * Author: 黎永顺
 * name:工资单发放-重构页面新建编辑模板基础设置
 * Description:
 * Date: 2023/10/13
 */
import React, { Component } from "react";
import { toJS } from "mobx";
import { WeaFormItem, WeaLocaleProvider, WeaTools } from "ecCom";
import { tempBaseSetConditions, tempBaseSetFbConditions } from "../conditions";
import { payrollFormRender } from "../../form";
import { getPayrollBaseForm, getReplenishRuleSetOptions } from "../../../../apis/payroll";
import { commonEnumList } from "../../../../apis/archive";
import { SendTimeComp } from "../../../payroll/stepForm/baseInformForm";
import SmsSettingDialog from "./smsSettingDialog";

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

class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      conditions: [], salaryMonthOptions: [], fbConditions: [],
      formData: {
        autoSendDayOfMonth: "1",
        autoSendTimeOfDay: "09:00",
        autoSendCycleType: "1"
      },
      smsSettingDialog: { visible: false, content: "", salarySobId: "" }
    };
  }

  componentDidMount() {
    this.commonEnumList();
    this.props.visible && this.getPayrollBaseForm(this.props);
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) this.getPayrollBaseForm(nextProps);
    if (nextProps.visible !== this.props.visible && !nextProps.visible) {
      nextProps.payrollStore.setTmplDataSource({});
      nextProps.payrollStore.initPayrollTempForm();
      nextProps.payrollStore.initPayrollTempFeedbackForm();
    }
  }

  commonEnumList = () => {
    commonEnumList({ enumClass: "com.engine.salary.enums.salarysend.SalaryAutoSendCycleTypeEnum" })
      .then(({ status, data }) => {
        if (status && !_.isEmpty(data)) {
          this.setState({
            salaryMonthOptions: _.map(data, it => ({ key: it.value.toString(), showname: it.defaultLabel }))
          });
        }
      });
  };
  getPayrollBaseForm = (props) => {
    const { detail, tmplId: id, payrollStore: { payrollTempForm, payrollTempFeedbackForm, tmplDataSource } } = props;
    getPayrollBaseForm({ id }).then(async ({ status, data }) => {
      if (status) {
        const { salaryTemplateBaseSet: { salarySobOptions, data: result } } = data;
        const {
          autoSendDayOfMonth = "1", autoSendTimeOfDay = "09:00", autoSendCycleType = "1",
          smsSetting = "", ...fieldsEchoData
        } = {
          ...result, ...toJS(tmplDataSource),
          reissueRule: (
            (!id && (_.isEmpty(toJS(tmplDataSource)) || (!_.isEmpty(toJS(tmplDataSource)) && toJS(tmplDataSource).replenishRule === "ALL"))) ||
            (id && ((_.isEmpty(toJS(tmplDataSource)) && !result.replenishRule) || (!_.isEmpty(toJS(tmplDataSource)) && toJS(tmplDataSource).replenishRule === "ALL")))
          ) ? "0" : "1"
        };
        const { data: replenishRuleOptions } = (fieldsEchoData["reissueRule"] === "1" && fieldsEchoData["salarySob"]) ? await getReplenishRuleSetOptions({ salarySobId: fieldsEchoData["salarySob"] }) : [];
        this.setState({
          conditions: _.map(tempBaseSetConditions, it => {
            if (it.title === "baseSet") {
              return {
                ...it, title: getLabel(82743, "基础信息"),
                items: _.map(it.items, o => {
                  if (getKey(o) === "salarySob") {
                    return {
                      ...o, options: _.map(salarySobOptions, g => ({ key: g.id.toString(), showname: g.name })),
                      viewAttr: _.isNil(id) ? o.viewAttr : 1
                    };
                  } else if (getKey(o) === "reissueRule") {
                    return {
                      ...o, viewAttr: !detail ? o.viewAttr : 1, options: [
                        { key: "0", showname: getLabel(332, "全部") },
                        { key: "1", showname: getLabel(542696, "按规则") }
                      ]
                    };
                  } else if (getKey(o) === "replenishRule") {
                    return {
                      ...o, hide: (_.isNil(fieldsEchoData["reissueRule"]) || fieldsEchoData["reissueRule"] === "0"),
                      options: _.map(replenishRuleOptions, t => ({ key: t.id, showname: t.content })),
                      viewAttr: !detail ? o.viewAttr : 1
                    };
                  }
                  return { ...o, viewAttr: !detail ? o.viewAttr : 1 };
                })
              };
            } else if (it.title === "sendSet") {
              return {
                ...it, title: getLabel(18905, "发送设置"),
                items: _.map(it.items, o => {
                  if (getKey(o) === "autoSendStatus") {
                    return {
                      ...o, viewAttr: !detail ? o.viewAttr : 1,
                      helpfulTitle: getLabel(544272, "开启后，还需在计划任务中配置定时任务，执行工资单定时发送任务；")
                    };
                  } else if (getKey(o) === "smsSetting") {
                    return {
                      ...o, viewAttr: !detail ? o.viewAttr : 1,
                      hide: _.isNil(fieldsEchoData["smsStatus"]) || !fieldsEchoData["smsStatus"] || (!_.isNil(fieldsEchoData["smsStatus"]) && (fieldsEchoData["smsStatus"].toString() === "0"))
                    };
                  }
                  return { ...o, viewAttr: !detail ? o.viewAttr : 1 };
                })
              };
            }
          }),
          fbConditions: _.map(tempBaseSetFbConditions, it => {
            if (it.title === "feedbackSet") {
              return {
                ...it, title: getLabel(544092, "工资单确认反馈设置"),
                items: _.map(it.items, o => {
                  if (getKey(o) === "autoAckDays") {
                    return {
                      ...o, viewAttr: !detail ? o.viewAttr : 1,
                      hide: _.isNil(fieldsEchoData["ackFeedbackStatus"]) ? o.hide : !fieldsEchoData["ackFeedbackStatus"],
                      helpfulTitle: getLabel(544273, "开启后，还需在计划任务中配置定时任务，执行自动确认任务；邮箱端查看工资单暂不支持确认及反馈；")
                    };
                  } else if (getKey(o) === "feedbackUrl" || getKey(o) === "mobileFeedbackUrl") {
                    return {
                      ...o, viewAttr: !detail ? o.viewAttr : 1,
                      hide: _.isNil(fieldsEchoData["feedbackStatus"]) ? o.hide : !fieldsEchoData["feedbackStatus"]
                    };
                  }
                  return { ...o, viewAttr: !detail ? o.viewAttr : 1 };
                })
              };
            }
          })
        }, () => {
          payrollTempForm.initFormFields(this.state.conditions);
          payrollTempFeedbackForm.initFormFields(this.state.fbConditions);
          //字段回显
          const tempBaseSetDomkeys = _.reduce(tempBaseSetConditions, (pre, cur) => ([...pre, ..._.map(cur.items, o => getKey(o))]), []),
            tempBaseSetFbDomkeys = _.reduce(tempBaseSetFbConditions, (pre, cur) => ([...pre, ..._.map(cur.items, o => getKey(o))]), []);
          _.map(tempBaseSetDomkeys, it => {
            switch (it) {
              case "msgStatus":
                payrollTempForm.updateFields({ [it]: _.isNil(fieldsEchoData[it]) ? "1" : fieldsEchoData[it] ? "1" : "0" });
                break;
              case "reissueRule":
                payrollTempForm.updateFields({ [it]: fieldsEchoData[it] ? fieldsEchoData[it] : "0" });
                break;
              case "emailStatus":
              case "autoSendStatus":
              case "smsStatus":
                payrollTempForm.updateFields({ [it]: fieldsEchoData[it] ? "1" : "0" });
                this.setState({
                  smsSettingDialog: {
                    ...this.state.smsSettingDialog,
                    content: (!_.isNil(smsSetting) && smsSetting.length > 0) ? JSON.parse(smsSetting).content : ""
                  }
                });
                break;
              default:
                payrollTempForm.updateFields({ [it]: fieldsEchoData[it] ? fieldsEchoData[it].toString() : "" });
                break;
            }
          });
          _.map(tempBaseSetFbDomkeys, it => {
            if (it === "ackFeedbackStatus" || it === "feedbackStatus") {
              payrollTempFeedbackForm.updateFields({ [it]: fieldsEchoData[it] ? "1" : "0" });
            } else {
              payrollTempFeedbackForm.updateFields({ [it]: (!_.isNil(fieldsEchoData[it]) && fieldsEchoData[it]) ? fieldsEchoData[it].toString() : "/" });
            }
          });
          this.setState({
            formData: {
              ...this.state.formData,
              autoSendDayOfMonth: !_.isNil(autoSendDayOfMonth) ? autoSendDayOfMonth : "1",
              autoSendTimeOfDay: !_.isNil(autoSendTimeOfDay) ? autoSendTimeOfDay : "09:00",
              autoSendCycleType: !_.isNil(autoSendCycleType) ? autoSendCycleType : "1"
            }
          });
          this.forceUpdate();
        });
      }
    });
  };
  handleChange = async (params) => {
    const { payrollStore: { payrollTempForm, setHasBeenModify } } = this.props;
    const key = _.keys(params)[0], salarySobId = payrollTempForm.getFormParams().salarySob,
      reissueRule = payrollTempForm.getFormParams().reissueRule;
    const { data: replenishRuleOptions } = (reissueRule === "1" && salarySobId) ? await getReplenishRuleSetOptions({ salarySobId }) : [];
    if (key === "reissueRule") {
      this.setState({
        conditions: _.map(this.state.conditions, it => {
          if (it.title === getLabel(82743, "基础信息")) {
            return {
              ...it, items: _.map(it.items, o => {
                if (getKey(o) === "replenishRule") {
                  return {
                    ...o, hide: params[key].value === "0",
                    rules: (!_.isEmpty(replenishRuleOptions) && reissueRule === "1") ? "required|string" : "",
                    viewAttr: (!_.isEmpty(replenishRuleOptions) && reissueRule === "1") ? 3 : 2,
                    options: _.map(replenishRuleOptions, t => ({ key: t.id, showname: t.content }))
                  };
                }
                return { ...o };
              })
            };
          }
          return { ...it };
        })
      }, () => {
        payrollTempForm.initFormFields(this.state.conditions);
        this.resetRequiredForm();
      });
    } else if (key === "salarySob") {
      this.setState({
        conditions: _.map(this.state.conditions, it => {
          if (it.title === getLabel(82743, "基础信息")) {
            return {
              ...it, items: _.map(it.items, o => {
                if (getKey(o) === "replenishRule") {
                  return {
                    ...o, options: _.map(replenishRuleOptions, t => ({ key: t.id, showname: t.content })),
                    rules: (!_.isEmpty(replenishRuleOptions) && reissueRule === "1") ? "required|string" : "",
                    viewAttr: (!_.isEmpty(replenishRuleOptions) && reissueRule === "1") ? 3 : 2
                  };
                }
                return { ...o };
              })
            };
          }
          return { ...it };
        })
      }, () => {
        payrollTempForm.initFormFields(this.state.conditions);
        const salarySob = payrollTempForm.getFormDatas().salarySob;
        payrollTempForm.updateFields({
          name: salarySob.valueSpan,
          replenishName: salarySob.valueSpan + "-补发工资单"
        });
        this.resetRequiredForm();
      });
    } else if (key === "smsStatus") {
      this.setState({
        conditions: _.map(this.state.conditions, it => {
          if (it.title === getLabel(18905, "发送设置")) {
            return {
              ...it, items: _.map(it.items, o => {
                if (getKey(o) === "smsSetting") {
                  return {
                    ...o, hide: params[key].value === "0"
                    // rules: (!_.isEmpty(replenishRuleOptions) && reissueRule === "1") ? "required|string" : "",
                    // viewAttr: (!_.isEmpty(replenishRuleOptions) && reissueRule === "1") ? 3 : 2,
                  };
                }
                return { ...o };
              })
            };
          }
          return { ...it };
        })
      }, () => {
        payrollTempForm.initFormFields(this.state.conditions);
      });
    }
    setHasBeenModify(true);
    this.forceUpdate();
  };
  handleSmsSetting = () => {
    const { payrollStore: { payrollTempForm } } = this.props;
    const { smsSettingDialog } = this.state;
    this.setState({
      smsSettingDialog: {
        ...smsSettingDialog, visible: true,
        salarySobId: payrollTempForm.getFormParams().salarySob
      }
    });
  };
  resetRequiredForm = () => {
    const { payrollStore: { payrollTempForm } } = this.props;
    const reissueRule = payrollTempForm.getFormParams().reissueRule;
    if (reissueRule === "0") payrollTempForm.updateFields({ replenishRule: "0" });
    if (reissueRule === "1") payrollTempForm.updateFields({ replenishRule: "" });
  };
  handleFbChange = (params) => {
    const { payrollStore: { payrollTempFeedbackForm, setHasBeenModify } } = this.props;
    const key = _.keys(params)[0];
    if (key === "ackFeedbackStatus" || key === "feedbackStatus") {
      this.setState({
        fbConditions: _.map(this.state.fbConditions, it => {
          if (it.title === getLabel(544092, "工资单确认反馈设置")) {
            return {
              ...it, items: _.map(it.items, o => {
                if (getKey(o) === "autoAckDays" && key === "ackFeedbackStatus") {
                  return {
                    ...o, hide: params["ackFeedbackStatus"].value === "0"
                  };
                } else if (key === "feedbackStatus" && (getKey(o) === "feedbackUrl" || getKey(o) === "mobileFeedbackUrl")) {
                  return {
                    ...o, hide: params["feedbackStatus"].value === "0"
                  };
                } else {
                  return { ...o };
                }
              })
            };
          }
          return { ...it };
        })
      }, () => {
        payrollTempFeedbackForm.initFormFields(this.state.fbConditions);
        const ackFeedbackStatus = payrollTempFeedbackForm.getFormParams().ackFeedbackStatus;
        const feedbackStatus = payrollTempFeedbackForm.getFormParams().feedbackStatus;
        if (ackFeedbackStatus === "0") payrollTempFeedbackForm.updateFields({
          autoAckDays: "7"
        });
        if (feedbackStatus === "0") payrollTempFeedbackForm.updateFields({
          feedbackUrl: "/",
          mobileFeedbackUrl: "/"
        });
      });
    }
    setHasBeenModify(true);
    this.forceUpdate();
  };

  render() {
    const { conditions, fbConditions, formData, salaryMonthOptions, smsSettingDialog } = this.state;
    const { payrollStore: { payrollTempForm, payrollTempFeedbackForm } } = this.props;
    const autoSendStatus = payrollTempForm.getFormParams().autoSendStatus;
    return (
      <React.Fragment>
        {!_.isEmpty(fbConditions) && payrollFormRender(payrollTempForm, conditions, this.handleChange, this.handleSmsSetting, smsSettingDialog.content)}
        {
          autoSendStatus === "1" &&
          <WeaFormItem className="sendTime-outer" label={getLabel(18961, "发送时间")} labelCol={{ span: 6 }}
                       wrapperCol={{ span: 16 }}>
            <SendTimeComp salaryMonthOptions={salaryMonthOptions} value={{ ...formData }}
                          onChange={(v) => this.setState({ formData: { ...formData, ...v } })}
            />
          </WeaFormItem>
        }
        {!_.isEmpty(fbConditions) && payrollFormRender(payrollTempFeedbackForm, fbConditions, this.handleFbChange)}
        <SmsSettingDialog {...smsSettingDialog}
                          onCancel={({ smsContent } = {}) => this.setState({
                            smsSettingDialog: { ...smsSettingDialog, visible: false, content: smsContent || "" }
                          })}
        />
      </React.Fragment>
    );
  }
}

export default Index;
