import React, { useEffect, useRef, useReducer } from "react";
import { Button, Tooltip, Row, Divider, message } from "antd";
import AutoTable from "@/components/AutoTable";
import getPrem from "@/utils/getPrem"; //权限判断fn
import { useRequest } from "umi";
import defaultFields from "./fields";
import { doFetch } from "@/utils/doFetch";
import DrawInitForm from "@/components/DrawInitForm";
import { userDetails, userCheckDetails } from "@/utils/detailTotalCard";
import Details from "@/components/Details";
import { userSelect } from "@/services/system";
const initState = {
  vs: false,
  fields: {},
  iftype: {},
  curitem: {},
  detail: {
    dataSource: {},
    totalCard: [],
  },
  visible: false,
  extraparams: {
    orderType: "1",
  },
},
  tabList = [
    {
      key: "1",
      tab: "正式用户",
    },
    {
      key: "2",
      tab: "用户申请",
    },
  ];
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 "audit":
      newState = {
        ...state,
        vs: true,
        iftype: {
          title: "审批用户",
          val: type,
        },
        fields: { ...action.fields },
        curitem: action.curitem,
      };
      break;
    case "see":
      newState = {
        ...state,
        detail: {
          dataSource: action.dataSource,
          totalCard: action.totalCard,
        },
        visible: true,
      };
      break;
    case "start":
      newState = {
        ...state,
        extraparams: {
          orderType: action.tabKey,
        },
      };
      break;
    case "close":
      newState = {
        ...state,
        vs: false,
        fields: {},
        iftype: {},
        curitem: {},
        detail: {
          dataSource: {},
          totalCard: [],
        },
        visible: false,
      };
      break;
  }

  return newState;
}
const Staff = (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") {
        reload();
        dispatch({ type: "close" });
      }
    },
  }),
    [state, dispatch] = useReducer(reducer, initState),
    { vs, fields, iftype, curitem, detail, visible, extraparams } = state,
    columns = [
      {
        title: "用户名",
        dataIndex: "accountName",
        key: "accountName",
      },
      {
        title: "姓名",
        dataIndex: "userName",
        key: "userName",
        render: (_, row) => {
          return (
            <Tooltip title={row.userName}>
              <a
                className="table-cell"
                onClick={() => {
                  doFetch({
                    url: "/ngic-auth/sysUser/query/detail",
                    params: { id: row.id },
                  }).then((res) => {
                    if (res.code == "0000") {
                      let dataSource = res?.data?.data ?? {},
                        totalCard = [...userDetails];
                      dataSource.genderName =
                        dataSource.gender == 1
                          ? "男"
                          : dataSource.gender == 2
                            ? "女"
                            : "-";
                      dispatch({ type: "see", dataSource, totalCard });
                    }
                  });
                }}
              >
                {row.userName}
              </a>
            </Tooltip>
          );
        },
      },
      {
        title: "组织",
        dataIndex: "departmentName",
        key: "departmentName",
      },
      {
        title: "工厂",
        dataIndex: "factoryName",
        key: "factoryName",
      },
      {
        title: "负责仓库",
        dataIndex: "chargeStoreName",
        key: "chargeStoreName",
      },
      {
        title: "角色",
        dataIndex: "roleName",
        key: "roleName",
      },
      {
        title: "联系电话",
        dataIndex: "telephone",
        key: "telephone",
      },
      {
        title: "操作",
        dataIndex: "option_dataindex",
        key: "option_dataindex",
        valueType: "option",
        width: 225,
        render: (text, row, _, action) => extraAction(text, row, _, action),
      },
    ],
    columnsc = [
      {
        title: "用户名",
        dataIndex: "accountName",
        key: "accountName",
      },
      {
        title: "姓名",
        dataIndex: "userName",
        key: "userName",
        render: (_, row) => {
          return (
            <Tooltip title={row.userName}>
              <a
                className="table-cell"
                onClick={() => {
                  doFetch({
                    url: "/ngic-auth/sysAccountApply/queryById",
                    params: { id: row.id },
                  }).then((res) => {
                    if (res.code == "0000") {
                      let dataSource = res?.data?.data ?? {},
                        totalCard = [...userCheckDetails];
                      dataSource.genderName =
                        dataSource.gender == 1
                          ? "男"
                          : dataSource.gender == 2
                            ? "女"
                            : "-";
                      dispatch({ type: "see", dataSource, totalCard });
                    }
                  });
                }}
              >
                {row.userName}
              </a>
            </Tooltip>
          );
        },
      },
      {
        title: "组织",
        dataIndex: "departmentName",
        key: "departmentName",
      },
      {
        title: "工厂",
        dataIndex: "factoryName",
        key: "factoryName",
      },
      {
        title: "负责仓库",
        dataIndex: "chargeStoreName",
        key: "chargeStoreName",
      },

      {
        title: "角色",
        dataIndex: "roleName",
        key: "roleName",
      },
      {
        title: "联系电话",
        dataIndex: "telephone",
        key: "telephone",
      },
      {
        title: "审批结果",
        dataIndex: "auditResultName",
        key: "auditResultName",
        valueType: "select",
        options: [
          {
            label: "通过",
            value: 1,
          },
          {
            label: "不通过",
            value: 2,
          },
        ],
        formItemProps: {
          name: "auditResult",
        },
      },
      {
        title: "工单状态",
        dataIndex: "statusName",
        key: "statusName",
        valueType: "select",
        options: [
          {
            label: "待审批",
            value: 1,
          },
          {
            label: "已审批",
            value: 2,
          },
        ],
        formItemProps: {
          name: "status",
        },
      },
      {
        title: "操作",
        dataIndex: "option_dataindex",
        key: "option_dataindex",
        valueType: "option",
        width: 150,
        render: (text, row, _, action) => extraAction(text, row, _, action),
      },
    ];
  function extraAction(text, record, _, action) {
    return [
      extraparams.orderType == "1" &&
      getPrem("sysUser_restPassword", action, "重置密码", null, {
        title: "确认重置密码?",
        onConfirm: () => {
          doFetch({
            url: "/ngic-auth/sysUser/restPassword",
            params: { id: record.id },
          }).then((res) => {
            if (res.code == "0000") {
              message.success(res.msg);
              reload();
            }
          });
        },
      }),
      extraparams.orderType == "1" &&
      getPrem("sysDepartment_save", action, "修改", () => {
        doFetch({
          url: "/ngic-auth/sysUser/query/detail",
          params: { id: record.id },
        }).then((res) => {
          if (res.code == "0000") {
            let data = res?.data?.data ?? {};
            for (let i in defaultFields) {
              defaultFields[i].value = data[i];
              if (i == "parentId") {
                defaultFields[i].belinked = {
                  options: {
                    database: userSelect,
                    params: { id: record.id },
                  },
                };
              }
            }
            dispatch({
              type: "edit",
              fields: { ...defaultFields },
              curitem: data,
            });
          }
        });
      }),
      extraparams.orderType == "1" &&
      getPrem("sysDepartment_deleteById", action, "删除", null, {
        title: "确认删除该用户?",
        onConfirm: () => {
          run({
            url: "/ngic-auth/sysUser/deleteById",
            params: { id: record.id },
          });
        },
      }),
      extraparams.orderType == "2" &&
      record.status == 1 &&
      getPrem("sysDepartment_save", action, "审批", () => {
        doFetch({
          url: "/ngic-auth/sysAccountApply/queryById",
          params: { id: record.id },
        }).then((res) => {
          if (res.code == "0000") {
            message.success(res.msg);

            let data = res?.data?.data ?? {};
            for (let i in defaultFields) {
              defaultFields[i].value = data[i];
              if (i == "parentId") {
                defaultFields[i].belinked = {
                  options: {
                    database: userSelect,
                    params: { id: record.id },
                  },
                };
              }
            }
            let newParams = {
              remark: {
                value: data.remark,
                type: "textarea",
                title: "备注",
                name: ["remark"],
                required: false,
                col: { span: 24 },
              },
              applyTime: {
                value: data.applyTime,
                type: "datepicker",
                title: "申请时间",
                name: ["applyTime"],
                required: false,
                disabled: true,
              },
              auditResult: {
                value: null,
                type: "select",
                title: "审批结果",
                name: ["auditResult"],
                required: true,
                options: [
                  {
                    label: "通过",
                    value: 1,
                  },
                  {
                    label: "不通过",
                    value: 2,
                  },
                ],
                linked: true,
              },
              auditOpinion: {
                value: null,
                type: "textarea",
                title: "审批意见",
                name: ["auditOpinion"],
                required: true,
                col: { span: 24 },
                belinked: {
                  hides: [
                    {
                      name: "auditResult",
                      equalvalue: [1, null],
                      required: true,
                    },
                  ],
                },
              },
            };
            dispatch({
              type: "audit",
              fields: { ...defaultFields, ...newParams },
              curitem: data,
            });
          }
        });
      }),
    ];
  }
  let saveData = (values, fn) => {
    let newfields = JSON.parse(JSON.stringify(values));
    //新增&修改
    let difrid = iftype.val != "add" ? { id: curitem.id } : {};
    run({
      url:
        iftype.val == "audit"
          ? "/ngic-auth/sysAccountApply/audit"
          : "/ngic-auth/sysUser/save",
      params: { ...newfields, ...difrid },
    });
  };
  let extrarender = [
    <Button
      disabled={!getPrem("sysDepartment_save", "ifs")}
      type="primary"
      onClick={() => {
        for (let i in defaultFields) {
          defaultFields[i].value = i.indexOf("List") != -1 ? [] : "";
        }
        dispatch({ type: "add", fields: defaultFields });
      }}
    >
      新增
    </Button>,
  ];
  return (
    <div>
      {extraparams.orderType == "1" && (
        <AutoTable
          pagetitle={props.route.name} //页面标题
          pageextra={extrarender} //页面操作 新增or批量删除
          columns={columns}
          actionRef={actionRef}
          onRef={(node) => (ChildRef = node)}
          tabList={tabList}
          activeTabKey={extraparams.orderType}
          onTabChange={(key) => {
            dispatch({ type: "start", tabKey: key });
          }}
          path={"/ngic-auth/sysUser/query/page"}
        ></AutoTable>
      )}
      {extraparams.orderType == "2" && (
        <AutoTable
          pagetitle={props.route.name} //页面标题
          columns={columnsc}
          actionRef={actionRef}
          onRef={(node) => (ChildRef = node)}
          tabList={tabList}
          activeTabKey={extraparams.orderType}
          onTabChange={(key) => {
            dispatch({ type: "start", tabKey: key });
          }}
          path={"/ngic-auth/sysAccountApply/queryList"}
        ></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={"60%"}
      ></DrawInitForm>
      <Details
        title="用户详情"
        visible={visible}
        onClose={() => dispatch({ type: "close" })}
        footer={false}
        destroyOnClose={true}
        width={"100%"}
        {...detail}
      ></Details>
    </div>
  );
};
export default Staff;