import React, { useEffect, useRef, useReducer } from "react";
import { Button, Tooltip, Row, Divider, Drawer } 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 Details from "@/components/Details";
import { shiftgroupDetail } from "@/utils/detailTotalCard";
import Coltext from "@/components/Coltext";
import TableTransfer from "@/components/TableTransfer";
const initState = {
  vs: false,
  fields: {},
  iftype: {},
  curitem: {},
  detail: {
    dataSource: {},
    totalCard: [],
  },
  visible: false,
  vsc: false,
  transferParams: {},
};
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 "see":
      newState = {
        ...state,
        detail: {
          dataSource: action.dataSource,
          totalCard: [...shiftgroupDetail],
        },
        visible: true,
      };
      break;
    case "station":
      newState = {
        ...state,
        vsc: true,
        transferParams: action.transferParams,
      };
      break;
    case "close":
      newState = {
        vs: false,
        fields: {},
        iftype: {},
        curitem: {},
        detail: {
          dataSource: {},
          totalCard: [],
        },
        visible: false,
        vsc: false,
        transferParams: {},
      };
      break;
  }

  return newState;
}

const Shiftgroup = (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, vsc, transferParams } =
      state,
    columns = [
      {
        title: "班组编号",
        dataIndex: "groupNo",
        key: "groupNo",
      },
      {
        title: "班组名称",
        dataIndex: "groupName",
        key: "groupName",
        render: (_, row) => {
          return (
            <Tooltip title={row.groupName}>
              <a
                className="table-cell"
                onClick={() => {
                  doFetch({
                    url: "/ngic-auth/sysGroup/queryById",
                    params: { id: row.id },
                  }).then((res) => {
                    if (res.code == "0000") {
                      let dataSource = res?.data?.data ?? {};
                      dispatch({ type: "see", dataSource });
                    }
                  });
                }}
              >
                {row.groupName}
              </a>
            </Tooltip>
          );
        },
      },
      {
        title: "所属工厂",
        dataIndex: "factoryName",
        key: "factoryName",
        search: false,
      },
      {
        title: "所属车间",
        dataIndex: "shopName",
        key: "shopName",
        search: false,
      },
      {
        title: "所属工段",
        dataIndex: "sectionName",
        key: "sectionName",
        search: false,
      },
      {
        title: "描述",
        dataIndex: "description",
        key: "description",
        search: false,
      },
      {
        title: "操作",
        dataIndex: "option_dataindex",
        key: "option_dataindex",
        valueType: "option",
        width: 255,
        render: (text, row, _, action) => extraAction(text, row, _, action),
      },
    ],
    rightColumns = [
      {
        title: "用户名",
        dataIndex: "accountName",
        key: "accountName",
      },
      {
        title: "姓名",
        dataIndex: "userName",
        key: "userName",
      },
      {
        title: "组织",
        dataIndex: "departmentName",
        key: "departmentName",
        search: false,
      },
      {
        title: "角色",
        dataIndex: "roleNames",
        key: "roleNames",
        search: false,
      },
    ],
    leftColumns = [
      {
        title: "用户名",
        dataIndex: "accountName",
        key: "accountName",
        search: false,
      },
      {
        title: "姓名",
        dataIndex: "userName",
        key: "userName",
        search: false,
      },
      {
        title: "工厂",
        dataIndex: "factoryName",
        key: "factoryName",
        search: false,
      },
      {
        title: "组织",
        dataIndex: "departmentName",
        key: "departmentName",
        search: false,
      },
      {
        title: "负责车间",
        dataIndex: "shopNames",
        key: "shopNames",
        search: false,
      },
      {
        title: "负责工段",
        dataIndex: "sectionNames",
        key: "sectionNames",
        search: false,
      },
      {
        title: "角色",
        dataIndex: "roleNames",
        key: "roleNames",
        search: false,
      },
      {
        title: "联系电话",
        dataIndex: "telephone",
        key: "telephone",
        search: false,
      },
    ];
  function extraAction(text, record, _, action) {
    return [
      getPrem("sysDepartment_save", action, "编辑人员", () => {
        let params = {
          leftColumns,
          rightColumns,
          rightPath: "/ngic-auth/sysGroup/queryNotSelectedUserPage",
          leftPath: "/ngic-auth/sysGroup/querySelectedUserPage",
          toLeft: "/ngic-auth/sysGroup/addUser",
          toRight: "/ngic-auth/sysGroup/deleteUser",
          leftCol: { span: 14 },
          rightCol: { span: 9 },
          leftExtraparams: { id: record.id },
          rightExtraparams: { id: record.id },
          rightRowName: "accountName",
          leftRowName: "accountName",
          leftClickParams: { id: record.id },
          rightClickParams: { id: record.id },
          leftTitle: "班组人员",
          rightTitle: "待选人员",
          leftSelectRowKey: "userIdList",
          rightSelectRowKey: "userIdList",
        };
        dispatch({ type: "station", transferParams: params });
      }),
      getPrem("sysDepartment_save", action, "修改", () => {
        for (let i in defaultFields) {
          defaultFields[i].value = record[i];
        }
        dispatch({ type: "edit", fields: defaultFields, curitem: record });
      }),
      getPrem("sysDepartment_deleteById", action, "删除", null, {
        title: "确认删除该班组？",
        onConfirm: () => {
          run({
            url: "/ngic-auth/sysGroup/deleteById",
            params: { id: record.id },
          });
        },
      }),
    ];
  }
  let saveData = (values, fn) => {
    let newfields = JSON.parse(JSON.stringify(values));
    //新增&修改
    let difrid = iftype.val == "edit" ? { id: curitem.id } : {};
    run({
      url: "/ngic-auth/sysGroup/save",
      params: { ...newfields, ...difrid },
    });
  };
  let extrarender = [
    <Button
      disabled={!getPrem("sysDepartment_save", "ifs")}
      type="primary"
      onClick={() => {
        for (let i in defaultFields) {
          defaultFields[i].value = null;
          defaultFields[i].disabled = false;
        }
        dispatch({ type: "add", fields: defaultFields });
      }}
    >
      新增
    </Button>,
  ];
  return (
    <div>
      <AutoTable
        pagetitle={props.route.name} //页面标题
        pageextra={extrarender} //页面操作 新增or批量删除
        columns={columns}
        path="/ngic-auth/sysGroup/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={"50%"}
      ></DrawInitForm>
      <Details
        title="班组详情"
        visible={visible}
        onClose={() => dispatch({ type: "close" })}
        footer={false}
        destroyOnClose={true}
        width={"100%"}
        {...detail}
      ></Details>
      <Drawer
        title="编辑人员"
        visible={vsc}
        onClose={() => dispatch({ type: "close" })}
        footer={false}
        destroyOnClose={true}
        width={"100%"}
        style={{ position: "absolute" }}
        getContainer={false}
        maskClosable={false}
      >
        <TableTransfer {...transferParams} />
      </Drawer>
    </div>
  );
};
export default Shiftgroup;
