/*
 * Author: 黎永顺
 * name:社保福利档案页面重构-查看编辑弹框
 * Description:
 * Date: 2023/11/6
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaDialog, WeaLocaleProvider, WeaSlideModal, WeaTools } from "ecCom";
import * as API from "../../../../../apis/welfareArchive";
import { getTaxAgentSelectList } from "../../../../../apis/taxAgent";
import { sysinfo } from "../../../../../apis/ruleconfig";
import { getWelfareSearchsForm, welfareConditions } from "../../config";
import { getConditionDomkeys, toDecimal_n } from "../../../../../util";
import { Button, message, Modal } from "antd";

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

@inject("archivesStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false, conditions: [], formData: {}, errorDialog: { visible: false, errorMsg: "" }
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) {
      document.querySelector(".salary-welfare-archive").classList.add("zIndex0-welfare-archive");
      const promise = this.getBaseForm(nextProps);
    } else if (nextProps.visible !== this.props.visible && !nextProps.visible) {
      const { archivesStore: { initWelfareProfileForm } } = nextProps;
      document.querySelector(".salary-welfare-archive").classList.remove("zIndex0-welfare-archive");
      initWelfareProfileForm();
    }
  }

  getBaseForm = async (props) => {
    const [taxAgentListData, sysInfoData] = await Promise.all([getTaxAgentSelectList(), sysinfo()]);
    const {
      archivesStore: { welfareProfileForm }, socialBase, fundBase, otherBase, runStatuses,
      employeeId, paymentOrganization, socialBaseData, fundBaseData, othersBaseData,
      showOperateBtn
    } = props;
    let socialComData = {}, fundComData = {}, otherComData = {};
    if (!_.isNil(socialBase.comItems)) {
      _.forEach(getConditionDomkeys(socialBase.comItems), o => {
        socialComData = {
          ...socialComData,
          [`${o}_com`]: !_.isNil(socialBase.comData) ? socialBase.comData[o] : _.find(socialBase.comItems[0].items, k => getKey(k) === o).min
        };
      });
    }
    if (!_.isNil(fundBase.comItems)) {
      _.forEach(getConditionDomkeys(fundBase.comItems), o => {
        fundComData = {
          ...fundComData,
          [`${o}_com`]: !_.isNil(fundBase.comData) ? fundBase.comData[o] : _.find(fundBase.comItems[0].items, k => getKey(k) === o).min
        };
      });
    }
    if (!_.isNil(otherBase.comItems)) {
      _.forEach(getConditionDomkeys(otherBase.comItems), o => {
        otherComData = {
          ...otherComData,
          [`${o}_com`]: !_.isNil(otherBase.comData) ? otherBase.comData[o] : _.find(otherBase.comItems[0].items, k => getKey(k) === o).min
        };
      });
    }
    const payload = { employeeId, paymentOrganization, welfareTypeEnum: "" };
    API.getBaseForm(payload).then(({ status, data }) => {
      if (status) {
        const { data: result } = data;
        const formData = {
          ...result, ...socialBaseData, ...fundBaseData, ...othersBaseData,
          ...socialBase.data, ...fundBase.data, ...otherBase.data,
          ...socialComData, ...fundComData, ...otherComData,
          welBaseAutoAdjust: sysInfoData.data.welBaseAutoAdjust === "1"
        };
        this.setState({
          formData,
          conditions: _.map(welfareConditions, o => {
            if (o.title === "basic") {
              return {
                ...o, title: getLabel(542699, "员工基本信息"),
                viewAttr: (runStatuses === "4,5" || !showOperateBtn) ? 1 : o.viewAttr,
                items: _.map(o.items, g => {
                  return { ...g, label: getLabel(g.lanId, g.label) };
                })
              };
            } else if (o.title === "taxAgent") {
              return {
                ...o, title: getLabel(537996, "个税扣缴义务人"),
                items: _.map(o.items, g => {
                  return {
                    ...g, label: getLabel(g.lanId, g.label),
                    options: _.map(taxAgentListData.data, j => ({ key: j.id, showname: j.content }))
                  };
                })
              };
            } else if (o.title === "social" || o.title === "fund" || o.title === "others") {
              const title = o.title === "social" ? getLabel(543194, "社保基础信息") : o.title === "fund" ? getLabel(543197, "公积金基础信息") : getLabel(543198, "其他福利基础信息");
              return {
                ...o, title,
                items: _.map(o.items, g => {
                  if (getKey(g) === "socialSchemeId" || getKey(g) === "fundSchemeId" || getKey(g) === "otherSchemeId" || _.lowerCase(getKey(g)).indexOf("take") !== -1) {
                    const key = _.lowerCase(getKey(g)).indexOf("take") !== -1 ? "underTake" : getKey(g);
                    return {
                      ...g, label: getLabel(g.lanId, g.label),
                      viewAttr: (runStatuses === "4,5" || !showOperateBtn) ? 1 : g.viewAttr,
                      options: _.find(props[`${o.title}Items`], j => j.domkey[0] === key).options,
                      otherParams: {
                        showSearch: true, optionFilterProp: "children"
                      }
                    };
                  } else if (getKey(g).indexOf("StartTime") !== -1) {
                    return {
                      ...g, label: getLabel(g.lanId, g.label),
                      viewAttr: (runStatuses === "4,5" || !showOperateBtn) ? 1 : (formData[o["typename"]][`${o.title}Name`] && showOperateBtn) ? 3 : g.viewAttr
                    };
                  }
                  return {
                    ...g, label: getLabel(g.lanId, g.label),
                    viewAttr: (runStatuses === "4,5" || !showOperateBtn) ? 1 : g.viewAttr
                  };
                })
              };
            }
            return {
              ...o, items: _.map(o.items, g => {
                return {
                  ...g, label: getLabel(g.lanId, g.label),
                  viewAttr: (runStatuses === "4,5" || !showOperateBtn) ? 1 : g.viewAttr
                };
              })
            };
          })
        }, () => {
          welfareProfileForm.initFormFields(this.state.conditions);
          _.map(getConditionDomkeys(this.state.conditions), k => {
            if (k === "paymentOrganization") {
              welfareProfileForm.updateFields({ [k]: paymentOrganization.toString() });
            } else if (_.lowerCase(k).indexOf("social") !== -1 || k === "schemeAccount") {
              welfareProfileForm.updateFields({ [k]: formData["SOCIAL_SECURITY"][k] ? formData["SOCIAL_SECURITY"][k].toString() : "" });
            } else if (_.lowerCase(k).indexOf("fund") !== -1) {
              welfareProfileForm.updateFields({ [k]: formData["ACCUMULATION_FUND"][k] ? formData["ACCUMULATION_FUND"][k].toString() : "" });
            } else if (_.lowerCase(k).indexOf("other") !== -1) {
              welfareProfileForm.updateFields({ [k]: formData["OTHER"][k] ? formData["OTHER"][k].toString() : "" });
            } else {
              welfareProfileForm.updateFields({ [k]: formData[k] || "" });
            }
          });
        });
      }
    });
  };
  covertPayload = (welfareType, underTakeType, paymentForm, paymentComForm) => {
    const { archivesStore: { welfareProfileForm } } = this.props;
    const welfareData = welfareProfileForm.getFormParams();
    const { formData } = this.state;
    return {
      baseForm: JSON.stringify({
        ...formData[welfareType], ..._.reduce(_.keys(formData[welfareType]), (pre, cur) => {
          if (welfareData[cur] || !_.isNil(welfareData[cur])) return { ...pre, [cur]: welfareData[cur] };
          return { ...pre };
        }, {}),
        underTake: welfareData[`${underTakeType}UnderTake`]
      }),
      paymentForm: !_.isEmpty(paymentForm) ? JSON.stringify(_.reduce(paymentForm, (pre, cur) => {
        if (formData[cur] || formData[cur] === 0) return { ...pre, [cur]: toDecimal_n(formData[cur], 2).toString() };
        return { ...pre, [cur]: "0" };
      }, {})) : "",
      paymentComForm: !_.isEmpty(paymentComForm) ? JSON.stringify(_.reduce(paymentComForm, (pre, cur) => {
        if (formData[`${cur}_com`] || formData[`${cur}_com`] === 0) return {
          ...pre,
          [cur]: toDecimal_n(formData[`${cur}_com`], 2).toString()
        };
        return { ...pre, [cur]: "0" };
      }, {})) : "",
      welfareType, validate: welfareData[`${underTakeType}SchemeId`] ? !!welfareData[`${underTakeType}StartTime`] : true
    };
  };
  save = async (changeData = false) => {
    const socailPayload = this.covertPayload("SOCIAL_SECURITY", "social", getConditionDomkeys(this.props.socialBase.items), getConditionDomkeys(this.props.socialBase.comItems || [])),
      fundPayload = this.covertPayload("ACCUMULATION_FUND", "fund", getConditionDomkeys(this.props.fundBase.items), getConditionDomkeys(this.props.fundBase.comItems || [])),
      otherPayload = this.covertPayload("OTHER", "other", getConditionDomkeys(this.props.otherBase.items), getConditionDomkeys(this.props.otherBase.comItems || []));
    if (!(socailPayload.validate && fundPayload.validate && otherPayload.validate)) {
      message.warning(getLabel(111, "请维护起始缴纳月！"));
      return;
    }
    this.setState({ loading: true });
    const [{
      status: socialStatus,
      errormsg: socialErrorMsg = "!"
    }, {
      status: fundStatus,
      errormsg: fundErrorMsg = "!"
    }, {
      status: otherStatus,
      errormsg: otherErrorMsg = "!"
    }] = await Promise.all([
      API.save({ ...socailPayload, changeData }),
      API.save({ ...fundPayload, changeData }),
      API.save({ ...otherPayload, changeData })]);
    this.setState({ loading: false });
    if (socialStatus && fundStatus && otherStatus) {
      message.success(getLabel(30700, "操作成功！"));
      this.props.onClose(true);
    } else {
      !changeData && this.setState({
        errorDialog: { visible: true, errorMsg: socialErrorMsg + fundErrorMsg + otherErrorMsg }
      });
    }
  };
  updateFormData = (baseData) => this.setState({ formData: { ...this.state.formData, ...baseData } });
  handleFormChange = (val) => {
    const changeKey = _.keys(val)[0], changeVal = val[changeKey].value;
    const {
      archivesStore: { setHasBeenModify },
      onChangeProgramme, employeeId,
      paymentOrganization, showOperateBtn
    } = this.props;
    setHasBeenModify(true);
    if (changeKey === "socialSchemeId" || changeKey === "fundSchemeId" || changeKey === "otherSchemeId") {
      this.setState({
        conditions: _.map(this.state.conditions, o => {
          if (
            (o.typename === "SOCIAL_SECURITY" && changeKey === "socialSchemeId") ||
            (o.typename === "ACCUMULATION_FUND" && changeKey === "fundSchemeId") ||
            (o.typename === "OTHER" && changeKey === "otherSchemeId")
          ) {
            return {
              ...o, items: _.map(o.items, g => {
                if (getKey(g).indexOf("StartTime") !== -1) {
                  return {
                    ...g, viewAttr: (changeVal && showOperateBtn) ? 3 : g.viewAttr
                  };
                }
                return { ...g };
              })
            };
          }
          return { ...o };
        })
      });
      onChangeProgramme(changeKey.slice(0, changeKey.indexOf("SchemeId")), changeVal, {
        employeeId,
        paymentOrganization
      });
    }
  };
  handleExtraChange = (key, value) => this.setState({ formData: { ...this.state.formData, [key]: value } });
  handleSameChange = (baseItems, value) => {
    if (!value) return;
    let newFormDatas = {}, hasCompromise = false;
    baseItems.forEach((formLabel) => {
      // const { min, max } = formLabel;
      newFormDatas[getKey(formLabel)] = toDecimal_n(value, 2) || "";
      // if (min !== "0.000" && value !== "" && Number(value) < Number(min)) {
      //   hasCompromise = true;
      //   newFormDatas[getKey(formLabel)] = toDecimal_n(Number(min), 2);
      // }
      // if (max !== "0.000" && value !== "" && Number(value) > Number(max)) {
      //   hasCompromise = true;
      //   newFormDatas[getKey(formLabel)] = toDecimal_n(Number(max), 2);
      // }
    });
    if (hasCompromise) {
      message.warning(getLabel("111", "超出所选缴纳方案设置的基数上下限范围，将自动按基数上下限填充。"));
    }
    this.setState({ formData: { ...this.state.formData, ...newFormDatas } });
  };
  handleNoPaymentChange = (type, value) => this.setState({
    formData: { ...this.state.formData, [type]: { ...this.state.formData[type], nonPayment: value } }
  });
  renderTitle = () => {
    const { loading } = this.state;
    const { runStatuses, showOperateBtn } = this.props;
    return <div className="titleDialog">
      <div className="titleCol titleLeftBox">
        <div className="titleIcon"><i className="icon-coms-fa"/></div>
        <div className="title">{getLabel(543191, "员工福利档案")}</div>
      </div>
      <div className="titleCol titleRightBox">
        {
          runStatuses !== "4,5" && showOperateBtn &&
          <Button type="primary" onClick={() => this.save()} loading={loading}>{getLabel(537558, "保存")}</Button>
        }
      </div>
    </div>;
  };
  handleClose = () => {
    const { archivesStore: { hasBeenModify }, onClose } = this.props;
    if (hasBeenModify) {
      Modal.confirm({
        title: getLabel(131329, "信息确认"),
        content: getLabel(111, "确定放弃填写吗？放弃后数据将不会被保存！"),
        onOk: () => {
          onClose();
        }
      });
    } else {
      onClose();
    }
  };

  render() {
    const { archivesStore: { welfareProfileForm }, showOperateBtn } = this.props;
    const { conditions, formData, errorDialog } = this.state;
    return (
      <WeaSlideModal
        className="salary-welfare-archive-edit-layout" {...this.props}
        top={0} width={800} height={100} measureT={"%"} measureX={"px"} measureY={"%"}
        direction={"right"} title={this.renderTitle()} onClose={this.handleClose}
        content={<div className="salary-welfare-archive-edit-area">
          {
            getWelfareSearchsForm(
              welfareProfileForm, conditions, this.handleFormChange, this.handleNoPaymentChange, this.handleExtraChange,
              this.handleSameChange, formData, this.props, showOperateBtn
            )
          }
          <WeaDialog title={getLabel(111, "信息确认")} visible={errorDialog.visible}
                     style={{ width: 480, height: 200 }} hasScroll
                     buttons={[
                       <Button type="primary" onClick={() => {
                         this.setState({ errorDialog: { ...errorDialog, visible: false } }, () => {
                           const promise = this.save(true);
                           message.success(getLabel(30700, "操作成功！"));
                           this.props.onClose(true);
                         });
                       }}>{getLabel(111, "确认")}</Button>
                     ]}
                     onCancel={() => this.setState({ errorDialog: { ...errorDialog, visible: false } })}
                     bottomLeft={getLabel(111, "点击【确认】自动将不满足条件的基数值设置为对应的上限或下限值")}
          >
            <div style={{ padding: 16 }}>
              <div dangerouslySetInnerHTML={{ __html: (errorDialog.errorMsg).replace(/\n/g, "</br>") }}/>
            </div>
          </WeaDialog>
        </div>}
      />
    );
  }
}

export default Index;
