/*
 * Author: 黎永顺
 * name: 工资单部分发放和撤回
 * Description:
 * Date: 2022/12/2
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaBrowser, WeaDialog, WeaFormItem, WeaSearchGroup, WeaSelect } from "ecCom";
import { Button, message, Modal } from "antd";
import { commonEnumList } from "../../../apis/ruleconfig";
import { sendRangeSave } from "../../../apis/payroll";
import "./index.less";

@inject("taxAgentStore")
@observer
class PayrollPartModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      targetTypeList: [],
      personalAddItem: [
        {
          viewAttr: 3,
          key: "include",
          label: "对象",
          targetType: "1",
          targetTypeIds: "",
          targetTypeIdsNames: ""
        },
        {
          viewAttr: 2,
          key: "exclude",
          label: "对象中排除",
          targetType: "1",
          targetTypeIds: "",
          targetTypeIdsNames: ""
        }
      ]
    };
  }

  componentDidMount() {
    const { taxAgentStore } = this.props;
    const { getTaxAgentSelectListAsAdmin } = taxAgentStore;
    getTaxAgentSelectListAsAdmin();
  }

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

  orderRuleEnum = () => {
    const payload = {
      enumClass: "com.engine.salary.enums.salarysend.SalarySendRangeTargetTypeEnum"
    };
    commonEnumList(payload).then(({ status, data }) => {
      if (status) {
        this.setState({
          targetTypeList: _.map(data, item => {
            return {
              key: item.value.toString(),
              showname: item.defaultLabel
            };
          })
        });
      }
    });
  };
  taxAgentRangeSave = () => {
    const { grantType, salarySendId, onCancel } = this.props;
    const { personalAddItem } = this.state;
    let excludeObjParams = [], includeObjParams = [];
    if (
      _.find(personalAddItem, item => item.viewAttr === 3).targetType !== "0" &&
      _.isEmpty(_.find(personalAddItem, item => item.viewAttr === 3).targetTypeIds)
    ) {
      Modal.warning({
        title: "信息确认",
        content: "必要信息不完整，红色*为必填项！"
      });
      return;
    }
    _.map(personalAddItem, it => {
      const { key, targetType, targetTypeIds } = it;
      if (key === "include") {
        if (targetType === "0") {
          includeObjParams = [{ targetType, targetId: "" }];
        } else {
          if (targetTypeIds) {
            includeObjParams = _.map(targetTypeIds.split(","), child => ({
              targetType, targetId: child
            }));
          }
        }
      } else if (key === "exclude") {
        if (targetType === "0") {
          excludeObjParams = [{ targetType, targetId: "" }];
        } else {
          if (targetTypeIds) {
            excludeObjParams = _.map(targetTypeIds.split(","), child => ({
              targetType, targetId: child
            }));
          }
        }
      }
    });
    const payload = {
      grantType, salarySendId,
      excludeObjParams, includeObjParams
    };
    this.setState({ loading: true });
    sendRangeSave(payload).then(({ status, errormsg }) => {
      this.setState({ loading: false });
      if (status) {
        message.success("保存成功");
        this.handleReset();
        onCancel();
      } else {
        message.error(errormsg || "保存失败");
      }
    }).catch(() => this.setState({ loading: false }));
  };
  handleChange = (type, value) => {
    const { personalAddItem } = this.state;
    this.setState({
      personalAddItem: _.map(personalAddItem, it => {
        if (it.key === type) {
          return {
            ...it,
            targetType: value,
            targetTypeIds: ""
          };
        }
        return { ...it };
      })
    });
  };
  renderBrowser = (item) => {
    const { personalAddItem } = this.state;
    const { taxAgentStore } = this.props;
    const { targetType, targetTypeIds, targetTypeIdsNames, key, viewAttr } = item;
    let browserType = {};
    if (targetType === "5") {
      return <WeaSelect
        multiple
        viewAttr={viewAttr}
        style={{ width: 200 }}
        value={targetTypeIds}
        options={taxAgentStore.taxAgentAdminOption}
        onChange={(targetTypeIds, targetTypeIdsNames) => {
          this.setState({
            personalAddItem: _.map(personalAddItem, it => {
              if (it.key === key) {
                return {
                  ...it,
                  targetTypeIds, targetTypeIdsNames
                };
              }
              return { ...it };
            })
          });
        }}
      />;
    } else if (targetType === "0") {
      return null;
    } else {
      switch (targetType) {
        case "1":
          browserType = { ...browserType, type: 17, title: "人员选择" };
          break;
        case "2":
          browserType = { ...browserType, type: 57, title: "部门选择" };
          break;
        case "3":
          browserType = { ...browserType, type: 164, title: "分部选择" };
          break;
        case "4":
          browserType = { ...browserType, type: 278, title: "岗位选择" };
          break;
        default:
          break;
      }
      return <WeaBrowser
        {...browserType}
        viewAttr={viewAttr}
        isSingle={false}
        value={targetTypeIds}
        valueSpan={targetTypeIdsNames}
        inputStyle={{ width: 200 }}
        onChange={(targetTypeIds, targetTypeIdsNames) => {
          this.setState({
            personalAddItem: _.map(personalAddItem, it => {
              if (it.key === key) {
                return {
                  ...it,
                  targetTypeIds, targetTypeIdsNames
                };
              }
              return { ...it };
            })
          });
        }}
      />;
    }
  };
  handleReset = () => {
    this.setState({
      personalAddItem: [
        {
          viewAttr: 3,
          key: "include",
          label: "对象",
          targetType: "1",
          targetTypeIds: "",
          targetTypeIdsNames: ""
        },
        {
          viewAttr: 2,
          key: "exclude",
          label: "对象中排除",
          targetType: "1",
          targetTypeIds: "",
          targetTypeIdsNames: ""
        }
      ]
    });
  };

  render() {
    const { onCancel, visible } = this.props;
    const { targetTypeList, personalAddItem, loading } = this.state;
    const buttons = [
      <Button type="primary" onClick={this.taxAgentRangeSave} loading={loading}>确定</Button>,
      <Button type="ghost" onClick={this.handleReset}>重置</Button>
    ];
    return (
      <WeaDialog
        initLoadCss
        className="payrollPartModalWrapper"
        title="添加"
        visible={visible}
        style={{ width: 600 }}
        buttons={buttons}
        onCancel={() => {
          this.handleReset();
          onCancel();
        }}
      >
        <WeaSearchGroup col={1} needTigger title="" showGroup center>
          {
            _.map(personalAddItem, it => {
              const { targetType, key, label } = it;
              return <WeaFormItem
                key={key}
                label={label}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
              >
                <div style={{ display: "flex", alignItems: "center" }}>
                  <WeaSelect
                    style={{ width: 60, marginRight: 12 }}
                    value={targetType}
                    options={targetTypeList}
                    onChange={(v) => this.handleChange(key, v)}
                  />
                  {this.renderBrowser(it)}
                </div>
              </WeaFormItem>;
            })
          }
        </WeaSearchGroup>
      </WeaDialog>
    );
  }
}

export default PayrollPartModal;
