/*
 * Author: 黎永顺
 * name: 薪资项目-列表数据
 * Description:
 * Date: 2022/12/13
 */
import React, { Component } from "react";
import { WeaCheckbox, WeaHelpfulTip, WeaLocaleProvider, WeaTable } from "ecCom";
import LedgerSalaryItemEditSlide from "./ledgerSalaryItemEditSlide";
import { getSalaryItemForm } from "../../../apis/ledger";
import { commonEnumList } from "../../../apis/ruleconfig";
import FormalFormModal from "../../salaryItem/formalFormModal";
import { toDecimal_n } from "../../../util";

const getLabel = WeaLocaleProvider.getLabel;

class LedgerSalaryItemTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [],
      originRecord: {},
      salaryItemPayload: {
        visible: false, record: {},
        request: {}, isLedger: true,
        userStatusList: [], loading: false
      },
      editFormulModal: {
        visible: false,
        formulaId: "",
        valueType: "",
        dataType: "",
        name: ""
      }
    };
  }

  /*
   * Author: 黎永顺
   * Description: 列表操作隐藏复选框
   * Params:
   * Date: 2022/12/14
   */
  handleChangeItem = (value, id) => {
    const { dataSource, onHandleItemhide } = this.props;
    onHandleItemhide(
      _.map([...dataSource], item => {
        if (id === item.id || id === item.key) {
          return {
            ...item,
            itemHide: String(value)
          };
        }
        return { ...item };
      })
    );
  };
  handleChangeAllItem = (value) => {
    const { dataSource, onHandleItemhide } = this.props;
    onHandleItemhide(
      _.map([...dataSource], item => {
        return {
          ...item,
          itemHide: String(value)
        };
      })
    );
  };
  handleChangeSalaryItem = (data, id) => {
    const { dataSource, onHandleItemhide } = this.props;
    onHandleItemhide(
      _.map([...dataSource], item => {
        if (id === item.salaryItemId) {
          return {
            ...item,
            ...data
          };
        }
        return { ...item };
      })
    );
  };
  /*
   * Author: 黎永顺
   * Description: 编辑薪资项目
   * Params:
   * Date: 2023/7/19
   */
  handleEditSalaryItem = async (record) => {
    const { salarySobId, dataSource } = this.props, { salaryItemId, id } = record;
    const {
      itemHide: hideDefault, defaultValue,
      valueType, name, description,
      roundingMode, formulaId, dataType, useInEmployeeSalary,
      pattern, canEdit, formulaContent, originFormulaContent, originSqlContent
    } = _.find(dataSource, it => it.salaryItemId === salaryItemId);
    const { data: userStatusList } = await commonEnumList({ enumClass: "com.engine.salary.enums.sicategory.SharedTypeEnum" });
    if (id) {
      getSalaryItemForm({ salarySobId, salaryItemId }).then(({ status, data }) => {
        if (status) {
          this.setState({
            originRecord: _.find(dataSource, it => it.salaryItemId === salaryItemId),
            salaryItemPayload: {
              ...this.state.salaryItemPayload,
              visible: true,
              request: {
                ...data,
                useInEmployeeSalary: !_.isNil(data.useInEmployeeSalary) ? data.useInEmployeeSalary : "0",
                hideDefault: _.isNil(hideDefault) ? "0" : hideDefault, valueType, roundingMode, pattern,
                formulaContent: formulaContent ? formulaContent : data.formulaContent,
                originFormulaContent: originFormulaContent ? originFormulaContent : data.originFormulaContent,
                originSqlContent: originSqlContent ? originSqlContent : data.originSqlContent,
                formulaId: formulaId ? formulaId : data.formulaId
              },
              record,
              userStatusList: _.map(userStatusList, it => ({ key: it.value.toString(), showname: it.defaultLabel }))
            }
          });
        }
      });
    } else {
      this.setState({
        salaryItemPayload: {
          ...this.state.salaryItemPayload,
          visible: true,
          request: {
            canEdit, dataType, description, defaultValue,
            formulaContent, formulaId, name,
            hideDefault: _.isNil(hideDefault) ? "0" : hideDefault,
            valueType, roundingMode, pattern,
            useInEmployeeSalary: !_.isNil(useInEmployeeSalary) ? useInEmployeeSalary : "0",
            //不能改成其他空值
            originFormulaContent: _.isNil(originFormulaContent) ? formulaContent : originFormulaContent,
            originSqlContent: _.isNil(originSqlContent) ? formulaContent : originSqlContent
          },
          record,
          userStatusList: _.map(userStatusList, it => ({ key: it.value.toString(), showname: it.defaultLabel }))
        },
        originRecord: _.find(dataSource, it => it.salaryItemId === salaryItemId)
      });
    }
  };
  /*
   * Author: 黎永顺
   * Description: 保存薪资项目
   * Params:
   * Date: 2023/7/19
   */
  handleSaveItem = () => {
    const { salaryItemPayload } = this.state;
    const { request, record } = salaryItemPayload;
    this.setState({
      salaryItemPayload: { ...salaryItemPayload, visible: false }
    });
    const { salaryItemId } = record;
    const {
      hideDefault, roundingMode, pattern, valueType, defaultValue,
      originFormulaContent, originSqlContent, formulaId, dataType
    } = request;
    this.handleChangeSalaryItem({
      itemHide: hideDefault.toString(),
      defaultValue: dataType === "number" ? toDecimal_n(defaultValue, parseInt(pattern)) : defaultValue,
      roundingMode, pattern, valueType,
      formulaContent: valueType.toString() === "2" ? originFormulaContent : originSqlContent,
      formulaId: ((valueType.toString() === "3" && (!originSqlContent || originSqlContent === " ")) || (valueType.toString() === "2" && (!originFormulaContent || originFormulaContent === " ")) || valueType.toString() === "1") ? "" : formulaId,
      //不能改成其他空值
      originFormulaContent: ((valueType.toString() === "3" && (!originSqlContent) || originSqlContent === " ") || (valueType.toString() === "1") || (valueType.toString() === "3" && originSqlContent)) ? " " : originFormulaContent,
      originSqlContent: ((valueType.toString() === "2" && (!originFormulaContent || originFormulaContent === " ")) || (valueType.toString() === "1") || (valueType.toString() === "2" && originFormulaContent)) ? " " : originSqlContent
    }, salaryItemId);
  };
  handleEditFormnul = (salaryItemName) => {
    const { salaryItemPayload, editFormulModal } = this.state;
    const { record } = salaryItemPayload;
    const { valueType, formulaId, dataType, originFormulaContent, originSqlContent } = record;
    this.setState({
      editFormulModal: {
        ...editFormulModal, visible: true, valueType, dataType, name: salaryItemName,
        formulaId: ((valueType.toString() === "2" && (originFormulaContent || originFormulaContent !== " ")) || valueType.toString() === "3" && (originSqlContent || originSqlContent !== " ")) ? formulaId : ""
      }
    });
  };
  handleCloseFormnul = () => {
    const { editFormulModal } = this.state;
    this.setState({
      editFormulModal: {
        ...editFormulModal,
        visible: false,
        formulaId: "", name: "",
        valueType: "", dataType: ""
      }
    });
  };
  handleSaveFormnul = (data) => {
    const { salaryItemPayload } = this.state;
    const { record } = salaryItemPayload;
    const { salaryItemId } = record;
    const { dataSource, onHandleItemhide } = this.props;
    const tmpV = _.cloneDeep(dataSource);
    const formnulData = _.map(tmpV, it => {
      if (it.salaryItemId === salaryItemId) {
        return {
          ...it,
          formulaId: data.id, formulaContent: data.formula,
          originFormulaContent: data.referenceType === "formula" ? data.formula : "",
          originSqlContent: data.referenceType === "sql" ? data.formula : ""
        };
      }
      return { ...it };
    });
    this.setState({
      salaryItemPayload: {
        ...salaryItemPayload,
        request: {
          ...salaryItemPayload.request,
          formulaId: data.id,
          originFormulaContent: data.referenceType === "formula" ? data.formula : "",
          originSqlContent: data.referenceType === "sql" ? data.formula : ""
        },
        record: {
          ...salaryItemPayload.record,
          formulaId: data.id,
          originFormulaContent: data.referenceType === "formula" ? data.formula : "",
          originSqlContent: data.referenceType === "sql" ? data.formula : ""
        }
      }
    }, () => {
      this.handleCloseFormnul();
      onHandleItemhide(formnulData);
    });
  };

  render() {
    const { salaryItemPayload, editFormulModal, originRecord } = this.state;
    const { onHandleItemhide } = this.props;
    const {
      tableData, dataSource, onDropCategoryItem,
      onChangeSelectedRowKeys, selectedRowKeys, onMoveTo
    } = this.props;
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys) => this.setState({ selectedRowKeys }, () => {
        onChangeSelectedRowKeys(this.state.selectedRowKeys);
      }),
      getCheckboxProps: record => ({
        disabled: !record.canDelete
      })
    };
    const checkValue = (!_.isEmpty(tableData) && _.every(tableData, it => it.itemHide && it.itemHide === "1")) ? "1" : "0";
    const columns = [
      {
        title: "名称",
        dataIndex: "name",
        key: "name",
        render: (text, record) => {
          const { salarySobId, salaryItemId } = record;
          return <a
            // href={`/spa/hrmSalary/static/index.html#/main/hrmSalary/topologyView/${salarySobId}/${salaryItemId}`}
            // target="_blank"
            href="javascript:void(0);">{text}</a>;
        }
      },
      {
        title: <span>
          <span style={{ marginRight: 8 }}>核算公式</span>
          <WeaHelpfulTip title={<HelpContent/>} placement="bottom" width={200}/>
        </span>,
        dataIndex: "valueType",
        key: "valueType",
        render: (e, record) => {
          const { valueType, formulaContent } = record;
          const key = !_.isNil(valueType) ? valueType : "";
          return <span> {key.toString() === "1" ? "输入" : key.toString() === "2" ? formulaContent : key.toString() === "3" ? formulaContent : ""} </span>;
        }
      },
      {
        title: "个税申请表对应字段",
        dataIndex: "taxDeclarationColumn",
        key: "taxDeclarationColumn"
      },
      {
        title: <span>
          <WeaCheckbox
            value={checkValue}
            onChange={value => this.handleChangeAllItem(value)}
          />
          <span style={{ marginLeft: 8 }}>隐藏</span>
        </span>,
        dataIndex: "itemHide",
        key: "itemHide",
        width: 80,
        render: (text, record) => <WeaCheckbox
          value={text ? String(text) : !text ? "0" : "1"}
          onChange={value => {
            this.handleChangeItem(value, record.id || record.key);
          }}
        />
      },
      {
        title: "操作",
        dataIndex: "operate",
        key: "operate",
        width: 180,
        render: (_, record) => (
          <React.Fragment>
            <a href="javascript:void(0);" onClick={() => this.handleEditSalaryItem(record)}
               style={{ marginRight: 10 }}>编辑</a>
            <a href="javascript:void(0);" onClick={() => this.props.onAddCategoryItems(record)}
               style={{ marginRight: 10 }}>{getLabel(111, "插入")}</a>
            <a href="javascript:void(0);" onClick={() => onMoveTo(record)}>移动到</a>
          </React.Fragment>
        )
      }
    ];
    return (
      <React.Fragment>
        <WeaTable
          rowKey={record => record.id || record.key}
          rowSelection={rowSelection}
          dataSource={tableData}
          columns={columns}
          onRow={(record, index) => ({
            index,
            moveRow: record
          })}
          pagination={false}
          onDrop={onDropCategoryItem}
          draggable={dataSource.length === tableData.length}
        />
        <LedgerSalaryItemEditSlide
          {...salaryItemPayload}
          onUpdateRequest={(request, key) => {
            this.setState({
              salaryItemPayload: {
                ...salaryItemPayload,
                request,
                record: key === "valueType" ? {
                  ...salaryItemPayload.record,
                  [key]: request[key]
                } : { ...salaryItemPayload.record }
              }
            });
          }}
          onEditFormnul={this.handleEditFormnul}
          onSave={this.handleSaveItem}
          onClose={() => this.setState({
            salaryItemPayload: {
              ...salaryItemPayload, visible: false
            }
          }, () => {
            const result = _.map(_.cloneDeep(dataSource), it => {
              if (it.salaryItemId === originRecord.salaryItemId) {
                return { ...originRecord };
              }
              return { ...it };
            });
            onHandleItemhide(result);
          })}
        />
        {/*公式编辑*/}
        {
          editFormulModal.visible &&
          <FormalFormModal
            {...editFormulModal}
            onSaveFormal={this.handleSaveFormnul}
            onCancel={this.handleCloseFormnul}
          />
        }
      </React.Fragment>
    );
  }
}

export default LedgerSalaryItemTable;

const HelpContent = () => {
  return <span>
    <span>1、新建薪资账套时，核算公式与【薪资项目管理】菜单一致；</span><br/>
    <span>2、取值方式为公式的薪资项目，核算公式显示为具体公式；点击公式可编辑公式，核算时，按照当前薪资项目的公式进行核算；</span><br/>
    <span>3、薪资账套内的薪资项目的公式或SQL的修改或公式的修改，都不影响【薪资项目管理】菜单的薪资项目取值方式或公式，只对当前账套生效；</span><br/>
  </span>;
};
