/*
 * Author: 黎永顺
 * name:退差编辑页面
 * Description:
 * Date: 2022/11/23
 */
import React, { Component } from "react";
import { WeaInputNumber, WeaLocaleProvider, WeaSearchGroup, WeaSlideModal, WeaTable } from "ecCom";
import { message } from "antd";
import * as API from "../../../../apis/standingBook";
import SlideModalTitle from "../../../../components/slideModalTitle";
import { regColumns } from "../constant";
import { toDecimal_n } from "../../../../util";

const getLabel = WeaLocaleProvider.getLabel;

class RegEditDetial extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      listMap: [
        {
          key: "social",
          label: "社保",
          dataSource: [],
          columns: []
        },
        {
          key: "fund",
          label: "公积金",
          dataSource: [],
          columns: []
        },
        {
          key: "other",
          label: "企业年金及其他福利",
          dataSource: [],
          columns: []
        }
      ]
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.editId !== this.props.editId && nextProps.editId) {
      this.getPaymentById(nextProps.editId);
    }
  }

  handleSave = () => {
    const { editId, onCancel } = this.props;
    const { listMap } = this.state;
    const [socialData, foundData, otherData] = listMap;
    let payload = {
      id: editId,
      socialPerJson: {},
      socialComJson: {},
      fundPerJson: {},
      fundComJson: {},
      otherPerJson: {},
      otherComJson: {}
    };
    _.forEach(socialData.dataSource, item => {
      if (item.personalPaymentAmount) {
        payload["socialPerJson"][item["insuranceId"]] = toDecimal_n(item.personalPaymentAmount, item.personalPaymentAmountValidNum || 2);
      }
      if (item.companyPaymentAmount) {
        payload["socialComJson"][item["insuranceId"]] = toDecimal_n(item.companyPaymentAmount, item.companyPaymentAmountValidNum || 2);
      }
    });
    _.forEach(foundData.dataSource, item => {
      if (item.personalPaymentAmount) {
        payload["fundPerJson"][item["insuranceId"]] = toDecimal_n(item.personalPaymentAmount, item.personalPaymentAmountValidNum || 2);
      }
      if (item.companyPaymentAmount) {
        payload["fundComJson"][item["insuranceId"]] = toDecimal_n(item.companyPaymentAmount, item.companyPaymentAmountValidNum || 2);
      }
    });
    _.forEach(otherData.dataSource, item => {
      if (item.personalPaymentAmount) {
        payload["otherPerJson"][item["insuranceId"]] = toDecimal_n(item.personalPaymentAmount, item.personalPaymentAmountValidNum || 2);
      }
      if (item.companyPaymentAmount) {
        payload["otherComJson"][item["insuranceId"]] = toDecimal_n(item.companyPaymentAmount, item.companyPaymentAmountValidNum || 2);
      }
    });
    _.forEach(Object.keys(payload), item => {
      payload[item] = JSON.stringify(payload[item]);
    });
    this.setState({ loading: true });
    API.editAccount(payload).then(({ status, errormsg }) => {
      this.setState({ loading: false });
      if (status) {
        message.success("保存成功");
        onCancel(true);
      } else {
        message.error(errormsg || "保存成功");
      }
    });
  };
  handleChange = (type, dataIndex, value, record) => {
    const { listMap } = this.state;
    const [socialData, foundData, otherData] = listMap;
    switch (type) {
      case "social":
        const sociallist = _.map(socialData.dataSource, item => {
          if (item.insuranceId === record.insuranceId) {
            return { ...item, [dataIndex]: !_.isNil(value) ? String(value) : "0" };
          }
          return { ...item };
        });
        this.setState({
          listMap: [{ ...socialData, dataSource: sociallist }, { ...foundData }, { ...otherData }]
        });
        break;
      case "fund":
        const fundlist = _.map(foundData.dataSource, item => {
          if (item.insuranceId === record.insuranceId) {
            return { ...item, [dataIndex]: !_.isNil(value) ? String(value) : "0" };
          }
          return { ...item };
        });
        this.setState({
          listMap: [{ ...socialData }, { ...foundData, dataSource: fundlist }, { ...otherData }]
        });
        break;
      case "other":
        const otherlist = _.map(otherData.dataSource, item => {
          if (item.insuranceId === record.insuranceId) {
            return { ...item, [dataIndex]: !_.isNil(value) ? String(value) : "0" };
          }
          return { ...item };
        });
        this.setState({
          listMap: [{ ...socialData }, { ...foundData }, { ...otherData, dataSource: otherlist }]
        });
        break;
      default:
        break;
    }

  };
  getPaymentById = (id) => {
    const payload = { id };
    const { listMap } = this.state;
    const [socialData, foundData, otherData] = listMap;
    API.getPaymentById(payload).then(({ status, data }) => {
      if (status) {
        let socialSecurity = [], accumulationFund = [], otherBenefits = [];
        const { data: result } = data;
        _.map(result, it => {
          if (it.titleSign === "social") {
            socialSecurity.push(it);
          }
          if (it.titleSign === "fund") {
            accumulationFund.push(it);
          }
          if (it.titleSign === "other") {
            otherBenefits.push(it);
          }
        });
        const social = this.combinedData(socialSecurity, result);
        const fund = this.combinedData(accumulationFund, result);
        const other = this.combinedData(otherBenefits, result);
        this.setState({
          listMap: [
            {
              ...socialData, dataSource: social, columns: _.map(regColumns, item => {
                if (item.dataIndex === "personalPaymentAmount" || item.dataIndex === "companyPaymentAmount") {
                  return {
                    ...item,
                    render: (text, record) => {
                      return (
                        <WeaInputNumber
                          disabled={_.isNil(text)}
                          precision={parseFloat(record[`${item.dataIndex}ValidNum`] || 2)}
                          value={text}
                          onChange={v => this.handleChange("social", item.dataIndex, v, record)}
                        />
                      );
                    }
                  };
                }
                return { ...item };
              })
            },
            {
              ...foundData, dataSource: fund, columns: _.map(regColumns, item => {
                if (item.dataIndex === "personalPaymentAmount" || item.dataIndex === "companyPaymentAmount") {
                  return {
                    ...item,
                    render: (text, record) => {
                      return (
                        <WeaInputNumber
                          disabled={_.isNil(text)}
                          precision={parseFloat(record[`${item.dataIndex}ValidNum`] || 2)}
                          value={text}
                          onChange={v => this.handleChange("fund", item.dataIndex, v, record)}
                        />
                      );
                    }
                  };
                }
                return { ...item };
              })
            },
            {
              ...otherData, dataSource: other, columns: _.map(regColumns, item => {
                if (item.dataIndex === "personalPaymentAmount" || item.dataIndex === "companyPaymentAmount") {
                  return {
                    ...item,
                    render: (text, record) => {
                      return (
                        <WeaInputNumber
                          disabled={_.isNil(text)}
                          precision={parseFloat(record[`${item.dataIndex}ValidNum`] || 2)}
                          value={text}
                          onChange={v => this.handleChange("other", item.dataIndex, v, record)}
                        />
                      );
                    }
                  };
                }
                return { ...item };
              })
            }
          ]
        });
      }
    });
  };
  combinedData = (data = []) => {
    const fieldItems = _.map(data, item => item.insuranceName);
    let result = [];
    result = _.map(_.uniqWith(fieldItems, _.isEqual), item => {
      let obj = { benefits: item };
      _.forEach(data, it => {
        if (item === it.insuranceName && it.paymentScopeSign === "per") {
          obj = _.assign(obj, {
            ...it, personalPaymentAmount: it.insuranceValue,
            personalPaymentAmountValidNum: it.validNum
          });
        } else if (item === it.insuranceName && it.paymentScopeSign === "com") {
          obj = _.assign(obj, {
            ...it, companyPaymentAmount: it.insuranceValue,
            companyPaymentAmountValidNum: it.validNum
          });
        }
      });
      return obj;
    });
    return result;
  };

  render() {
    const { visible, title, onCancel } = this.props;
    const { listMap, loading } = this.state;
    return (
      <WeaSlideModal
        className="slideOuterWrapper"
        visible={visible}
        top={0}
        width={48}
        height={100}
        direction="right"
        measure="%"
        title={
          <SlideModalTitle
            loading={loading}
            subtitle={title}
            showOperateBtn={true}
            editable={true}
            onSave={this.handleSave}
          />
        }
        content={
          <div className="regEditContentWrapper">
            {
              _.map(listMap, item => {
                const { key, label, dataSource, columns } = item;
                return <WeaSearchGroup title={label} items={[]} needTigger showGroup key={key}>
                  <WeaTable dataSource={dataSource} columns={columns} pagination={false}/>
                </WeaSearchGroup>;
              })
            }
          </div>
        }
        onClose={() => onCancel()}
        showMask={true}
      />
    );
  }
}

export default RegEditDetial;
