import React from "react";
import { Button, message } from "antd";
import { WeaButtonIcon, WeaFormItem, WeaInput, WeaSearchGroup, WeaTab, WeaTable } from "ecCom";
import AddTaxAgentModal from "./addTaxAgentModal";
import ImportModal from "../../components/importModal";
import { taxAgentRangeImportData, taxAgentRangePreview } from "../../apis/taxAgent";
import { sysinfo } from "../../apis/ruleconfig";
import { importEmployColumns } from "./columns";
import ExternalPersonModal from "../../components/externalPersonModal";

export default class SlideTaxagentUser extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showSearchAd: false,
      externalPersonModalVisible: false, //外部人员关联弹框
      addTaxagentModalVisible: false,
      scopeRecord: {},
      includeType: "1",
      selectedRowKeys: [],
      searchValue: "",
      targetWorkcode: "",
      previewDataSource: [],
      importParams: {
        visible: false,
        step: 0,
        importResult: {}
      },
      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 });
    });
  };

  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys });
  };

  handleTabDelete = () => {
    const { onDeleteTaxAgent } = this.props;
    const { includeType, selectedRowKeys } = this.state;
    if (selectedRowKeys.length === 0) {
      message.warning("未选择条目");
      return;
    }
    onDeleteTaxAgent({ ids: this.state.selectedRowKeys, tab: includeType });
  };

  handleSearch = () => {
    const { includeType, searchValue, targetWorkcode } = this.state;
    const { onTaxAngetSearch } = this.props;
    onTaxAngetSearch({
      tab: includeType,
      targetName: searchValue,
      targetWorkcode
    });
  };

  closeModal = () => {
    this.setState({
      addTaxagentModalVisible: false,
      externalPersonModalVisible: false,
      scopeRecord: {}
    }, () => {
      this.addTaxRef && this.addTaxRef.handleReset();
    });
  };
  handleInitModal = () => {
    //  清空导入弹框列表数据
    this.setState({
      previewDataSource: [],
      importParams: {
        ...this.state.importParams,
        importResult: {}
      }
    });
  };
  // 导入档案
  handleImportFile = (params) => {
    const { taxAgentId } = this.props;
    taxAgentRangeImportData({ ...params, taxAgentId }).then(({ status, data }) => {
      if (status) {
        this.setState({
          importParams: {
            ...this.state.importParams,
            importResult: data
          }
        });
      }
    });
  };
  salaryArchivePreview = (params) => {
    taxAgentRangePreview(params).then(({ status, data }) => {
      if (status) {
        const { preview } = data;
        this.setState({
          previewDataSource: preview
        });
      }
    });
  };
  getSearchs = () => {
    return <WeaSearchGroup center needTigger showGroup title="其他条件">
      <WeaFormItem label="工号" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
        <WeaInput
          value={this.state.targetWorkcode}
          onChange={v => this.setState({ targetWorkcode: v })}
        />
      </WeaFormItem>
    </WeaSearchGroup>;
  };

  render() {
    const {
      includeType,
      selectedRowKeys,
      searchValue,
      addTaxagentModalVisible,
      externalPersonModalVisible,
      importParams,
      previewDataSource,
      showSearchAd, extEmpsWitch,
      scopeRecord
    } = this.state;
    const {
      submitLoading,
      queryLoading,
      dataSource,
      columns: taxAgentColumns,
      pageObj,
      setPageObj,
      employeeStatus,
      targetTypeList,
      onTaxAgentSave,
      hideIconInTax,
      showSalaryItemBtn,
      onTaxAngetSearch,
      taxAgentId,
      onChangeTab
    } = this.props;

    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange
    };
    const pagination = {
      ...pageObj,
      total: pageObj.total,
      showTotal: total => `共 ${total} 条`,
      pageSizeOptions: ["10", "20", "50", "100"],
      showQuickJumper: true,
      showSizeChanger: true,
      onShowSizeChange: (current, pageSize) => {
        setPageObj &&
        setPageObj({
          current,
          pageSize,
          tab: includeType,
          targetName: searchValue
        });
      },
      onChange: current => {
        setPageObj &&
        setPageObj({
          current,
          tab: includeType,
          targetName: searchValue
        });
      }
    };
    let btns = [
      <Button type="primary" size="small"
              onClick={() => {
                this.setState({ importParams: { ...importParams, visible: true, step: 0 } });
              }}
      ><span className="icon-coms-leading-in" title="导入"></span></Button>,
      <WeaButtonIcon buttonType="del" type="primary" disabled={_.isEmpty(selectedRowKeys)}
                     onClick={this.handleTabDelete}/>,
      <WeaButtonIcon
        buttonType="add" type="primary"
        onClick={() => {
          const key = includeType === "2" ? "externalPersonModalVisible" : "addTaxagentModalVisible";
          this.setState({ [key]: true });
        }}
      />
    ];
    (includeType === "0" || includeType === "2") && btns.shift();
    return (
      <div className="slideRefereUser">
        <WeaTab
          datas={
            (extEmpsWitch === "0" || !extEmpsWitch) ?
              [
                { title: "人员范围", viewcondition: "1" },
                { title: "从范围中排除", viewcondition: "0" }
              ] :
              [
                { title: "人员范围", viewcondition: "1" },
                { title: "从范围中排除", viewcondition: "0" },
                { title: "非系统人员范围", viewcondition: "2" }
              ]
          }
          keyParam="viewcondition" selectedKey={includeType}
          searchType={["base"]} advanceHeight={200}
          showSearchAd={showSearchAd} searchsAd={this.getSearchs()}
          setShowSearchAd={showSearchAd => {
            this.setState({ showSearchAd });
          }}
          buttons={(hideIconInTax || showSalaryItemBtn) ? btns : []}
          onAdReset={() => this.setState({ targetWorkcode: "" })}
          onAdSearch={this.handleSearch}
          onSearch={this.handleSearch}
          onSearchChange={searchValue => this.setState({ searchValue })}
          onChange={v => this.setState({ includeType: v }, () => onChangeTab && onChangeTab(this.state.includeType))}
        />

        <div style={{ maxHeight: "500px", scrollY: "scroll" }}>
          <WeaTable rowKey="id" loading={queryLoading} rowSelection={rowSelection} dataSource={dataSource}
                    pagination={pagination}
                    columns={_.map(taxAgentColumns, o => {
                      return {
                        ...o, render: (text, record) => {
                          if (o.dataIndex === "targetName") {
                            return <a href="javascript:void(0);" onClick={() => {
                              const key = includeType === "2" ? "externalPersonModalVisible" : "addTaxagentModalVisible";
                              this.setState({ [key]: true, scopeRecord: record });
                            }}>{text}</a>;
                          }
                          return <span>{text}</span>;
                        }
                      };
                    })}/>
        </div>
        <ExternalPersonModal
          visible={externalPersonModalVisible}
          loading={submitLoading}
          onCancel={() => this.setState({ externalPersonModalVisible: false, scopeRecord: {} })}
          onExternalPersonSave={val => onTaxAgentSave({ ...val, includeType: includeType })}
        />
        <AddTaxAgentModal
          ref={(ref) => this.addTaxRef = ref}
          scopeRecord={scopeRecord}
          loading={submitLoading}
          employeeStatus={employeeStatus}
          targetTypeList={targetTypeList}
          onTaxAgentSave={val =>
            onTaxAgentSave &&
            onTaxAgentSave({ ...val, includeType: includeType })}
          visible={addTaxagentModalVisible}
          onCancel={() => {
            this.setState({ addTaxagentModalVisible: false, scopeRecord: {} });
          }}
        />
        {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
                }
              }, () => {
                onTaxAngetSearch({
                  tab: includeType,
                  targetName: searchValue
                });
              });
            }}
            previewImport={(params) => this.salaryArchivePreview(params)}
            importFile={(params) => this.handleImportFile(params)}
            templateLink={`/api/bs/hrmsalary/taxAgent/range/downloadTemplate?taxAgentId=${taxAgentId}`}
            visiable={importParams.visible}
            onCancel={() => {
              this.setState({ importParams: { ...this.state.importParams, visible: false } });
            }}
          />
        )}
      </div>
    );
  }
}
