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 StoreApp from './store'
const initState = {
  vs: false,
  fields: {},
  iftype: {},
  curitem: {},
  detail: {
    dataSource: {},
    totalCard: [],
  },
  visible: false,
},
  otherBasic = {
    productionLineName: "产线（加工中心）",
    sectionName: "工段",
    processLineName: "工艺路线",
    groupName: "班组",
    shiftName: "班次",
  };
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,
        curitem: action.curitem,
        visible: true,
      };
      break;
    case "close":
      newState = {
        ...state,
        curitem: {},
        vs: false,
        visible: false,
      };
      break;
  }

  return newState;
}

const Store = (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 } = state,
    columns = [
      {
        "title": "仓库编号",
        "dataIndex": "storeCode",
        "key": "storeCode"
      },
      {
        "title": "仓库名称",
        "dataIndex": "storeName",
        "key": "storeName"
      },
      {
        "title": "仓库类型",
        "dataIndex": "storeTypeName",
        "key": "storeTypeName",
        "valueType": "select",
        "options": [
          {
            "label": "半成品库",
            "value": "0"
          },
          {
            "label": "成品库",
            "value": "1"
          },
          {
            "label": "原材料库",
            "value": "2"
          }
        ]
      },
      {
        "title": "工厂名",
        "dataIndex": "factoryName",
        "key": "factoryName"
      },
      {
        title: "操作",
        dataIndex: "option_dataindex",
        key: "option_dataindex",
        valueType: "option",
        width: 135,
        render: (text, row, _, action) => extraAction(text, row, _, action),
      },
    ];

  function extraAction(text, record, _, action) {
    return [
      getPrem("sysDepartment_save", action, "库位管理", () => {
        dispatch({ type: "see", curitem: record });
      }),
      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/sysStore/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/sysStore/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/sysStore/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={"60%"}
      >
      </DrawInitForm>

      <Drawer
        visible={visible}
        onClose={() => dispatch({ type: "close" })}
        title="库位列表"
        footer={false}
        destroyOnClose={true}
        width={"100%"}
        getContainer={false}
        style={{ position: "absolute" }}
      >
        <StoreApp curitem={curitem}></StoreApp>
      </Drawer>


    </div>
  );
};
export default Store;
