/*
 * Author: 黎永顺
 * name: 非系统人员管理
 * Description:
 * Date: 2023/3/13
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaHelpfulTip, WeaLocaleProvider, WeaTab, WeaTable, WeaTop } from "ecCom";
import ExternalPersonManageEditSlide from "./components/externalPersonManageEditSlide";
import ExternalPersonImport from "./components/externalPersonImport";
import { Button, Dropdown, Menu, message, Modal } from "antd";
import { getSearchs } from "../../util";
import { condition, searchCondition } from "./conditions";
import { deleteExtEmp, listPage } from "../../apis/externalPersonManage";
import "./index.less";
import LogDialog from "../../components/logViewModal";

const getLabel = WeaLocaleProvider.getLabel;

@inject("externalPersonManageStore", "taxAgentStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false, logDialogVisible: false, filterConditions: "[]",
      selectedRowKeys: [],
      pageInfo: { current: 1, pageSize: 10, total: 0 },
      showSearchAd: false,
      externalPersonManagePayload: {
        visible: false, title: "新建", id: ""
      },
      externalPersonImportPayload: {
        visiable: false, step: 0
      }
    };
  }

  componentDidMount() {
    const { externalPersonManageStore: { form, addForm } } = this.props;
    form.initFormFields(searchCondition);
    addForm.initFormFields(condition);
    this.listPage();
  }

  listPage = () => {
    const { pageInfo } = this.state;
    const { externalPersonManageStore: { form } } = this.props;
    const payload = { ...pageInfo, ...form.getFormParams() };
    listPage(payload).then(({ status, data }) => {
      if (status) {
        const { list: dataSource, columns, pageNum: current, pageSize, total } = data;
        this.setState({
          dataSource, columns,
          pageInfo: { ...pageInfo, current, pageSize, total }
        });
      }
    });
  };
  deleteExtEmp = (ids) => {
    deleteExtEmp(ids).then(({ status, errormsg }) => {
      if (status) {
        message.success("删除成功");
        this.listPage();
      } else {
        message.error(errormsg || "删除失败");
      }
    });
  };
  handleDelete = (id) => {
    Modal.confirm({
      title: "信息确认",
      content: "确定删除吗",
      onOk: () => this.deleteExtEmp([id])
    });
  };
  handleCancel = (isRefresh) => {
    const { externalPersonManagePayload } = this.state;
    const { externalPersonManageStore: { addForm } } = this.props;
    addForm.resetForm();
    this.setState({
      externalPersonManagePayload: {
        ...externalPersonManagePayload,
        visible: false, title: "新建", id: ""
      }
    }, () => isRefresh && this.listPage());
  };
  handleAdd = (id = "") => {
    const { externalPersonManagePayload } = this.state;
    this.setState({
      externalPersonManagePayload: {
        ...externalPersonManagePayload,
        visible: true, id, title: id ? "编辑" : "新建"
      }
    });
  };
  getColumns = () => {
    const { columns } = this.state;
    return _.map(_.filter(columns, item => !!item.display), child => ({
      ...child,
      render: (text) => {
        return <span className="ellipsis" title={text}>{text}</span>;
      }
    }));
  };
  onDropMenuClick = (key, targetid = "") => {
    switch (key) {
      case "log":
        this.setState({
          logDialogVisible: true,
          filterConditions: targetid ? `[{\"connectCondition\":\"AND\",\"columIndex\":\"targetid\",\"type\":\"=\",\"value\":\"${targetid}\"}]` : "[]"
        });
        break;
      default:
        break;
    }
  };

  render() {
    const {
      showSearchAd, externalPersonManagePayload, loading, logDialogVisible, filterConditions,
      pageInfo, selectedRowKeys, dataSource, externalPersonImportPayload
    } = this.state;
    const {
      externalPersonManageStore: { form, addForm },
      taxAgentStore: { showOperateBtn, showSalaryItemBtn }
    } = this.props;
    const pagination = {
      current: pageInfo.current,
      pageSize: pageInfo.pageSize,
      total: pageInfo.total,
      showTotal: total => `共 ${total} 条`,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ["10", "20", "50", "100"],
      onShowSizeChange: (current, pageSize) => {
        this.setState({ pageInfo: { ...pageInfo, current, pageSize } }, () => this.listPage());
      },
      onChange: current => {
        this.setState({ pageInfo: { ...pageInfo, current } }, () => this.listPage());
      }
    };
    const rowSelection = {
      selectedRowKeys,
      onChange: selectedRowKeys => this.setState({ selectedRowKeys })
    };
    return (
      <div className="externalPerWrapper">
        <WeaTop
          title="非系统人员管理" icon={<i className="icon-coms-fa"/>}
          iconBgcolor="#F14A2D" showDropIcon onDropMenuClick={this.onDropMenuClick}
          dropMenuDatas={[
            {
              key: "log", icon: <i className="iconfont icon-caozuorizhi32"/>,
              content: getLabel(545781, "操作日志")
            }
          ]}
        >
          <div className="externalPerCont">
            <WeaTab
              buttons={(showOperateBtn || showSalaryItemBtn) ? [
                <WeaHelpfulTip
                  title={getLabel(111, "非系统人员，且需要缴纳社保福利以及代发工资的人员，需在本表维护人员信息")}
                  placement="topRight"
                />,
                <Button type="ghost" onClick={() => this.setState({
                  externalPersonImportPayload: {
                    ...externalPersonImportPayload,
                    visiable: true,
                    step: 0
                  }
                })}>{getLabel(32935, "导入")}</Button>,
                <Button type="primary" onClick={() => this.handleAdd()}>新建</Button>
              ] : [
                <WeaHelpfulTip
                  title={getLabel(111, "非系统人员，且需要缴纳社保福利以及代发工资的人员，需在本表维护人员信息")}
                  placement="topRight"
                />
              ]}
              searchType={["base", "advanced"]} showSearchAd={showSearchAd}
              setShowSearchAd={(showSearchAd) => this.setState({ showSearchAd })}
              searchsAd={getSearchs(form, searchCondition, 2)}
              searchsBasePlaceHolder="请输入姓名" onSearch={this.listPage}
              onSearchChange={username => form.updateFields({ username })}
              searchsBaseValue={form.getFormParams().username}
              onAdSearch={() => this.setState({ showSearchAd: false }, () => this.listPage())}
              onAdReset={() => form.resetForm()} onAdCancel={() => this.setState({ showSearchAd: false })}
            />
            <WeaTable
              rowKey="id"
              loading={loading}
              columns={(showOperateBtn || showSalaryItemBtn) ? [
                ...this.getColumns(),
                {
                  dataIndex: "operate",
                  title: "操作",
                  width: 120,
                  render: (_, { id }) => (
                    <React.Fragment>
                      <a href="javascript: void(0);" onClick={() => this.handleAdd(id)}
                         style={{ paddingRight: 8 }}>编辑</a>
                      <Dropdown
                        overlay={
                          <Menu>
                            <Menu.Item>
                              <a href="javascript:void(0);"
                                 onClick={() => this.onDropMenuClick("log", id)}>{getLabel(545781, "操作日志")}</a>
                            </Menu.Item>
                          </Menu>
                        }>
                        <a href="javascript:void(0)"><i className="icon-coms-more"/></a>
                      </Dropdown>
                      {/*<a href="javascript: void(0);" onClick={() => this.handleDelete(id)}>删除</a>*/}
                    </React.Fragment>
                  )
                }
              ] : []}
              dataSource={dataSource}
              pagination={pagination}
              rowSelection={rowSelection}
              xWidth={800}
            />
            <ExternalPersonManageEditSlide
              showOperateBtn={showOperateBtn || showSalaryItemBtn} form={addForm} condition={condition}
              onCancel={this.handleCancel} {...externalPersonManagePayload}
            />
            {
              externalPersonImportPayload.visiable &&
              <ExternalPersonImport
                {...externalPersonImportPayload}
                setStep={(step) => {
                  this.setState({ externalPersonImportPayload: { ...externalPersonImportPayload, step } });
                }}
                onCancel={() => {
                  this.setState({
                    externalPersonImportPayload: {
                      ...externalPersonImportPayload,
                      visiable: false,
                      step: 0
                    }
                  });
                }}
                onFinish={() => {
                  this.setState({
                    externalPersonImportPayload: {
                      ...externalPersonImportPayload,
                      visiable: false, step: 0
                    }
                  }, () => this.listPage());
                }}
              />
            }
          </div>
          {/*操作日志*/}
          <LogDialog visible={logDialogVisible} logFunction="extemployee" filterConditions={filterConditions}
                     onCancel={() => this.setState({ logDialogVisible: false })}/>
        </WeaTop>
      </div>
    );
  }
}

export default Index;
