/*
  *  角色管理
  *
  * @Author:    黎永顺
  * @Date:      2024/9/6
  * @Wechat:
  * @Email:     971387674@qq.com
  * @description:
*/
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaLocaleProvider, WeaTable, WeaTop } from "ecCom";
import { Button, Dropdown, Menu, message, Modal } from "antd";
import * as API from "../../apis/taxAgent";
import AddRoleDialog from "./components/addRoleDialog";
import RoleDetailSetDialog from "./components/roleDetailSetDialog";
import AdvanceInputBtn from "./components/advanceInputBtn";
import AdvanceSearchPannel from "./components/advanceSearchPannel";
import LogDialog from "../../components/logViewModal";
import cs from "classnames";
import "./index.less";

const getLabel = WeaLocaleProvider.getLabel;

@inject("taxAgentStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [], columns: [], pageInfo: { current: 1, pageSize: 10, total: 0 },
      loading: false, selectedRowKeys: [], addRoleDialog: { taxAgentId: "", visible: false },
      logDialogVisible: false, filterConditions: "", showSearchAd: false, syncLoading: false,
      roleSetDialog: {
        visible: false, roleId: "", name: "", selectedKey: "",
        counts: { datas: 0, members: 0, resources: 0, opts: 0 }
      }
    };
  }

  componentDidMount() {
    this.getRoleList();
  }

  syncAuth = () => {
    this.setState({ syncLoading: true });
    API.syncAuth().then(({ status, errormsg }) => {
      this.setState({ syncLoading: false });
      if (status) {
        message.success(getLabel(111, "操作成功！"));
        this.getRoleList();
      } else {
        message.error(errormsg);
      }
    });
  };
  getRoleList = () => {
    const { taxAgentStore: { advanceForm } } = this.props, { pageInfo } = this.state;
    const paylaod = {
      ...pageInfo, ...advanceForm.getFormParams(),
      employeeIds: !_.isEmpty(advanceForm.getFormParams()["employeeIds"]) ? advanceForm.getFormParams()["employeeIds"].split(",") : [],
      opts: !_.isEmpty(advanceForm.getFormParams()["opts"]) ? advanceForm.getFormParams()["opts"].split(",") : [],
      roleEmpIds: !_.isEmpty(advanceForm.getFormParams()["roleEmpIds"]) ? advanceForm.getFormParams()["roleEmpIds"].split(",") : [],
      sobIds: !_.isEmpty(advanceForm.getFormParams()["sobIds"]) ? advanceForm.getFormParams()["sobIds"].split(",") : [],
      taxAgentIds: !_.isEmpty(advanceForm.getFormParams()["taxAgentIds"]) ? advanceForm.getFormParams()["taxAgentIds"].split(",") : [],
      pages: !_.isEmpty(advanceForm.getFormParams()["pages"]) ? advanceForm.getFormParams()["pages"].split(",") : []
    };
    this.setState({ loading: true });
    API.getRoleList(paylaod).then(({ status, data }) => {
      this.setState({ loading: false });
      if (status) {
        const { list: dataSource, columns, pageNum: current, pageSize, total } = data;
        this.setState({
          dataSource, pageInfo: { ...pageInfo, current, pageSize, total },
          columns: [..._.map(columns, o => {
            if (
              o.dataIndex === "resources" || o.dataIndex === "members" ||
              o.dataIndex === "opts" || o.dataIndex === "datas"
            ) {
              const tabsKey = {
                resources: "baseinfo",
                members: "auth.MemberTargetTypeEnum",
                opts: "auth.AuthTargetTypeEnum",
                datas: "auth.DataTargetTypeEnum"
              };
              return {
                ...o, render: (text, record) => (
                  <a href="javascript:void(0)" style={{ marginRight: 10 }} onClick={() => this.showRoleSetDialog({
                    ...record, selectedKey: tabsKey[o.dataIndex]
                  })}>{text}</a>)
              };
            }
            return { ...o };
          }), {
            title: getLabel(111, "操作"), width: 150, dataIndex: "action",
            render: (__, record) => (
              <React.Fragment>
                <a href="javascript:void(0)" style={{ marginRight: 10 }}
                   onClick={() => this.showRoleSetDialog(record)}>{getLabel(111, "编辑")}</a>
                <a href="javascript:void(0)" style={{ marginRight: 10 }}
                   onClick={() => this.deleteAuthRole([record.id])}>{getLabel(111, "删除")}</a>
                <Dropdown overlay={
                  <Menu onClick={e => this.handleDropMenuClick(e.key, record.id)}>
                    <Menu.Item key="log">{getLabel(545781, "操作日志")}</Menu.Item>
                  </Menu>
                }>
                  <a href="javascript:void(0);"><i className="icon-coms-more"/></a>
                </Dropdown>
              </React.Fragment>
            )
          }]
        }, () => {
          const { roleSetDialog, dataSource } = this.state;
          roleSetDialog.roleId && this.setState({
            roleSetDialog: {
              ...roleSetDialog, counts: {
                ...roleSetDialog.counts, ..._.reduce(_.keys(roleSetDialog.counts), (pre, cur) => ({
                  ...pre, [cur]: _.find(dataSource, o => o.id === roleSetDialog.roleId)[cur] || 0
                }), {})
              }
            }
          });
        });
      }
    });
  };
  showRoleSetDialog = (role) => this.setState({
    roleSetDialog: {
      visible: true, roleId: role.id, name: role.name, selectedKey: role.selectedKey,
      counts: {
        ...this.state.roleSetDialog.counts, ..._.reduce(_.keys(this.state.roleSetDialog.counts), (pre, cur) => ({
          ...pre, [cur]: role[cur] || 0
        }), {})
      }
    }
  });
  deleteAuthRole = (payload) => {
    Modal.confirm({
      title: getLabel(111, "信息确认"),
      content: getLabel(111, "确认要删除吗?"),
      onOk: () => {
        API.deleteAuthRole(payload).then(({ status, errormsg }) => {
          if (status) {
            message.success(getLabel(111, "操作成功！"));
            this.setState({ selectedRowKeys: [] }, () => this.getRoleList());
          } else {
            message.error(errormsg);
          }
        });
      }
    });
  };
  handleDropMenuClick = (key, targetid = "") => {
    switch (key) {
      case "log":
        this.setState({
          logDialogVisible: true,
          filterConditions: targetid ? `[{\"connectCondition\":\"AND\",\"columIndex\":\"targetid\",\"type\":\"=\",\"value\":\"${targetid}\"}]` : "[]"
        });
        break;
      default:
        break;
    }
  };

  render() {
    const {
      dataSource, columns, pageInfo, loading, selectedRowKeys, addRoleDialog, roleSetDialog,
      logDialogVisible, filterConditions, showSearchAd, syncLoading
    } = this.state;
    const { taxAgentStore: { PageAndOptAuth } } = this.props;
    const admin = PageAndOptAuth.opts.includes("admin");
    const dropMenuDatas = [{
      key: "log", icon: <i className="iconfont icon-caozuorizhi32"/>,
      content: getLabel(545781, "操作日志")
    }];
    let buttons = [
      <Button type="primary" onClick={() => this.setState({
        addRoleDialog: { taxAgentId: "", visible: true }
      })}>{getLabel(111, "新建")}</Button>,
      <Button type="ghost" loading={syncLoading} onClick={this.syncAuth}>{getLabel(111, "同步")}</Button>,
      <Button type="ghost" disabled={_.isEmpty(selectedRowKeys)}
              onClick={() => this.deleteAuthRole(selectedRowKeys)}>{getLabel(111, "批量删除")}</Button>,
      <AdvanceInputBtn onOpenAdvanceSearch={() => this.setState({ showSearchAd: true })}
                       onAdvanceSearch={() => this.setState({ pageInfo: { ...pageInfo, current: 1 } },
                         () => this.getRoleList())}/>
    ];
    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.getRoleList());
      },
      onChange: current => {
        this.setState({ pageInfo: { ...pageInfo, current } }, () => this.getRoleList());
      }
    };
    const rowSelection = {
      selectedRowKeys, onChange: (selectedRowKeys) => this.setState({ selectedRowKeys })
    };
    !admin && (buttons = buttons.slice(-1));
    return (
      <WeaTop title={getLabel(111, "业务线管理")} icon={<i className="icon-coms-Flow-setting"/>} iconBgcolor="#F14A2D"
              buttons={buttons} className="rolemanagement-index" showDropIcon dropMenuDatas={dropMenuDatas}
              onDropMenuClick={this.handleDropMenuClick}>
        <div className="rolemanagement-content">
          <div
            className={cs("searchAdvanced-condition-container", { "searchAdvanced-condition-hide": !showSearchAd })}>
            <AdvanceSearchPannel onCancel={() => this.setState({ showSearchAd: false })}
                                 onAdSearch={() => this.setState({
                                   showSearchAd: false, pageInfo: { ...pageInfo, current: 1 }
                                 }, () => this.getRoleList())}/>
          </div>
          <WeaTable dataSource={dataSource} columns={columns} pagination={pagination} loading={loading}
                    rowSelection={rowSelection} scroll={{ y: `calc(100vh - 173px)` }} rowKey="id"/>
          {/*添加角色*/}
          <AddRoleDialog {...addRoleDialog} onSearch={this.getRoleList}
                         showRoleSetDialog={this.showRoleSetDialog}
                         onCancel={callback => this.setState({
                           addRoleDialog: { ...addRoleDialog, visible: false }
                         }, () => callback && callback())}/>
          {/*角色详情设置*/}
          <RoleDetailSetDialog {...roleSetDialog} onSearch={this.getRoleList}
                               onCancel={callback => this.setState({
                                 roleSetDialog: { ...roleSetDialog, visible: false, roleId: "" }
                               }, () => {
                                 this.props.taxAgentStore.initRoleForm();
                                 callback && callback();
                               })}/>
        </div>
        {/*操作日志*/}
        <LogDialog visible={logDialogVisible} logFunction="authlink" filterConditions={filterConditions}
                   onCancel={() => this.setState({ logDialogVisible: false })}/>
      </WeaTop>
    );
  }
}

export default Index;
