/*
 * Author: 黎永顺
 * name: 添加补缴
 * Description:
 * Date: 2022/12/30
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { message, Modal } from "antd";
import { WeaFormItem, WeaLocaleProvider, WeaSearchGroup, WeaSelect, WeaSlideModal } from "ecCom";
import SlideModalTitle from "../../../../components/slideModalTitle";
import { Picker, SelectWithAll } from "./regAddEmployee";
import { Browser } from "../../../dataAcquisition/addItems";
import { getPaymentGroup, getSupplementPaymentForm, siaccountSupplementarySave } from "../../../../apis/standingBook";
import "./index.less";
import BusinessAccounting from "./businessAccounting";
import InputPaymentAmount from "./inputPaymentAmount";
import { toDecimal_n } from "../../../../util";

const getLabel = WeaLocaleProvider.getLabel;

@inject("taxAgentStore")
@observer
class SupplementarySlide extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      baseInfo: {
        includes: "",
        includeNames: "",
        supplementType: "1",
        projectsAll: "",
        projects: "",
        billMonthList: "",
        historyMonth: ""
      },
      businessAccounting: {
        socialSecurityBase: [],
        fundBase: [],
        otherBase: []
      },
      inputPaymentAmount: {
        socialPayment: [],
        fundPayment: [],
        otherPayment: []
      }
    };
  }

  /*
   * Author: 黎永顺
   * Description: 按补缴人员的历史月份核算基数和当前档案方案核算 数据转换
   * Params: socialSecurityBase fundBase otherBase
   * Date: 2023/1/3
   */
  convertBusinessAccounting = () => {
    let payload = { socialPaymentBaseString: {}, fundPaymentBaseString: {}, otherPaymentBaseString: {} };
    const { businessAccounting } = this.state;
    _.map(Object.keys(businessAccounting), item => {
      _.map(businessAccounting[item], child => {
        const key = child.insuranceId, value = child.insuranceBase;
        _.assign(
          payload[item === "socialSecurityBase" ? "socialPaymentBaseString" : item === "fundBase" ? "fundPaymentBaseString" : "otherPaymentBaseString"],
          { [key]: value ? value.toString() : "0" }
        );
      });
    });
    for (let i in payload) {
      _.assign(payload, { [i]: JSON.stringify(payload[i]) });
    }
    return payload;
  };
  /*
   * Author: 黎永顺
   * Description: 动输入补缴金额数据整改
   * Params:
   * Date: 2023/1/3
   */
  convertInputPaymentAmount = () => {
    let payload = {
      socialPaymentPerString: {},
      socialPaymentComString: {},
      fundPaymentPerString: {},
      fundPaymentComString: {},
      otherPaymentPerString: {},
      otherPaymentComString: {}
    };
    const { inputPaymentAmount } = this.state;
    _.map(Object.keys(inputPaymentAmount), item => {
      _.map(inputPaymentAmount[item], child => {
        const key = child.insuranceId, valuePer = child[`${child.insuranceId}_per`],
          valueCom = child[`${child.insuranceId}_com`];
        if (!child.perDisabled) {
          _.assign(payload[`${item}PerString`], { [key]: toDecimal_n(valuePer, parseFloat(child.perValidNum || 2)) || "0" });
        }
        if (!child.comDisabled) {
          _.assign(payload[`${item}ComString`], { [key]: toDecimal_n(valueCom, parseFloat(child.comValidNum || 2)) || "0" });
        }
      });
    });
    for (let i in payload) {
      _.assign(payload, { [i]: JSON.stringify(payload[i]) });
    }
    return payload;
  };
  handleSaveSupplementSalary = () => {
    const { billMonth, paymentOrganization, onCancel } = this.props;
    const { baseInfo } = this.state;
    const { supplementType, projects, projectsAll, billMonthList, includes, historyMonth } = baseInfo;
    if (!projects || !billMonthList || !includes) {
      Modal.warning({
        title: "信息确认",
        content: "必要信息不完整，红色*为必填项！"
      });
      return;
    }
    if (supplementType === "2" && !historyMonth) {
      Modal.warning({
        title: "信息确认",
        content: "必要信息不完整，红色*为必填项！"
      });
      return;
    }
    const payload = {
      supplementType,
      projects: projectsAll.split(",").concat(projects.split(",")),
      billMonth,
      paymentOrganization,
      billMonthList: billMonthList.split(","),
      includes: includes.split(","),
      ...this.convertBusinessAccounting(),
      ...this.convertInputPaymentAmount()
    };
    this.setState({ loading: true });
    siaccountSupplementarySave(payload).then(({ status, errormsg }) => {
      this.setState({ loading: false });
      if (status) {
        onCancel(true);
        this.handleResetForm();
      } else {
        message.error(errormsg || "接口调用失败！");
      }
    }).catch(() => this.setState({ loading: false }));
  };
  handleResetForm = () => {
    this.setState({
      baseInfo: {
        includes: "",
        includeNames: "",
        supplementType: "1",
        projectsAll: "",
        projects: "",
        billMonthList: ""
      },
      businessAccounting: {
        socialSecurityBase: [],
        fundBase: [],
        otherBase: []
      }
    });
  };
  handleChangeItem = () => {
    const { paymentOrganization } = this.props;
    const { baseInfo } = this.state;
    const { supplementType, includes, projects, projectsAll, historyMonth } = baseInfo;
    if (supplementType === "2") {
      if (includes && (projects || projectsAll) && historyMonth) {
        const payload = {
          billMonth: historyMonth,
          paymentOrganization: Number(paymentOrganization),
          employeeId: Number(includes),
          projects: projectsAll ? projectsAll.split(",").concat(projects.split(",")) : projects.split(",")
        };
        getSupplementPaymentForm(payload).then(({ status, data, errormsg }) => {
          if (status) {
            this.setState({
              businessAccounting: {
                socialSecurityBase: _.filter(data, it => it.titleSign === "social"),
                fundBase: _.filter(data, it => it.titleSign === "fund"),
                otherBase: _.filter(data, it => it.titleSign === "other")
              }
            });
          } else {
            message.error(errormsg || "");
            this.setState({
              baseInfo: { ...baseInfo, historyMonth: "" },
              businessAccounting: {
                socialSecurityBase: [],
                fundBase: [],
                otherBase: []
              }
            });
          }
        });
      }
    } else if (supplementType === "3") {
      if (includes && (projects || projectsAll)) {
        const payload = {
          paymentOrganization: Number(paymentOrganization),
          employeeId: Number(includes),
          projects: projectsAll ? projectsAll.split(",").concat(projects.split(",")) : projects.split(",")
        };
        getPaymentGroup(payload).then(({ status, data, errormsg }) => {
          if (status) {
            this.setState({
              inputPaymentAmount: {
                socialPayment: convertData(_.filter(data, it => it.titleSign === "social")),
                fundPayment: convertData(_.filter(data, it => it.titleSign === "fund")),
                otherPayment: convertData(_.filter(data, it => it.titleSign === "other"))
              }
            });
          } else {
            message.error(errormsg || "");
            this.setState({
              inputPaymentAmount: {
                socialPayment: [],
                fundPayment: [],
                otherPayment: []
              }
            });
          }
        });
      }
    }
  };
  handleChangeBaseFieldItem = (socialSecurityBase, fundBase, otherBase) => {
    this.setState({
      businessAccounting: { socialSecurityBase, fundBase, otherBase }
    });
  };
  handleChangeInputItem = (socialPayment, fundPayment, otherPayment) => {
    this.setState({
      inputPaymentAmount: { socialPayment, fundPayment, otherPayment }
    });
  };

  render() {
    const { title, visible, onCancel, taxAgentStore: { showOperateBtn } } = this.props;
    const { baseInfo, loading, businessAccounting, inputPaymentAmount } = this.state;
    const baseItems = [
      {
        com: Browser({
          label: "对象",
          viewAttr: 3,
          value: baseInfo.includes,
          valueSpan: baseInfo.includeNames,
          onChange: ({ ids, names }) => {
            this.setState({
              baseInfo: {
                ...baseInfo,
                includes: ids,
                includeNames: names
              }
            }, () => this.handleChangeItem());
          }
        })
      },
      {
        com: Picker({
          label: "补缴月份",
          value: baseInfo.billMonthList,
          onChange: (billMonthList) => {
            this.setState({ baseInfo: { ...baseInfo, billMonthList } });
          }
        })
      },
      {
        com: SelectWithAll({
          label: "补缴项目",
          options: [
            { key: "1", showname: "社保" },
            { key: "2", showname: "公积金" },
            { key: "3", showname: "企业年金及其他福利" },
            { key: "4", showname: "养老保险" },
            { key: "5", showname: "医疗保险" }
          ],
          detailtype: 2,
          valueAll: baseInfo.projectsAll,
          value: baseInfo.projects,
          onChangeAll: ({ selected }) => {
            if (selected) {
              this.setState({
                baseInfo: {
                  ...baseInfo,
                  projectsAll: selected,
                  projects: "1,2,3,4,5"
                }
              }, () => this.handleChangeItem());
            } else {
              this.setState({
                baseInfo: {
                  ...baseInfo,
                  projectsAll: selected,
                  projects: ""
                }
              }, () => this.handleChangeItem());
            }
          },
          onChange: ({ selected }) => {
            const bool1 = selected.split(",").includes("1");
            const bool2 = selected.split(",").includes("2");
            const bool3 = selected.split(",").includes("3");
            const bool4 = selected.split(",").includes("4");
            const bool5 = selected.split(",").includes("5");
            if (bool1 && bool2 && bool3 && bool4 && bool5) {
              this.setState({
                baseInfo: {
                  ...baseInfo,
                  projectsAll: "0",
                  projects: selected
                }
              }, () => this.handleChangeItem());
            } else {
              this.setState({
                baseInfo: {
                  ...baseInfo,
                  projectsAll: "",
                  projects: selected
                }
              }, () => this.handleChangeItem());
            }
          }
        })
      },
      {
        com: SelectDetailType({
          label: "补缴金额核算方式",
          options: [
            { key: "1", showname: "按补缴人员当前档案基数及方案核算" },
            { key: "2", showname: "按补缴人员的历史月份核算基数和当前档案方案核算" },
            { key: "3", showname: "手动输入补缴金额" }
          ],
          detailtype: 3,
          value: baseInfo.supplementType,
          onChange: ({ selected: supplementType }) => {
            this.setState({
              baseInfo: {
                ...baseInfo,
                supplementType,
                historyMonth: ""
              },
              businessAccounting: {
                socialSecurityBase: [],
                fundBase: [],
                otherBase: []
              },
              inputPaymentAmount: {
                socialPayment: [],
                fundPayment: [],
                otherPayment: []
              }
            }, () => this.handleChangeItem());
          }
        })
      }
    ];
    const baseExtraItems = [
      {
        com: Picker({
          label: "补缴基数参考月份",
          value: baseInfo.historyMonth,
          onChange: (historyMonth) => {
            this.setState({ baseInfo: { ...baseInfo, historyMonth } }, () => this.handleChangeItem());
          }
        })
      }
    ];
    return (
      <WeaSlideModal
        className="supplementarySlideWrapper"
        visible={visible}
        top={0}
        measureT="%"
        width={800}
        measureX="px"
        height={100}
        measureY="%"
        direction="right"
        title={
          <SlideModalTitle
            subtitle={title}
            tabs={[]}
            loading={loading}
            showOperateBtn={showOperateBtn}
            editable={true}
            onSave={this.handleSaveSupplementSalary}
          />
        }
        content={
          <div>
            <WeaSearchGroup
              title="基础信息"
              items={baseInfo.supplementType === "2" ? [...baseItems, ...baseExtraItems] : baseItems}
              showGroup col={1}
            />
            {/* 按补缴人员的历史月份核算基数和当前档案方案核算 */}
            {
              baseInfo.supplementType === "2" &&
              <BusinessAccounting {...businessAccounting} onChangeBaseItem={this.handleChangeBaseFieldItem}/>
            }
            {/* 动输入补缴金额 */}
            {
              baseInfo.supplementType === "3" &&
              <InputPaymentAmount {...inputPaymentAmount} onChangeInputItem={this.handleChangeInputItem}/>
            }
          </div>
        }
        onClose={() => {
          onCancel();
          this.handleResetForm();
        }}
      />
    );
  }
}

export default SupplementarySlide;

export const SelectDetailType = payload => {
  const { label, onChange, value, options = [], viewAttr = 3, detailtype = 1 } = payload;
  return (
    <WeaFormItem label={label} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
      <WeaSelect
        options={options}
        viewAttr={viewAttr}
        detailtype={detailtype}
        value={value}
        onChange={(selected, showName) => onChange({ type: label, selected, showName })}
        style={{ width: "60%" }}
      />
    </WeaFormItem>
  );
};

export const convertData = (dataSource) => {
  let endList = [];
  _.values(_.groupBy(dataSource, "insuranceName")).forEach((itemList) => {
    let data = {};
    itemList.forEach(d => {
      const perKey = `${d.insuranceId}_per`, comKey = `${d.insuranceId}_com`;
      data = _.assign(data, {
        ...d,
        [perKey]: "",
        [comKey]: "",
        perDisabled: !_.includes(_.map(itemList, o => o.paymentScopeSign), "per"),
        perValidNum: !_.isEmpty(_.filter(itemList, i => i.paymentScopeSign === "per")) ? _.filter(itemList, i => i.paymentScopeSign === "per")[0].validNum : 2,
        comDisabled: !_.includes(_.map(itemList, o => o.paymentScopeSign), "com"),
        comValidNum: !_.isEmpty(_.filter(itemList, i => i.paymentScopeSign === "com")) ? _.filter(itemList, i => i.paymentScopeSign === "com")[0].validNum : 2,
      });
    });
    return endList.push(data);
  });
  return endList;
};
