/*
 * Author: 黎永顺
 * name: 工资单模板-薪资项目设置
 * Description:
 * Date: 2023/2/2
 */
import React, { Component } from "react";
import { toJS } from "mobx";
import { WeaFormItem, WeaInput, WeaSortable, WeaTransfer } from "ecCom";
import { Icon, Modal } from "antd";
import SalaryItemModal from "./salaryItemModal";
import { getAvailableSalaryGroupSet, getAvailableSalaryItemSet } from "../../../apis/payroll";

class SalaryItemSettings extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataList: [],
      itemShowNamesetting: [], //名称修改集合
      checkedValue: "",
      modalPayload: {
        visible: false,
        title: "",
        groupId: "",
        groupName: "",
        options: [],
        salaryItemName: "",
        salaryItemId: ""
      }
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.dataSource !== this.props.dataSource) {
      this.setState({
        dataList: _.map(toJS(nextProps.dataSource), item => {
          return {
            ...item,
            id: item.groupId
          };
        })
      });
    }
  }

  /*
   * Author: 黎永顺
   * Description:删除薪资项目大类
   * Params:
   * Date: 2023/2/2
   */
  handleDeleteClick = (group) => {
    Modal.confirm({
      title: "信息确认",
      content: "确认删除",
      onOk: () => {
        let resultSalaryItemSet = [...this.state.dataList];
        resultSalaryItemSet.map((sourceGroup, index) => {
          if (sourceGroup.groupId === group.groupId) {
            resultSalaryItemSet.splice(index, 1);
          }
        });
        this.setState({
          dataList: resultSalaryItemSet
        }, () => {
          this.props.onChangeSalaryItem(resultSalaryItemSet);
        });
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description: 删除薪资项目项
   * Params:
   * Date: 2023/2/2
   */
  handleDeleteSalaryItem = (group, item) => {
    let resultSalaryItemSet = [...this.state.dataList];
    resultSalaryItemSet.map(sourceGroup => {
      if (sourceGroup.groupId === group.groupId) {
        sourceGroup.items.map((sourceItem, index) => {
          if (sourceItem.id === item.id) {
            sourceGroup.items.splice(index, 1);
          }
        });
      }
    });
    this.setState({
      dataList: resultSalaryItemSet,
      itemShowNamesetting: _.filter(this.state.itemShowNamesetting, it => it.salaryItemId !== item.id)
    }, () => {
      this.props.onChangeSalaryItem(resultSalaryItemSet);
      this.props.onChangeSalaryItemShowNamesetting(this.state.itemShowNamesetting);
    });
  };
  handleCloseModal = () => {
    const { modalPayload } = this.state;
    this.setState({
      checkedValue: "",
      modalPayload: {
        ...modalPayload,
        visible: false,
        title: "",
        groupId: "",
        groupName: "",
        options: [],
        salaryItemName: "",
        salaryItemId: ""
      }
    });
  };
  handleOpenModal = (record, title, isItem) => {
    if (title === "分类名称编辑") {
      const { modalPayload } = this.state;
      this.setState({
        modalPayload: {
          ...modalPayload,
          visible: true,
          title,
          groupId: record.groupId,
          groupName: record.groupName
        }
      });
    } else {
      isItem ? this.getAvailableSalaryItemSet(record, title) : this.getAvailableSalaryGroupSet(record, title);
    }
  };
  getAvailableSalaryItemSet = (record, title) => {
    const payload = {
      salaryTemplateId: this.props.salaryTemplateId,
      salarySobId: this.props.salarySobId,
      existSalaryItemIds: _.map(record.items, it => it.id),
      groupId: record.groupId,
      groupName: record.groupName,
      isReplenish: this.props.isReplenish
    };
    getAvailableSalaryItemSet(payload).then(({ status, data }) => {
      if (status) {
        const { modalPayload } = this.state;
        this.setState({
          modalPayload: {
            ...modalPayload,
            visible: true,
            title,
            groupId: record.groupId,
            options: _.map(data, it => ({ ...it, name: it.name, id: it.salaryItemId }))
          }
        });
      }
    });
  };
  getAvailableSalaryGroupSet = (salarySobId, title) => {
    const { dataList } = this.state;
    const payload = {
      salarySobId,
      salaryTemplateId: this.props.salaryTemplateId,
      existSalaryGroupIds: _.map(dataList, it => it.groupId),
      isReplenish: this.props.isReplenish
    };
    getAvailableSalaryGroupSet(payload).then(({ status, data }) => {
      if (status) {
        const { modalPayload } = this.state;
        this.setState({
          modalPayload: {
            ...modalPayload,
            visible: true,
            title,
            options: _.map(data, it => ({ ...it, name: it.groupName, id: it.groupId }))
          }
        });
      }
    });
  };
  handleChangeClassName = (groupName) => {
    const { modalPayload } = this.state;
    this.setState({
      modalPayload: {
        ...modalPayload,
        groupName
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description:添加薪资项目项
   * Params:
   * Date: 2023/2/2
   */
  handleConfirm = () => {
    const { modalPayload, checkedValue, dataList } = this.state;
    const { options = [], groupId, groupName } = modalPayload;
    if (groupName) {
      this.setState({
        dataList: _.map(dataList, it => {
          if (it.groupId === groupId) {
            return {
              ...it,
              groupName
            };
          }
          return { ...it };
        })
      }, () => {
        this.props.onChangeSalaryItem(this.state.dataList);
        this.handleCloseModal();
      });
    } else {
      this.setState({
        dataList: groupId ? _.map(dataList, it => {
          if (it.groupId === groupId) {
            return {
              ...it,
              items: [...it.items, ..._.filter(options, child => checkedValue.split(",").includes(child.salaryItemId))]
            };
          }
          return { ...it };
        }) : [...dataList, ..._.filter(options, child => checkedValue.split(",").includes(child.groupId))]
      }, () => {
        this.props.onChangeSalaryItem(this.state.dataList);
        this.handleCloseModal();
      });
    }
  };
  handleEditSalaryItemName = (item, field, viewAttr) => {
    const { groupId } = item, { salaryItemId } = field, { dataList } = this.state;
    if (groupId === "111111111111111111") return;
    this.setState({
      dataList: _.map(dataList, item => {
        if (item.groupId === groupId) {
          return {
            ...item,
            items: _.map(item.items, child => {
              if (child.salaryItemId === salaryItemId) {
                return {
                  ...child,
                  viewAttr
                };
              }
              return { ...child, viewAttr: 1 };
            })
          };
        }
        return {
          ...item,
          items: _.map(item.items, child => {
            return { ...child, viewAttr: 1 };
          })
        };
      })
    }, () => document.getElementById("salaryItemInput") && document.getElementById("salaryItemInput").focus());
  };
  handleChangeSalaryItemShowName = (item, field, name) => {
    const { groupId } = item, { salaryItemId, originName } = field, { dataList, itemShowNamesetting } = this.state;
    this.setState({
      dataList: _.map(dataList, item => {
        if (item.groupId === groupId) {
          return {
            ...item,
            items: _.map(item.items, child => {
              if (child.salaryItemId === salaryItemId) {
                return { ...child, salaryItemShowName: name, name: name ? name : child.originName };
              }
              return { ...child };
            })
          };
        }
        return { ...item };
      }),
      itemShowNamesetting: _.unionBy([{
        salaryItemId,
        salaryItemShowName: originName === name ? "" : name
      }], itemShowNamesetting, "salaryItemId")
    }, () => {
      const modifySalaryItemids = _.reduce(this.state.itemShowNamesetting, (pre, cur) => [...pre, cur.salaryItemId], []);
      const convertDataList = _.map(this.state.dataList, it => {
        if (it.groupId === "111111111111111111") return { ...it };
        return {
          ...it,
          items: _.map(it.items, item => {
            if (modifySalaryItemids.includes(item.salaryItemId)) return { ...item };
            return { ...item, name: item.salaryItemShowName };
          })
        };
      });
      this.props.onChangeSalaryItem(convertDataList);
      this.props.onChangeSalaryItemShowNamesetting(this.state.itemShowNamesetting);
    });
  };

  render() {
    const { onChangeSalaryItem, salaryBillItemNameSet } = this.props;
    const { dataList, modalPayload, checkedValue } = this.state;
    if (_.isEmpty(dataList)) return null;
    return (
      <div className="salaryItemSettingWrapper">
        <WeaSortable
          datas={dataList}
          onChange={(list) => onChangeSalaryItem(list)}
          renderNodeItem={(item) => {
            return <div className="salaryItemWrapper">
              <div className="salaryItemHeader">
                <span className="titleWrapper">
                  <span className="salaryClassTitle">{item.groupName}</span>
                  <span className="iconWrapper">
                    <i className="icon-coms-edit" onClick={() => this.handleOpenModal(item, "分类名称编辑")}/>
                    <i className="icon-coms-Delete" onClick={() => this.handleDeleteClick(item)}/>
                  </span>
                </span>
                <i className="icon-coms-Add-to" onClick={() => this.handleOpenModal(item, "请选择薪资项目", true)}/>
              </div>
              <div className="salaryItemContent">
                {
                  !_.isEmpty(item.items) ?
                    <WeaSortable
                      datas={item.items}
                      onChange={(items) => onChangeSalaryItem(
                        _.map(dataList, child => {
                          if (child.id === item.id) {
                            return { ...child, items };
                          }
                          return { ...child };
                        })
                      )}
                      renderNodeItem={(filed) => {
                        const salaryBillItemNameObj = salaryBillItemNameSet[filed.id] || {};
                        return <div className="salaryItemList">
                          <div className="salaryItem"
                               title={
                                 (item.groupId !== "111111111111111111" && (!_.isEmpty(salaryBillItemNameObj) || (filed.salaryItemShowName !== filed.originName))) ?
                                   `${filed.salaryItemShowName}(${filed.originName})` :
                                   filed.name
                               }
                          >
                            {
                              filed.viewAttr === 2 ?
                                <WeaInput
                                  value={
                                    item.groupId !== "111111111111111111" ?
                                      filed.salaryItemShowName :
                                      filed.name
                                  }
                                  id="salaryItemInput"
                                  onBlur={() => this.handleEditSalaryItemName(item, filed, 1)}
                                  onChange={(val) => this.handleChangeSalaryItemShowName(item, filed, val)}
                                /> :
                                <div className="salaryItemName"
                                     onClick={() => this.handleEditSalaryItemName(item, filed, 2)}>
                                  {
                                    (item.groupId !== "111111111111111111" && (!_.isEmpty(salaryBillItemNameObj) || (filed.salaryItemShowName !== filed.originName))) ?
                                      `${filed.salaryItemShowName}(${filed.originName})` :
                                      filed.name
                                  }
                                </div>
                            }
                            <Icon type="cross" onClick={() => this.handleDeleteSalaryItem(item, filed)}/>
                          </div>
                        </div>;
                      }}
                      className="wea-sortable-salary-item"
                    /> :
                    <div className="empty">暂无数据</div>
                }
              </div>
            </div>;
          }}
          className="wea-sortable-salary-item"
        />
        <SalaryItemModal {...modalPayload} onCancel={this.handleCloseModal} onConfirm={this.handleConfirm}>
          <div className="modalContent">
            {
              modalPayload.title === "分类名称编辑" ?
                <WeaFormItem label="分类名称" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
                  <WeaInput value={modalPayload.groupName} onChange={this.handleChangeClassName}/>
                </WeaFormItem>
                : <WeaTransfer
                  data={modalPayload.options}
                  selectedKeys={checkedValue ? checkedValue.split(",") : []}
                  onChange={v => this.setState({ checkedValue: v.join(",") })}
                />
            }
          </div>
        </SalaryItemModal>
      </div>
    );
  }
}

export default SalaryItemSettings;
