/*
 * Author: 黎永顺
 * name: 调差列表
 * Description:
 * Date: 2022/12/5
 */
import React, { Component } from "react";
import { WeaHelpfulTip, WeaInputNumber, WeaSelect, WeaTableEdit } from "ecCom";
import { message, Modal } from "antd";
import {
  compensationBack,
  compensationCategoryType,
  compensationSave,
  getCompensationComTotal,
  getCompensationList,
  getEmployeeListToCompensation
} from "../../../../apis/standingBook";
import { getQueryString } from "../../../../util/url";
import "./index.less";

class AdjustTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: {
        query: false
      },
      dataSource: [],
      columns: [],
      selectedRowKeys: [],
      targetOptions: []
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible) {
      nextProps.visible && this.getCompensationList().then(r => {
      });
    }
  }

  getCompensationList = async () => {
    const { pageInfo, loading } = this.state;
    const billMonth = getQueryString("billMonth");
    const paymentOrganization = getQueryString("paymentOrganization");
    const [adjustmentObjEnum] = await Promise.all([this.getEmployeeListToCompensation()]);
    const { status, data: list } = adjustmentObjEnum;
    this.setState({ targetOptions: list });
    const targetOptions = status ? _.map(list, it => ({
      key: it.employeeId.toString(),
      showname: it.username
    })) : [];
    const payload = {
      paymentOrganization,
      billMonth,
      ...pageInfo
    };
    this.setState({ loading: { ...loading, query: true } });
    getCompensationList(payload).then(({ status, data }) => {
      this.setState({ loading: { ...loading, query: false } });
      if (status) {
        const { columns, data: dataSource } = data;
        this.setState({
          dataSource: _.map(dataSource, it => {
            return {
              ...it,
              welfareType: it.welfareType.toString(),
              target: it.employeeId.toString(),
              adjustTo: it.adjustTo.toString(),
              adjustToOptions: _.map(it.categoryTypeOptions, child => ({ key: child.id, showname: child.content })),
              categoryTypeOptions: _.map(it.categoryTypeOptions, child => ({ key: child.id, showname: child.content })),
              targetOptions: _.map([it.targetOptions], child => ({ key: child.id, showname: child.name }))
            };
          }),
          columns: _.map(columns, item => {
            const { dataIndex } = item;
            switch (dataIndex) {
              case "target":
                item.com = [
                  {
                    type: "custom",
                    key: "target",
                    width: 220,
                    render: (text, record, index, onEdit) => {
                      return (
                        <WeaSelect
                          showSearch
                          optionFilterProp="children"
                          options={targetOptions}
                          value={record.target}
                          style={{ width: "100%" }}
                          viewAttr={record.status ? 1 : 3}
                          onChange={v => this.handleChangeTableItem("target", v, index)}
                        />
                      );
                    }
                  }
                ];
                break;
              case "welfareType":
                item.com = [
                  {
                    width: 220,
                    type: "custom",
                    key: "welfareType",
                    render: (text, record, index, onEdit) => (
                      <WeaSelect
                        options={[{ key: "1", showname: "社保" }]}
                        value={record.welfareType}
                        viewAttr={record.status ? 1 : 3}
                        onChange={v => this.handleChangeTableItem("welfareType", v, index)}
                      />
                    )
                  }
                ];
                break;
              case "categoryType":
                item.com = [
                  {
                    width: 220,
                    type: "custom",
                    key: "categoryType",
                    render: (text, record, index, onEdit) => (
                      <WeaSelect
                        multiple
                        options={record.categoryTypeOptions || []}
                        value={record.categoryType}
                        viewAttr={record.status ? 1 : 3}
                        onChange={v => this.handleChangeTableItem("categoryType", v, index)}
                      />
                    )
                  }
                ];
                break;
              case "countryTotal":
                item.com = [
                  {
                    width: 220,
                    type: "custom",
                    key: "countryTotal",
                    render: (text, record, index, onEdit) => (
                      <WeaInputNumber
                        precision={2}
                        value={record.countryTotal}
                        viewAttr={record.status ? 1 : 3}
                        onChange={v => this.handleChangeTableItem("countryTotal", v, index)}
                      />
                    )
                  }
                ];
                break;
              case "companyTotal":
                item.com = [
                  {
                    width: 220,
                    type: "custom",
                    key: "companyTotal",
                    render: (text, record, index, onEdit) => (
                      <WeaInputNumber
                        precision={2}
                        disabled
                        value={record.companyTotal}
                        onChange={v => this.handleChangeTableItem("companyTotal", v, index)}
                      />
                    )
                  }
                ];
                break;
              case "adjustmentTotal":
                item.title = <span>
                  <span>{item.title}</span>
                  <WeaHelpfulTip
                    width={200}
                    title="国家核算金额(单位) - 公司核算金额(单位)"
                    placement="topLeft"
                  />
                </span>;
                item.com = [
                  {
                    width: 220,
                    type: "custom",
                    key: "adjustmentTotal",
                    render: (text, record, index, onEdit) => (
                      <WeaInputNumber
                        precision={2}
                        disabled
                        value={record.adjustmentTotal}
                        onChange={v => this.handleChangeTableItem("adjustmentTotal", v, index)}
                      />
                    )
                  }
                ];
                break;
              case "adjustTo":
                item.com = [
                  {
                    width: 220,
                    type: "custom",
                    key: "adjustTo",
                    render: (text, record, index, onEdit) => {
                      return (
                        <WeaSelect
                          options={record.adjustToOptions || []}
                          value={record.adjustTo}
                          viewAttr={record.status ? 1 : 3}
                          onChange={v => this.handleChangeTableItem("adjustTo", v, index)}
                        />
                      );
                    }
                  }
                ];
                break;
              default:
                break;
            }
            return { ...item, display: true, width: "20%" };
          })
        });
      }
    }).catch(() => {
      this.setState({ loading: { ...loading, query: false } });
    });
  };
  compensationCategoryType = (id, index) => {
    const { dataSource } = this.state;
    compensationCategoryType({ id }).then(({ status, data }) => {
      if (status) {
        this.setState({
          dataSource: _.map(dataSource, (item, idx) => {
            if (index === idx) {
              return {
                ...item,
                adjustTo: "",
                adjustToOptions: [],
                categoryType: "",
                categoryTypeOptions: _.map(data, child => ({ key: child.id, showname: child.content }))
              };
            } else {
              return { ...item };
            }
          })
        });
      }
    });
  };
  getEmployeeListToCompensation = () => {
    const billMonth = getQueryString("billMonth");
    const paymentOrganization = getQueryString("paymentOrganization");
    const payload = {
      billMonth, paymentOrganization,
      pageNum: 1, pageSize: 100
    };
    return getEmployeeListToCompensation(payload);
  };
  getCompensationComTotal = (payload, index, categoryType) => {
    const { dataSource } = this.state;
    getCompensationComTotal(payload).then(({ status, data }) => {
        if (status && !_.isEmpty(data)) {
          this.setState({
            dataSource: _.map(dataSource, (item, idx) => {
              if (index === idx) {
                return {
                  ...item, adjustTo: "",
                  companyTotal: data[0].totalNum,
                  adjustToOptions: categoryType ? _.map(categoryType.split(","), tmpV => {
                    return _.find(item.categoryTypeOptions, tmpJ => tmpJ.key === tmpV);
                  }) : []
                };
              } else {
                return { ...item };
              }
            })
          });
        }
      }
    );
  };
  handleChangeCom = (dataSource) => {
    this.setState({
      dataSource: _.map(dataSource, (item, index) => {
        return {
          ...item,
          uuid: new Date().getTime() + index
        };
      })
    });
  };
  handleChangeTableItem = (filedItemkey, value, index) => {
    const { dataSource, targetOptions } = this.state;
    this.setState({
      dataSource: _.map(dataSource, (item, idx) => {
        if (index === idx) {
          return { ...item, [filedItemkey]: value };
        } else {
          return { ...item };
        }
      })
    }, () => {
      const paymentOrganization = getQueryString("paymentOrganization");
      if (filedItemkey === "target") {
        this.compensationCategoryType(_.find(targetOptions, it => it.employeeId == value).target, index);
      } else if (filedItemkey === "categoryType") {
        _.map(this.state.dataSource, (it, itdx) => {
          const bool = it.target && it.categoryType;
          if (bool && itdx === index) {
            const payload = {
              paymentOrganization,
              target: _.find(targetOptions, child => child.employeeId == it.target).target,
              employeeId: it.target,
              categoryType: it.categoryType
            };
            this.getCompensationComTotal([payload], itdx, it.categoryType);
          }
        });
      } else if (filedItemkey === "countryTotal") {
        this.setState({
          dataSource: _.map(this.state.dataSource, (child, childidx) => {
            if (index === childidx) {
              return {
                ...child,
                adjustmentTotal: (Number(!_.isNil(child.countryTotal) ? child.countryTotal : 0) - Number(child.companyTotal)).toFixed(2)
              };
            } else {
              return { ...child };
            }
          })
        });
      }
    });
  };

  handleClick = (record) => {
    const { status, id, paymentOrganization, billMonth, employeeId, target } = record;
    const { targetOptions } = this.state;
    if (status) {
      Modal.confirm({
        title: "信息确认",
        content: "确定撤回吗？撤回后该笔调差将失效！",
        onOk: () => {
          const payload = { id, paymentOrganization, billMonth };
          compensationBack(payload).then(async ({ status, data, errormsg }) => {
            const { data: categoryTypeOptions } = await compensationCategoryType({ id: _.find(targetOptions, child => (child.employeeId == employeeId || child.employeeId == target)).target });
            if (status) {
              message.success(data || "撤回成功");
              this.setState({
                dataSource: _.map(this.state.dataSource, (it, idx) => {
                  if (id === it.id) {
                    return {
                      ...it,
                      status: false,
                      uuid: new Date().getTime() + idx,
                      categoryTypeOptions: _.map(categoryTypeOptions, child => ({
                        key: child.id,
                        showname: child.content
                      }))
                    };
                  }
                  return { ...it, uuid: new Date().getTime() + idx };
                })
              });
            } else {
              message.error(errormsg || "撤回失败");
            }
          });
        },
        onCancel: () => {
        }
      });
    } else {
      Modal.confirm({
        title: "信息确认",
        content: "确定保存吗？保存后数据将即时更新到台账！",
        onOk: () => {
          const {
            adjustToOptions, categoryTypeOptions, key, target, status,
            originId, targetOptions: targetOption, billMonth,
            ...extraParams
          } = record;
          const month = getQueryString("billMonth");
          const paymentOrg = getQueryString("paymentOrganization");
          const tmpObj = { ...extraParams, target };
          for (let i in tmpObj) {
            if (tmpObj[i]) {
              Object.assign(tmpObj, { [i]: tmpObj[i].toString() });
            }
          }
          const bool = _.every(Object.keys({ ...extraParams, target }), child => {
            return !!tmpObj[child];
          });
          if (!bool) {
            Modal.warning({
              title: "信息确认",
              content: "必要信息不完整，红色*为必填项！"
            });
            return;
          }
          const payload = {
            ...extraParams,
            employeeId: target,
            target: _.find(targetOptions, child => child.employeeId == target).target,
            billMonth: month,
            paymentOrganization: paymentOrg
          };
          compensationSave([payload]).then(({ status, data, errormsg }) => {
            if (status) {
              const { data: dataMsg, errorMessage = [], successIds = [] } = data;
              const msg = dataMsg + errorMessage.join(",");
              !_.isEmpty(errorMessage) ? message.error(msg) : message.success(msg || "保存成功");
              if (_.isEmpty(errorMessage)) {
                this.setState({
                  dataSource: _.map(this.state.dataSource, it => {
                    if (record.id === it.id || (!it.id && record.uuid === it.uuid)) {
                      return {
                        ...it, status: true, id: successIds[0],
                        targetOptions: _.map([_.find(targetOptions, o => o.employeeId == target)], v => ({
                          key: v.target.toString(),
                          showname: v.username
                        }))
                      };
                    }
                    return { ...it };
                  })
                });
              }
            } else {
              message.error(errormsg || "保存失败");
            }
          });
        },
        onCancel: () => {
        }
      });
    }
  };
  getRowSelection = (rowSelection) => {
    let sel = { ...rowSelection };
    sel.getCheckboxProps = (record) => {
      return { disabled: record.status };
    };
    return sel;
  };

  render() {
    const { dataSource, columns, selectedRowKeys } = this.state;

    return (
      <WeaTableEdit
        deleteConfirm
        showCopy={false}
        columns={
          [
            ...columns,
            {
              dataIndex: "operate",
              title: "操作",
              key: "operate",
              width: 80,
              render: (text, record) => {
                const { status } = record;
                return <a href="javascript: void(0);"
                          onClick={() => this.handleClick(record)}>{status ? "撤回" : "保存"}</a>;
              }
            }
          ]
        }
        datas={dataSource}
        onChange={this.handleChangeCom}
        selectedRowKeys={selectedRowKeys}
        getRowSelection={this.getRowSelection}
        tableProps={{ x: 800 }}
      />
    );
  }
}

export default AdjustTable;
