/*
 * Author: 黎永顺
 * name: 人员范围
 * Description:
 * Date: 2022/11/30
 */
import React, { Component } from "react";
import { message, Modal } from "antd";
import { inject, observer } from "mobx-react";
import { WeaButtonIcon, WeaInputSearch, WeaLocaleProvider, WeaTab } from "ecCom";
import {
  taxAgentRangeDelete,
  taxAgentRangeExtDelete,
  taxAgentRangeExtSave,
  taxAgentRangeImportData
} from "../../../apis/taxAgent";
import { sysinfo } from "../../../apis/ruleconfig";
import PersonalScopeTable from "./personalScopeTable";
import PersonalScopeModal from "./personalScopeModal";
import ImportDialog from "../../../components/importDialog";
import ExternalPersonModal from "../../../components/externalPersonModal";

const getLabel = WeaLocaleProvider.getLabel;

@inject("taxAgentStore")
@observer
class PersonalScope extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchValue: "", selectedKey: "listInclude", rowKeys: [], loading: false,
      extEmpsWitch: "1", //非系统人员开关， 1： 开启， 0：关闭
      personalAddModal: {
        visible: false, externalVisible: false, title: getLabel(111, "关联人员"), includeType: "", record: {}
      },
      importParams: {
        visible: false, title: getLabel(111, "数据导入"), nextloading: false, importResult: {}, imageId: "",
        link: `/api/bs/hrmsalary/taxAgent/range/downloadTemplate?taxAgentId=${props.taxAgentId}`,
        previewUrl: "/api/bs/hrmsalary/taxAgent/range/preview"
      }
    };
    this.personalScopeTableRef = null;
  }

  componentDidMount() {
    const { taxAgentStore: { hasIconInTax } } = this.props;
    hasIconInTax();
    this.getSysinfo();
  }

  /*
   * Author: 黎永顺
   * Description:非系统人员开关查询
   * Params:
   * Date: 2023/11/9
   */
  getSysinfo = () => {
    sysinfo().then(({ status, data }) => {
      if (status) this.setState({ extEmpsWitch: data.extEmpsWitch });
    });
  };
  /*
   * Author: 黎永顺
   * Description: 删除人员范围
   * Params:
   * Date: 2022/11/30
   */
  taxAgentRangeDelete = () => {
    Modal.confirm({
      title: "信息确认",
      content: "确认要删除吗?",
      onOk: () => {
        const { selectedKey } = this.state;
        const API = selectedKey === "listExt" ? taxAgentRangeExtDelete : taxAgentRangeDelete;
        API(this.state.rowKeys).then(({ status, errormsg }) => {
          if (status) {
            message.success("删除成功");
            this.setState({ rowKeys: [] }, () => {
              this.personalScopeTableRef.clearRowkeys();
            });
          } else {
            message.error(errormsg || "删除失败");
          }
        });
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description:新增人员范围
   * Params:
   * Date: 2022/11/30
   */
  handleAddPersonal = (record = {}) => {
    const { personalAddModal, selectedKey } = this.state;
    this.setState({
      personalAddModal: {
        ...personalAddModal, record,
        visible: selectedKey !== "listExt",
        externalVisible: selectedKey === "listExt",
        includeType: selectedKey === "listInclude" ? 1 : 0
      }
    });
  };
  handleImportFile = (params) => {
    const { taxAgentId } = this.props, { importParams } = this.state;
    this.setState({ importParams: { ...importParams, nextloading: true } });
    taxAgentRangeImportData({ ...params, taxAgentId }).then(({ status, errormsg, data }) => {
      this.setState({ importParams: { ...importParams, nextloading: false } });
      if (status) {
        this.setState({ importParams: { ...importParams, importResult: data } });
      } else {
        message.warning(errormsg);
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description: 保存非系统人员
   * Params:
   * Date: 2023/11/9
   */
  handleSaveExtPersons = (payload = {}) => {
    const { taxAgentId } = this.props;
    const { personalAddModal } = this.state;
    this.setState({ loading: false });
    taxAgentRangeExtSave({ taxAgentId, ...payload }).then(({ status, errormsg }) => {
      this.setState({ loading: false });
      if (status) {
        message.success("新增成功");
        this.setState({
          personalAddModal: {
            ...personalAddModal,
            externalVisible: false
          }
        }, () => this.personalScopeTableRef.getPersonalScopeList());
      } else {
        message.error(errormsg);
      }
    }).catch(() => this.setState({ loading: false }));
  };

  render() {
    const { selectedKey, searchValue, rowKeys, personalAddModal, importParams, extEmpsWitch, loading } = this.state;
    const { taxAgentStore: { PageAndOptAuth, hideIconInTax }, taxAgentId } = this.props;
    const showOperateBtn = PageAndOptAuth.opts.includes("admin");
    const topTab = [
      {
        title: "管理范围",
        viewcondition: "listInclude"
      },
      {
        title: "从范围中排除",
        viewcondition: "listExclude"
      },
      {
        title: "非系统人员范围",
        viewcondition: "listExt"
      }
    ];
    const btns = showOperateBtn ? [
      <span className="icon-refresh" title={getLabel(111, "导入")} onClick={() => {
        this.setState({ importParams: { ...importParams, visible: true } });
      }}><i className="icon-coms-leading-in"/></span>,
      <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(selectedKey, 1)}
      />
    ] : [<WeaInputSearch
      style={{ width: 220 }}
      value={searchValue}
      onChange={searchValue => this.setState({ searchValue })}
      placeholder="请输入对象"
      onSearch={() => this.personalScopeTableRef.getPersonalScopeList(selectedKey, 1)}
    />];
    (selectedKey === "listExclude" || selectedKey === "listExt") && btns.shift();
    return (
      <div className="personal-scope">
        <WeaTab
          datas={(extEmpsWitch === "0" || !extEmpsWitch) ? topTab.slice(0, -1) : topTab}
          keyParam="viewcondition" //主键
          selectedKey={selectedKey}
          buttons={btns}
          onChange={selectedKey => this.setState({ selectedKey })}
        />
        <PersonalScopeTable
          ref={dom => this.personalScopeTableRef = dom}
          taxAgentId={taxAgentId}
          tabActive={selectedKey}
          searchValue={searchValue}
          onChangeSelectKey={rowKeys => this.setState({ rowKeys })}
          onEditScope={this.handleAddPersonal}
        />
        {/*非系统人员添加*/}
        <ExternalPersonModal
          visible={personalAddModal.externalVisible} loading={loading}
          onCancel={() => this.setState({ personalAddModal: { ...personalAddModal, externalVisible: false } })}
          onExternalPersonSave={this.handleSaveExtPersons}
        />
        <PersonalScopeModal
          {...personalAddModal}
          taxAgentId={taxAgentId}
          onSuccess={() => this.personalScopeTableRef.getPersonalScopeList()}
          onCancel={(callback) =>
            this.setState({
              personalAddModal: { ...personalAddModal, visible: false, includeType: "", record: {} }
            }, () => callback && callback())
          }
        />
        <ImportDialog {...importParams}
                      nextCallback={imageId => this.setState({ importParams: { ...importParams, imageId } })}
                      nextUplaodCallback={imageId => this.handleImportFile({ imageId })}
                      onResetImportResult={() => this.setState(({
                        importParams: { ...importParams, importResult: {}, imageId: "" }
                      }))}
                      onCancel={(callback) => this.setState({
                        importParams: { ...importParams, visible: false }
                      }, () => callback && this.personalScopeTableRef.getPersonalScopeList(selectedKey, 1))}/>
      </div>
    );
  }
}

export default PersonalScope;
