import React, { useEffect, useRef, useReducer } from "react";
import { Button, Tooltip, Row, Divider, Drawer, Image } 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 { labeltemplateDetail } from "@/utils/detailTotalCard";
import Coltext from "@/components/Coltext";
import TableTransfer from "@/components/TableTransfer";
import { unitSelect } from "@/services/craft";
const initState = {
  vs: false,
  fields: {},
  iftype: {},
  curitem: {},
  detail: {
    dataSource: {},
    totalCard: [],
  },
  visible: false,
  vsc: false,
  transferParams: {},
  imgUrl: "",
};
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: [...labeltemplateDetail],
        },
        visible: true,
      };
      break;
    case "station":
      newState = {
        ...state,
        vsc: true,
        transferParams: action.transferParams,
      };
      break;
    case "changeImgurl":
      newState = {
        ...state,
        imgUrl: action.imgUrl,
      };
      break;
    case "close":
      newState = {
        vs: false,
        fields: {},
        iftype: {},
        curitem: {},
        detail: {
          dataSource: {},
          totalCard: [],
        },
        visible: false,
        vsc: false,
        transferParams: {},
        imgUrl: "",
      };
      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,
      imgUrl,
    } = state,
    columns = [
      {
        title: "标签模板编号",
        dataIndex: "tableNo",
        key: "tableNo",
      },
      {
        title: "标签模板名称",
        dataIndex: "tableName",
        key: "tableName",
        render: (_, row) => {
          return (
            <Tooltip title={row.tableName}>
              <a
                className="table-cell"
                className="table-cell"
                onClick={() => {
                  doFetch({
                    url: "/ngic-base-business/bmTable/queryDetails",
                    params: { id: row.id },
                  }).then((res) => {
                    if (res.code == "0000") {
                      let dataSource = res?.data?.data ?? {};
                      dispatch({ type: "see", dataSource });
                    }
                  });
                }}
              >
                {row.tableName}
              </a>
            </Tooltip>
          );
        },
      },
      {
        title: "标签模板类别",
        dataIndex: "tableTypeName",
        key: "tableTypeName",
        options: [
          {
            label: "生产",
            value: 1,
          },
          {
            label: "检验",
            value: 2,
          },
          {
            label: "包装",
            value: 3,
          },
        ],
        valueType: "select",
        formItemProps: {
          name: "tableType",
        },
        options: {
          database: unitSelect,
          params: { dicKey: "table_template" },
        },
      },
      {
        title: "标签长度（cm）",
        dataIndex: "length",
        key: "length",
        search: false,
      },
      {
        title: "标签宽度（cm）",
        dataIndex: "width",
        key: "width",
        search: false,
      },
      {
        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: "fieldName",
        key: "fieldName",
      },
    ],
    leftColumns = [
      {
        title: "字段名称",
        dataIndex: "fieldName",
        key: "fieldName",
        search: false,
      },
    ];
  function extraAction(text, record, _, action) {
    return [
      getPrem("sysDepartment_save", action, "编辑字段", () => {
        let params = {
          leftColumns,
          rightColumns,
          rightPath: "/ngic-base-business/bmTableCommonField/queryList",
          leftPath: "/ngic-base-business/bmTableField/queryList",
          toLeft: "/ngic-base-business/bmTableField/save",
          toRight: "/ngic-base-business/bmTableField/delete",
          leftCol: { span: 14 },
          rightCol: { span: 9 },
          leftExtraparams: { tableId: record.id },
          rightExtraparams: {
            tableId: record.id,
          },
          rightRowName: "fieldName",
          leftRowName: "fieldName",
          leftClickParams: { tableId: record.id },
          rightClickParams: { tableId: record.id },
          leftTitle: "字段信息",
          rightTitle: "待选字段",
          leftRowKey: "id",
          leftSelectRowKey: "commonFieldIdList",
          rightSelectRowKey: "commonFieldIdList",
        };
        dispatch({ type: "station", transferParams: params });
      }),
      getPrem("sysDepartment_save", action, "修改", () => {
        doFetch({
          url: "/ngic-base-business/bmTable/queryDetails",
          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 == "tableType") {
                defaultFields[i].disabled = true;
              }
              if (i == "tableFileId") {
                doFetch({
                  url: "/ngic-base-business/bmTableFile/queryById",
                  params: { id: data[i] },
                }).then((res) => {
                  if (res.code == "0000") {
                    dispatch({
                      type: "changeImgurl",
                      imgUrl:
                        res?.data?.dataList?.length > 0
                          ? res?.data?.dataList[0].url
                          : "",
                    });
                  }
                });
              }
            }
            dispatch({ type: "edit", fields: defaultFields, curitem: data });
          }
        });
      }),
      getPrem("sysDepartment_deleteById", action, "删除", null, {
        title: "确认删除该标签模板？",
        onConfirm: () => {
          run({
            url: "/ngic-base-business/bmTable/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-base-business/bmTable/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-base-business/bmTable/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) => {
          //联动操作
          for (let i in changedValues) {
            if (i == "tableFileId") {
              if (changedValues[i]) {
                doFetch({
                  url: "/ngic-base-business/bmTableFile/queryById",
                  params: { id: changedValues[i] },
                }).then((res) => {
                  if (res.code == "0000") {
                    dispatch({
                      type: "changeImgurl",
                      imgUrl:
                        res?.data?.dataList?.length > 0
                          ? res?.data?.dataList[0].url
                          : "",
                    });
                  }
                });
              } else {
                dispatch({ type: "changeImgurl", imgUrl: "" });
              }
            }
          }
        }}
        submitting={loading || !vs}
        width={"50%"}
        bottomNode={
          imgUrl ? (
            <div>
              <div style={{ marginBottom: 12 }}>模板预览图：</div>
              <Image width={200} src={imgUrl} />
            </div>
          ) : null
        }
      ></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;
