import React, { useEffect, useRef, useReducer } from "react";
import { Button } from "antd";
import AutoTable from "@/components/AutoTable";
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 DrawInitForm from "@/components/DrawInitForm";
const initState = {
  vs: false,
  fields: {},
  iftype: {},
  curitem: {},
};
function reducer(state, action) {
  let { type } = action,
    newState = {};
  switch (type) {
    case "add":
      newState = {
        ...state,
        vs: true,
        iftype: {
          title: "新增组织",
          val: type,
        },
        fields: { ...action.fields },
        curitem: action.curitem,
      };
      break;
    case "addDepart":
      newState = {
        ...state,
        vs: true,
        iftype: {
          title: `新增 ${action.curitem.title} 下的组织`,
          val: type,
        },
        fields: { ...action.fields },
        curitem: action.curitem,
      };
      break;
    case "edit":
      newState = {
        ...state,
        vs: true,
        iftype: {
          title: "编辑组织",
          val: type,
        },
        fields: { ...action.fields },
        curitem: action.curitem,
      };
      break;
    case "close":
      newState = {
        vs: false,
        fields: {},
        iftype: {},
        curitem: {},
      };
      break;
  }

  return newState;
}

const Jiagou = (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 } = state,
    columns = [
      {
        title: "组织",
        dataIndex: "title",
        key: "departmentName",
      },
      {
        title: "组织类型",
        dataIndex: "departmentType",
        key: "departmentType",
        render: (text, record) => (
          <span>{record.departmentType == 0 ? "集团类型" : "组织类型"}</span>
        ),
        search: false,
      },
      {
        title: "组织代码",
        dataIndex: "departmentCode",
        key: "departmentCode",
        search: false,
      },
      {
        title: "操作",
        dataIndex: "option_dataindex",
        key: "option_dataindex",
        valueType: "option",
        width: 215,
        render: (text, row, _, action) => extraAction(text, row, _, action),
      },
    ];

  function extraAction(text, record, _, action) {
    let ifs = record.children;
    return [
      getPrem("sysDepartment_save", action, "新增", () => {
        for (let i in defaultFields) {
          defaultFields[i].value = null;
        }
        dispatch({ type: "addDepart", fields: defaultFields, curitem: record });
      }),
      getPrem("sysDepartment_save", action, "修改", () => {
        for (let i in defaultFields) {
          defaultFields[i].value = record[i];
          if (i == "departmentName") {
            defaultFields[i].value = record.title;
          }
        }
        dispatch({ type: "edit", fields: defaultFields, curitem: record });
      }),
      !ifs &&
        getPrem("sysDepartment_deleteById", action, "删除", null, {
          title: "确认删除该组织？",
          onConfirm: () => {
            run({
              url: "/ngic-auth/sysDepartment/deleteById",
              params: { id: record.key },
            });
          },
        }),
    ];
  }
  let saveData = (values, fn) => {
    let newfields = JSON.parse(JSON.stringify(values));
    //新增&修改
    let difrid =
      iftype.val == "edit" ? { id: curitem.key } : { parentId: curitem.key };
    run({
      url: "/ngic-auth/sysDepartment/save",
      params: { ...newfields, ...difrid },
    });
  };
  let extrarender = [
    <Button
      disabled={!getPrem("sysDepartment_save", "ifs")}
      type="primary"
      onClick={() => {
        for (let i in defaultFields) {
          defaultFields[i].value = null;
        }
        dispatch({ type: "add", fields: defaultFields, curitem: { key: 0 } });
      }}
    >
      新增
    </Button>,
  ];
  return (
    <div>
      <AutoTable
        pagetitle={props.route.name} //页面标题
        pageextra={extrarender} //页面操作 新增or批量删除
        columns={columns}
        rowKey="key"
        path="/ngic-auth/sysDepartment/query/tree"
        pagination="false"
        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}
      ></DrawInitForm>
    </div>
  );
};
export default Jiagou;
