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 { gatherDetail } 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: {},
  },
  otherBasic = {
    pmCollectionSiteStationNames: "工位",
  };
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: [...gatherDetail],
        },
        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 Gather = (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: "collectionSiteCode",
        key: "collectionSiteCode",
      },
      {
        title: "站点名称",
        dataIndex: "collectionSiteName",
        key: "collectionSiteName",
        render: (_, row) => {
          return (
            <Tooltip title={row.collectionSiteName}>
              <a
                className="table-cell"
                className="table-cell"
                onClick={() => {
                  doFetch({
                    url: "/ngic-workmanship/pmCollectionSite/queryById",
                    params: { id: row.id },
                  }).then((res) => {
                    if (res.code == "0000") {
                      let dataSource = res?.data?.data ?? {};
                      dispatch({ type: "see", dataSource });
                    }
                  });
                }}
              >
                {row.collectionSiteName}
              </a>
            </Tooltip>
          );
        },
      },
      {
        title: "所属工厂",
        dataIndex: "factoryName",
        key: "factoryName",
      },
      {
        title: "所属车间",
        dataIndex: "shopName",
        key: "shopName",
      },
      {
        title: "所属产线",
        dataIndex: "productionLineName",
        key: "productionLineName",
      },
      {
        title: "工序",
        dataIndex: "workingProcedureName",
        key: "workingProcedureName",
      },
      {
        title: "工序类型",
        dataIndex: "workingProcedureTypeName",
        key: "workingProcedureTypeName",
        options: [
          {
            label: "生产",
            value: 1,
          },
          {
            label: "检验",
            value: 2,
          },
          {
            label: "包装",
            value: 3,
          },
        ],
        valueType: "select",
        formItemProps: {
          name: "workingProcedureType",
        },
      },
      {
        title: "采集方式",
        dataIndex: "collectionModeName",
        key: "collectionModeName",
        options: [
          {
            label: "上下线",
            value: 1,
          },
          {
            label: "一次",
            value: 2,
          },
          {
            label: "投料",
            value: 3,
          },
        ],
        valueType: "select",
        formItemProps: {
          name: "collectionMode",
        },
      },
      {
        title: "描述",
        dataIndex: "remark",
        key: "remark",
        search: false,
      },
      {
        title: "操作",
        dataIndex: "option_dataindex",
        key: "option_dataindex",
        valueType: "option",
        width: 255,
        render: (text, row, _, action) => extraAction(text, row, _, action),
      },
    ],
    rightColumns = [
      {
        title: "工位编号",
        dataIndex: "stationCode",
        key: "stationCode",
      },
      {
        title: "工位名称",
        dataIndex: "stationName",
        key: "stationName",
      },
      {
        title: "工位类型",
        dataIndex: "stationTypeName",
        key: "stationTypeName",
        search: false,
      },
      {
        title: "能力",
        dataIndex: "capacity",
        key: "capacity",
        search: false,
      },
    ],
    leftColumns = [
      {
        title: "工位编号",
        dataIndex: "stationCode",
        key: "stationCode",
        search: false,
      },
      {
        title: "工位名称",
        dataIndex: "stationName",
        key: "stationName",
        search: false,
      },
      {
        title: "所属车间",
        dataIndex: "shopName",
        key: "shopName",
        search: false,
      },
      {
        title: "所属工段",
        dataIndex: "sectionName",
        key: "sectionName",
        search: false,
      },
      {
        title: "所属产线",
        dataIndex: "productionLineName",
        key: "productionLineName",
        search: false,
      },
      {
        title: "工位类型",
        dataIndex: "stationTypeName",
        key: "stationTypeName",
        search: false,
      },
      {
        title: "能力",
        dataIndex: "capacity",
        key: "capacity",
        search: false,
      },
    ];
  function extraAction(text, record, _, action) {
    return [
      getPrem("sysDepartment_save", action, "编辑工位", () => {
        let params = {
          leftColumns,
          rightColumns,
          rightPath: "/ngic-auth/sysStation/querySelectedList",
          leftPath: "/ngic-workmanship/pmCollectionSiteStation/queryList",
          toLeft: "/ngic-workmanship/pmCollectionSiteStation/save",
          toRight: "/ngic-workmanship/pmCollectionSiteStation/deleteByIds",
          leftCol: { span: 14 },
          rightCol: { span: 9 },
          leftExtraparams: { collectionSiteId: record.id },
          rightExtraparams: {
            collectionSiteId: record.id,
            workingProcedureId: record.workingProcedureId,
            shopId: record.shopId,
            productionLineId: record.productionLineId,
          },
          rightRowName: "stationName",
          leftRowName: "stationName",
          leftClickParams: { collectionSiteId: record.id },
          rightClickParams: { collectionSiteId: record.id },
          leftTitle: "工位信息",
          rightTitle: "待选工位",
          leftRowKey: "stationId",
          leftSelectRowKey: "stationIdList",
          rightSelectRowKey: "stationIdList",
        };
        dispatch({ type: "station", transferParams: params });
      }),
      getPrem("sysDepartment_save", action, "修改", () => {
        doFetch({
          url: "/ngic-workmanship/pmCollectionSite/queryById",
          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 == "factoryId" ||
                i == "shopId" ||
                i == "productionLineId" ||
                i == "workingProcedureId"
              ) {
                if (data?.pmCollectionSiteStationList?.length > 0) {
                  defaultFields[i].disabled = true;
                } else {
                  defaultFields[i].disabled = false;
                }
              }
            }
            let names =
                data?.pmCollectionSiteStationList?.map((it) => {
                  return it.stationName;
                }) ?? [],
              pmCollectionSiteStationNames = names.join(",");
            dispatch({
              type: "edit",
              fields: defaultFields,
              curitem: { ...data, pmCollectionSiteStationNames },
            });
          }
        });
      }),
      getPrem("sysDepartment_deleteById", action, "删除", null, {
        title: "确认删除该站点？",
        onConfirm: () => {
          run({
            url: "/ngic-workmanship/pmCollectionSite/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-workmanship/pmCollectionSite/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-workmanship/pmCollectionSite/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%"}
      >
        {iftype.val == "edit" && (
          <>
            <Row gutter={[16, 10]}>
              {Object.keys(otherBasic).map((it) => {
                return (
                  <Coltext
                    label={otherBasic[it]}
                    value={curitem[it]}
                    key={it}
                    col={{ span: 24 }}
                  />
                );
              })}
            </Row>
            <Divider />
          </>
        )}
      </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 Gather;
