/*
 * Author: 黎永顺
 * name: 薪资账套关联人员
 * Description:
 * Date: 2022/12/12
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { Button, message, Modal } from "antd";
import { WeaButtonIcon, WeaInputSearch, WeaTab } from "ecCom";
import PersonalScopeTable from "../../../components/PersonalScopeTable";
import PersonalScopeModal from "../../../components/PersonalScopeModal";
import {
  deleteLedgerPersonExtRange,
  deleteLedgerPersonRange,
  editLedgerPersonRange,
  getLedgerPersonRangeExclude,
  getLedgerPersonRangeExtList,
  getLedgerPersonRangeInclude,
  salarysobRangeImportData,
  salarysobRangePreview,
  saveLedgerPersonExtRange,
  saveLedgerPersonRange
} from "../../../apis/ledger";
import ImportModal from "../../../components/importModal";
import { importEmployColumns } from "../../taxAgent/columns";
import ExternalPersonModal from "../../../components/externalPersonModal";
import { sysinfo } from "../../../apis/ruleconfig";

const APIFox = {
  listInclude: getLedgerPersonRangeInclude,
  listExclude: getLedgerPersonRangeExclude,
  externalList: getLedgerPersonRangeExtList
};
const APISaveFox = {
  save: saveLedgerPersonRange,
  edit: editLedgerPersonRange
};

@inject("taxAgentStore")
@observer
class LedgerAssociatedPersonnel extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchValue: "",
      selectedKey: "listInclude",
      rowKeys: [],
      previewDataSource: [],
      externalPersonModalVisible: false,
      loading: false,
      importParams: {
        visible: false,
        step: 0,
        importResult: {}
      },
      personalAddModal: {
        visible: false,
        title: "关联人员",
        includeType: "",
        record: {}
      },
      extEmpsWitch: "1" //非系统人员开关， 1： 开启， 0：关闭
    };
  }

  componentDidMount() {
    this.getSysinfo();
  }

  /*
    * Author: 黎永顺
    * Description: 非系统人员开关查询
    * Params:
    * Date: 2023/7/14
    */
  getSysinfo = () => {
    sysinfo().then(({ status, data }) => {
      if (status) this.setState({ extEmpsWitch: data.extEmpsWitch });
    });
  };
  /*
   * Author: 黎永顺
   * Description:外部人员保存
   * Params:
   * Date: 2023/3/14
   */
  handleSaveExternalPerson = (val) => {
    const { editId: salarySobId, saveSalarySobId } = this.props;
    saveLedgerPersonExtRange({ ...val, salarySobId: salarySobId || saveSalarySobId }).then(({ status, errormsg }) => {
      this.setState({ loading: false });
      if (status) {
        message.success("保存成功");
        this.setState({ externalPersonModalVisible: false });
        this.personalScopeTableRef.getPersonalScopeList();
      } else {
        message.error(errormsg || "保存失败");
      }
    }).catch(() => this.setState({ loading: true }));
  };
  /*
   * Author: 黎永顺
   * Description: 删除人员范围
   * Params:
   * Date: 2022/11/30
   */
  taxAgentRangeDelete = () => {
    const { selectedKey } = this.state;
    Modal.confirm({
      title: "信息确认",
      content: "确认要删除吗?",
      onOk: () => {
        return new Promise((resolve, reject) => {
          return selectedKey === "externalList" ? this.deleteLedgerPersonExtRange(resolve, reject) : this.deleteLedgerPersonRange(resolve, reject);
        }).catch(() => console.log("出错!"));
      }
    });
  };
  deleteLedgerPersonExtRange = (resolve, reject) => {
    message.destroy();
    message.loading("正在删除中...", 0);
    deleteLedgerPersonExtRange(this.state.rowKeys).then(({ status, errormsg }) => {
      message.destroy();
      resolve();
      if (status) {
        message.success("删除成功");
        this.setState({ rowKeys: [] }, () => {
          this.personalScopeTableRef.clearRowkeys();
        });
      } else {
        message.error(errormsg || "删除失败");
      }
    }).catch(() => {
      message.destroy();
      reject();
    });
  };
  deleteLedgerPersonRange = (resolve, reject) => {
    message.destroy();
    message.loading("正在删除中...", 0);
    deleteLedgerPersonRange(this.state.rowKeys).then(({ status, errormsg }) => {
      message.destroy();
      resolve();
      if (status) {
        message.success("删除成功");
        this.setState({ rowKeys: [] }, () => {
          this.personalScopeTableRef.clearRowkeys();
        });
      } else {
        message.error(errormsg || "删除失败");
      }
    }).catch(() => {
      message.destroy();
      reject();
    });
  };
  /*
   * Author: 黎永顺
   * Description:新增人员范围
   * Params:
   * Date: 2022/11/30
   */
  handleAddPersonal = (record = {}) => {
    const { personalAddModal, selectedKey } = this.state;
    if (selectedKey === "externalList") {
      this.setState({ externalPersonModalVisible: true });
    } else {
      this.setState({
        personalAddModal: {
          ...personalAddModal,
          visible: true, record,
          includeType: selectedKey === "listInclude" ? 1 : 0
        }
      });
    }
  };
  /*
   * Author: 黎永顺
   * Description:清空导入弹框列表数据
   * Params:
   * Date: 2023/1/9
   */
  handleInitModal = () => {
    this.setState({
      previewDataSource: [],
      importParams: {
        ...this.state.importParams,
        importResult: {}
      }
    });
  };
  handleImportFile = (params) => {
    const { editId: salarySobId } = this.props;
    salarysobRangeImportData({ ...params, salarySobId }).then(({ status, data }) => {
      if (status) {
        this.setState({
          importParams: {
            ...this.state.importParams,
            importResult: data
          }
        });
      }
    });
  };
  salarysobRangePreview = (params) => {
    salarysobRangePreview(params).then(({ status, data }) => {
      if (status) {
        const { preview } = data;
        this.setState({
          previewDataSource: preview
        });
      }
    });
  };

  render() {
    const {
      selectedKey,
      searchValue,
      rowKeys,
      personalAddModal,
      importParams,
      previewDataSource,
      externalPersonModalVisible,
      loading, extEmpsWitch
    } = this.state;
    const { taxAgentStore: { showOperateBtn }, editId, saveSalarySobId } = this.props;
    const topTab = [
      {
        title: "关联人员范围",
        viewcondition: "listInclude"
      },
      {
        title: "从范围中排除",
        viewcondition: "listExclude"
      },
      {
        title: "非系统人员范围",
        viewcondition: "externalList"
      }
    ];
    const btns = showOperateBtn ? [
      <Button
        className="icon-coms-leading-in-btn"
        type="primary"
        size="small"
        onClick={() => this.setState({
          importParams: {
            ...this.state.importParams,
            visible: true,
            step: 0,
            importResult: {}
          }
        })}
      ><span className="icon-coms-leading-in" title="导入"></span></Button>,
      <WeaButtonIcon
        buttonType="del"
        type="primary"
        disabled={_.isEmpty(rowKeys)}
        onClick={this.taxAgentRangeDelete}
      />,
      <WeaButtonIcon buttonType="add" type="primary" onClick={() => this.handleAddPersonal()}/>,
      <WeaInputSearch
        style={{ width: 220 }}
        value={searchValue}
        onChange={searchValue => this.setState({ searchValue })}
        placeholder="请输入对象"
        onSearch={() => this.personalScopeTableRef.getPersonalScopeList()}
      />
    ] : [<WeaInputSearch
      style={{ width: 220 }}
      value={searchValue}
      onChange={searchValue => this.setState({ searchValue })}
      placeholder="请输入对象"
      onSearch={() => this.personalScopeTableRef.getPersonalScopeList()}
    />];
    return (
      <div>
        <WeaTab
          datas={(extEmpsWitch === "0" || !extEmpsWitch) ? _.dropRight(topTab) : topTab}
          keyParam="viewcondition" //主键
          selectedKey={selectedKey}
          buttons={showOperateBtn && selectedKey === "listInclude" ? btns : btns.slice(1)}
          onChange={selectedKey => this.setState({ selectedKey })}
        />
        <PersonalScopeTable
          ref={dom => this.personalScopeTableRef = dom}
          searchKeyVal={{ key: "salarySobId", value: editId || saveSalarySobId }}
          APIFox={APIFox}
          tabActive={selectedKey}
          searchValue={searchValue}
          showOperateBtn={showOperateBtn}
          onChangeSelectKey={rowKeys => this.setState({ rowKeys })}
          onEditScope={this.handleAddPersonal}
        />
        {/*关联人员范围导入*/}
        {importParams.visible && (
          <ImportModal
            init={() => {
              this.handleInitModal();
            }}
            isInit={false}
            columns={importEmployColumns}
            slideDataSource={previewDataSource}
            step={importParams.step}
            setStep={(step) => {
              this.setState({ importParams: { ...this.state.importParams, step } });
            }}
            importResult={importParams.importResult}
            onFinish={() => {
              this.setState({
                importParams: {
                  ...this.state.importParams,
                  visible: false
                }
              }, () => this.personalScopeTableRef.getPersonalScopeList());
            }}
            previewImport={(params) => this.salarysobRangePreview(params)}
            importFile={(params) => this.handleImportFile(params)}
            templateLink={`/api/bs/hrmsalary/salarysob/range/downloadTemplate?salarySobId=${editId}`}
            visiable={importParams.visible}
            onCancel={() => {
              this.setState({ importParams: { ...this.state.importParams, visible: false } });
            }}
          />
        )}
        {/*非系统人员添加*/}
        <ExternalPersonModal
          visible={externalPersonModalVisible}
          loading={loading}
          onCancel={() => this.setState({ externalPersonModalVisible: false })}
          onExternalPersonSave={this.handleSaveExternalPerson}
        />
        {/*新增人员范围*/}
        <PersonalScopeModal
          {...personalAddModal}
          APISaveFox={APISaveFox}
          isTaxgent={false}
          saveKeyVal={{ key: "salarySobId", value: editId || saveSalarySobId }}
          onSuccess={() => this.personalScopeTableRef.getPersonalScopeList()}
          onCancel={() =>
            this.setState({
              personalAddModal: {
                ...personalAddModal, record: {}, includeType: "", visible: false
              }
            })
          }
        />
      </div>
    );
  }
}

export default LedgerAssociatedPersonnel;
