import React, { useEffect, useRef, useReducer } from "react";
import { Modal, Button, Drawer, Dropdown, Menu } from "antd";
import AutoTable from "@/components/AutoTable";
import Tables from "@/components/Tableform";
import getPrem from "@/utils/getPrem"; //权限判断fn
import InitForm from "@/components/InitForm";
import { useRequest } from "umi";
import defaultFields from "./fields";
import { doFetch } from "@/utils/doFetch";
import Permissiontree from "./Permissiontree";
import DrawInitForm from "@/components/DrawInitForm";
const initState = {
  vs: false,
  fields: {},
  iftype: {},
  curitem: {},
  visible: false,
};
function reducer(state, action) {
  let { type } = action,
    newState = {};
  switch (type) {
    case "add":
      newState = {
        ...state,
        vs: true,
        iftype: {
          title: "新增角色",
          val: type,
        },
        fields: { ...action.fields },
      };
      break;
    case "edit":
      newState = {
        ...state,
        vs: true,
        iftype: {
          title: "编辑角色",
          val: type,
        },
        fields: { ...action.fields },
        curitem: action.curitem,
      };
      break;
    case "auth":
      newState = {
        ...state,
        visible: true,
        iftype: {
          title: action.title,
          val: type,
        },
        curitem: action.curitem,
      };
      break;
    case "dataauth":
      newState = {
        ...state,
        vs: true,
        iftype: {
          title: action.title,
          val: type,
        },
        fields: { ...action.fields },
        curitem: action.curitem,
      };
      break;
    case "staff":
      newState = {
        ...state,
        visible: true,
        iftype: {
          title: action.title,
          val: type,
        },
        curitem: action.curitem,
      };
      break;
    case "close":
      newState = {
        vs: false,
        fields: {},
        iftype: {},
        curitem: {},
        details: {
          dataSource: {},
          totalCard: [],
          visible: false,
        },
      };
      break;
  }

  return newState;
}

const Charactor = (props) => {
  let actionRef = useRef(),
    ChildRef = null;
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }
  const { run, loading } = useRequest(doFetch, {
      manual: true,
      formatResult: (res) => res,
      onSuccess: (result, params) => {
        if (result.code == "0000") {
          closeTree();
        }
      },
    }),
    [state, dispatch] = useReducer(reducer, initState),
    { vs, fields, iftype, curitem, visible } = state,
    columns = [
      {
        title: "角色名称",
        dataIndex: "roleName",
        key: "roleName",
      },
      {
        title: "角色描述",
        dataIndex: "remark",
        key: "remark",
        search: false,
      },
      {
        title: "操作",
        valueType: "option",
        dataIndex: "option_dataindex",
        key: "option_dataindex",
        width: 215,
        render: (text, row, _, action) => extraAction(text, row, _, action),
      },
    ],
    columnsc = [
      {
        title: "用户名",
        dataIndex: "accountName",
        key: "accountName",
      },
      {
        title: "姓名",
        dataIndex: "userName",
        key: "userName",
      },
      {
        title: "工厂",
        dataIndex: "factoryName",
        key: "factoryName",
      },
      {
        title: "组织",
        dataIndex: "departmentName",
        key: "departmentName",
      },
      // {
      //   title: "负责车间",
      //   dataIndex: "shopNames",
      //   key: "shopNames",
      // },
      // {
      //   title: "负责产线",
      //   dataIndex: "productionLines",
      //   key: "productionLines",
      // },
      // {
      //   title: "负责工段",
      //   dataIndex: "sectionNames",
      //   key: "sectionNames",
      // },
    ];

  function extraAction(text, record, _, action) {
    return [
      getPrem("sysRole_save", action, "修改", () => {
        for (let i in defaultFields) {
          defaultFields[i].value = record[i];
        }
        dispatch({ type: "edit", fields: defaultFields, curitem: record });
      }),
      getPrem("sysRole_deleteById", action, "删除", null, {
        title: "确认删除该用户？",
        onConfirm: () => {
          run({
            url: "/ngic-auth/sysRole/deleteById",
            params: { id: record.id },
          });
        },
      }),
      <Dropdown
        overlay={
          <Menu>
            <Menu.Item key="key1">
              {getPrem("sysRolePermission_save", null, "授权配置", () => {
                dispatch({
                  type: "auth",
                  title: `${record.roleName}-权限配置`,
                  curitem: record,
                });
              })}
            </Menu.Item>
            {/* <Menu.Item key="key2">
              {getPrem(true, null, "数据分权", () => {
                dispatch({ type: "dataauth", title: `给${record.roleName}添加数据权限`, curitem: record })
              })}
            </Menu.Item> */}
            <Menu.Item key="key3">
              {getPrem(true, null, "人员", () => {
                dispatch({
                  type: "staff",
                  curitem: record,
                  title: `拥有${record.roleName}角色 的人员列表`,
                });
              })}
            </Menu.Item>
          </Menu>
        }
      >
        {getPrem(true, action, "更多...", null, null)}
      </Dropdown>,
    ];
  }
  let saveData = (values, fn) => {
    let newfields = JSON.parse(JSON.stringify(values));
    //新增&修改
    let difrid = iftype.val == "edit" ? { id: curitem.id } : {};
    run({
      url: "/ngic-auth/sysRole/save",
      params: { ...newfields, ...difrid },
    });
  };
  let extrarender = [
    <Button
      disabled={!getPrem("sysRole_save", "ifs")}
      type="primary"
      onClick={() => {
        for (let i in defaultFields) {
          defaultFields[i].value = i.indexOf("List") != -1 ? [] : "";
        }
        dispatch({ type: "add", fields: defaultFields });
      }}
    >
      新增
    </Button>,
  ];
  const closeTree = () => {
    dispatch({ type: "close" });
    reload();
  };
  return (
    <div>
      <AutoTable
        pagetitle={props.route.name} //页面标题
        pageextra={extrarender} //页面操作 新增or批量删除
        columns={columns}
        path="/ngic-auth/sysRole/queryList"
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
      ></AutoTable>
      <DrawInitForm
        title={iftype.title}
        visible={vs}
        onClose={() => dispatch({ type: "close" })}
        footer={false}
        destroyOnClose={true}
        fields={fields}
        submitData={(values) => {
          saveData(values);
        }}
        onChange={(changedValues, allValues) => {
          //联动操作
        }}
        submitting={loading || !vs}
        width={iftype.val == "staff" || iftype.val == "auth" ? "70%" : "50%"}
      ></DrawInitForm>

      <Drawer
        title={iftype.title}
        visible={visible}
        onClose={() => dispatch({ type: "close" })}
        footer={false}
        destroyOnClose={true}
        width={iftype.val == "staff" || iftype.val == "auth" ? "70%" : "50%"}
      >
        {iftype.val == "auth" || iftype.val == "dataauth" ? (
          <Permissiontree
            {...curitem}
            close={closeTree}
            treeType={iftype.val}
          />
        ) : iftype.val == "staff" ? (
          <Tables
            columns={columnsc}
            extraparams={{ roleId: curitem.id }}
            path="/ngic-auth/sysUser/query/pageByRoleId"
          ></Tables>
        ) : (
          <></>
        )}
      </Drawer>
    </div>
  );
};
export default Charactor;
