/*
 * Author: 黎永顺
 * name: 人员确认
 * Description:
 * Date: 2023/9/13
 */
import React, { Component } from "react";
import { WeaBrowser, WeaButtonIcon, WeaHelpfulTip, WeaLocaleProvider, WeaTab, WeaTable, WeaTools } from "ecCom";
import { inject, observer } from "mobx-react";
import { Button, message, Modal } from "antd";
import BaseInfo from "./baseInfo";
import {
  acctemployeeList,
  addedemployeeList,
  deleteAcctemployee,
  reducedemployeeList,
  refreshAcctemployee,
  saveAcctemployee
} from "../../../../../apis/calculate";
import { personConfirmSearchConditions } from "./condition";
import { getSearchs } from "../../../../../util";
import { convertToUrlString } from "../../../../../util/url";

const getKey = WeaTools.getKey;
const getLabel = WeaLocaleProvider.getLabel;
const api = {
  range: acctemployeeList,
  sub: reducedemployeeList,
  add: addedemployeeList
};

@inject("calculateStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedKey: "range", showSearchAd: false,
      searchConditions: [], loading: false,
      pageInfo: { current: 1, pageSize: 10, total: 0 },
      selectedRowKeys: [], dataSource: [], columns: []
    };
  }

  componentDidMount() {
    if ($) {
      const domTabInnerList = $(".salary-calculate-do-calc-content .ant-tabs-tab-inner");
      domTabInnerList[0].setAttribute("title", "");
      domTabInnerList[1].setAttribute("title", "");
      domTabInnerList[2].setAttribute("title", "");
    }
    this.setState({
      searchConditions: _.map(personConfirmSearchConditions, item => {
        return {
          ...item,
          items: _.map(item.items, o => {
            if (getKey(o) === "statuses") {
              return {
                ...o,
                options: [
                  { key: "0", showname: getLabel(18883, "试用") }, { key: "1", showname: getLabel(15711, "正式") },
                  { key: "2", showname: getLabel(480, "临时") }, { key: "3", showname: getLabel(15844, "试用延期") },
                  { key: "4", showname: getLabel(542707, "解雇") }, { key: "5", showname: getLabel(6091, "离职") },
                  { key: "6", showname: getLabel(6092, "退休") }
                ]
              };
            }
            return { ...o };
          }),
          title: getLabel(32905, "常用条件")
        };
      })
    }, () => {
      const { calculateStore: { PCSearchForm } } = this.props;
      PCSearchForm.initFormFields(this.state.searchConditions);
      this.queryPCList();
    });
  }

  renderTabBtns = () => {
    const { selectedKey, selectedRowKeys } = this.state;
    const { calcDetail } = this.props;
    let tabBtns = [];
    switch (selectedKey) {
      case "range":
        tabBtns = [
          <WeaButtonIcon buttonType="del" type="primary" title={getLabel(111, "批量删除")}
                         disabled={_.isEmpty(selectedRowKeys)}
                         onClick={() => this.handleDeletePCitem()}/>,
          <WeaBrowser type={17} title={getLabel(383694, "添加人员")} isSingle={false} customized
                      onChange={ids => ids && this.handleUserBrowserChange(ids.split(","))}
          >
            <WeaButtonIcon buttonType="add" type="primary" title={getLabel(1421, "新增")}/>
          </WeaBrowser>,
          <span className="icon-refresh" onClick={this.handleRefresh}><i
            className="icon-coms-Refresh"/></span>,
          <Button type="primary" onClick={this.handleExport}>{getLabel(17416, "导出")}</Button>
        ];
        calcDetail && tabBtns.splice(0, 2);
        break;
      case "add":
      case "sub":
        tabBtns = [
          <Button type="primary" onClick={this.handleExport}>{getLabel(17416, "导出")}</Button>
        ];
        break;
      default:
        break;
    }
    return tabBtns;
  };
  queryPCList = () => {
    const { pageInfo, selectedKey } = this.state;
    const { calculateStore: { PCSearchForm }, routeParams: { salaryAcctRecordId } } = this.props;
    const { departmentIds, positionIds, statuses, ...extra } = PCSearchForm.getFormParams();
    const payload = {
      salaryAcctRecordId, ...pageInfo, ...extra,
      departmentIds: !_.isEmpty(departmentIds) ? departmentIds.split(",") : [],
      positionIds: !_.isEmpty(positionIds) ? positionIds.split(",") : [],
      statuses: !_.isEmpty(statuses) ? statuses.split(",") : []
    };
    this.setState({ loading: true });
    api[selectedKey](payload).then(({ status, data }) => {
      this.setState({ loading: false });
      if (status) {
        const { columns, list: dataSource = [], pageNum: current, pageSize, total } = data;
        this.setState({
          columns, dataSource, pageInfo: { ...pageInfo, current, pageSize, total }
        });
      }
    }).catch(() => this.setState({ loading: false }));
  };
  handleDeletePCitem = (ids) => {
    Modal.confirm({
      title: getLabel(131329, "信息确认"),
      content: getLabel(388758, "确认要删除吗?"),
      onOk: () => {
        const { selectedRowKeys } = this.state;
        const { routeParams: { salaryAcctRecordId } } = this.props;
        deleteAcctemployee({ salaryAcctRecordId, ids: !_.isEmpty(ids) ? ids : selectedRowKeys })
          .then(({ status, errormsg }) => {
            if (status) {
              message.success(getLabel(502230, "删除成功！"));
              this.queryPCList();
              _.isNil(ids) && this.setState({ selectedRowKeys: [] });
            } else {
              message.error(errormsg || getLabel(20462, "删除失败！"));
            }
          });
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description: 人员确认导出
   * Params:
   * Date: 2023/9/14
   */
  handleExport = () => {
    let url = "";
    const { routeParams: { salaryAcctRecordId }, calculateStore: { PCSearchForm } } = this.props;
    if (this.state.selectedKey === "range") {
      url = `${window.location.origin}/api/bs/hrmsalary/salaryacct/acctemployee/export?salaryAcctRecordId=${salaryAcctRecordId}&${convertToUrlString(PCSearchForm.getFormParams())}`;
    } else if (this.state.selectedKey === "sub") {
      url = `${window.location.origin}/api/bs/hrmsalary/salaryacct/reducedemployee/export?salaryAcctRecordId=${salaryAcctRecordId}&${convertToUrlString(PCSearchForm.getFormParams())}`;
    } else {
      url = `${window.location.origin}/api/bs/hrmsalary/salaryacct/addedemployee/export?salaryAcctRecordId=${salaryAcctRecordId}&${convertToUrlString(PCSearchForm.getFormParams())}`;
    }
    window.open(url, "_blank");
  };
  /*
   * Author: 黎永顺
   * Description: 添加人员确认
   * Params:
   * Date: 2023/9/14
   */
  handleUserBrowserChange = (employeeIds) => {
    const { routeParams: { salaryAcctRecordId } } = this.props;
    saveAcctemployee({ salaryAcctRecordId, employeeIds }).then(({ status, errormsg }) => {
      if (status) {
        message.success(getLabel(26712, "添加成功！"));
        this.queryPCList();
      } else {
        message.error(errormsg || getLabel(545246, "添加失败！"));
      }
    });
  };
  handleRefresh = () => {
    if (!this.handleDebounce) {
      this.handleDebounce = _.debounce(() => {
        const { routeParams: { salaryAcctRecordId } } = this.props;
        refreshAcctemployee({ salaryAcctRecordId }).then(({ status, errormsg }) => {
          if (status) {
            message.success(getLabel(111, "操作成功！"));
            this.queryPCList();
          } else {
            message.error(errormsg);
          }
        });
        this.handleDebounce = null;
      }, 500);
    }
    this.handleDebounce();
  };

  render() {
    const { calculateStore: { PCSearchForm }, calcDetail } = this.props;
    const {
      selectedKey, showSearchAd, searchConditions, pageInfo, loading, selectedRowKeys,
      columns, dataSource
    } = this.state;
    const tabDatas = [
      {
        title: <React.Fragment>
          <span>{getLabel(542307, "核算人员范围")}</span>
          <WeaHelpfulTip
            width={200} placement="topLeft"
            title={getLabel(543551, "核算完若薪资档案中个税扣缴义务人发生调整，需先刷新【核算人员范围】再到【薪资核算】中重新核算")}
            style={{ marginLeft: 8 }}
          />
        </React.Fragment>, viewcondition: "range"
      },
      {
        title: <React.Fragment>
          <span>{getLabel(542308, "环比上月减少人员")}</span>
          <WeaHelpfulTip
            width={200} placement="topLeft"
            title={getLabel(543552, "提示：环比上期当前选择的账套归档的各个税扣缴义务人下减少的人员")}
            style={{ marginLeft: 8 }}
          />
        </React.Fragment>, viewcondition: "sub"
      },
      {
        title: <React.Fragment>
          <span>{getLabel(542309, "环比上月增加人员")}</span>
          <WeaHelpfulTip
            width={200} placement="topLeft"
            title={getLabel(543553, "提示：环比上期当前选择的账套归档的各个税扣缴义务人下增加的人员")}
            style={{ marginLeft: 8 }}
          />
        </React.Fragment>, viewcondition: "add"
      }
    ];
    const pagination = {
      ...pageInfo,
      showTotal: total => `${getLabel(18609, "共")} ${total} ${getLabel(18256, "条")}`,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ["10", "20", "50", "100"],
      onShowSizeChange: (current, pageSize) => {
        this.setState({ pageInfo: { ...pageInfo, current, pageSize } }, () => this.queryPCList());
      },
      onChange: current => {
        this.setState({ pageInfo: { ...pageInfo, current } }, () => this.queryPCList());
      }
    };
    const rowSelection = {
      columnWidth: 80,
      selectedRowKeys,
      onChange: selectedRowKeys => this.setState({ selectedRowKeys })
    };
    return (
      <div className="person-confirm-layout">
        <BaseInfo {...this.props}/>
        <WeaTab
          datas={tabDatas} keyParam="viewcondition" selectedKey={selectedKey}
          onChange={v => this.setState({
            selectedKey: v,
            pageInfo: { ...pageInfo, current: 1 }
          }, () => this.queryPCList())}
          onSearch={v => this.setState({
            pageInfo: { ...pageInfo, current: 1 }
          }, () => this.queryPCList())}
          onAdSearch={v => this.setState({
            pageInfo: { ...pageInfo, current: 1 }
          }, () => this.queryPCList())}
          buttons={this.renderTabBtns()} searchType={["base", "advanced"]} advanceHeight={220}
          showSearchAd={showSearchAd} setShowSearchAd={bool => this.setState({ showSearchAd: bool })}
          searchsAd={getSearchs(PCSearchForm, searchConditions, 2, false)}
          onSearchChange={(v) => PCSearchForm.updateFields({ employeeName: v })}
          searchsBaseValue={PCSearchForm.getFormParams().employeeName}
          onAdReset={() => PCSearchForm.resetForm()} autoCalculateWidth
        />
        <WeaTable
          dataSource={dataSource} loading={loading} rowSelection={calcDetail ? null : rowSelection}
          pagination={pagination} scroll={{ y: `calc(100vh - 365px)` }} rowKey="id"
          columns={[..._.map(columns, item => {
            let width = "";
            const { dataIndex } = item;
            switch (dataIndex) {
              case "taxAgentName":
              case "departmentName":
                width = "15%";
                break;
              default:
                width = "10%";
                break;
            }
            return { ...item, width };
          }),
            {
              dataIndex: "operate",
              title: getLabel(30585, "操作"),
              width: 120,
              render: (_, record) => (<React.Fragment>
                  {calcDetail ? null : <a href="javascript:void(0);"
                                          onClick={() => this.handleDeletePCitem([record.id])}>{getLabel(535052, "删除")}</a>}
                </React.Fragment>
              )
            }
          ]}
        />
      </div>
    );
  }
}

export default Index;
