import React, { useEffect, useMemo, useRef, useState } from "react";
import { Dropdown, Menu, Button, message } from "antd";
import AutoTable from "@/components/AutoTable";
import defaultFields from "./fields";
import { doFetch } from "@/utils/doFetch";
import DrawInitForm from "@/components/DrawInitForm";
import getPrem from "@/utils/getPrem"; //权限判断fn
import { useReactToPrint } from "react-to-print";
import { useModel } from "umi";
import PrintDom from "./printdom";
import { PrintQrCode } from "@/components/PrintCode";

function Outstore(props) {
  const { initialState, setInitialState } = useModel("@@initialState");
  const [activeTabKey, onTabChange] = useState("1");
  const [selectKeys, setSelectKeys] = useState([]);

  let [drawprops, setdrawprops] = useState({
      title: "",
      visible: false,
      onClose: () => {
        setdrawprops((s) => ({
          ...s,
          visible: false,
          fields: {},
        }));
      },
      fields: {},
      width: 1200,
    }),
    actionRef = useRef(),
    ChildRef = null,
    printRef = useRef(),
    mutiPrintRef = useRef();

  //操作完成后刷新
  function reload() {
    actionRef.current.reload();
    ChildRef?.onRefresh();
    message.success("操作成功");
    setdrawprops((s) => ({
      ...s,
      visible: false,
      fields: {},
    }));
  }

  const handlePrint = useReactToPrint({
    content: () => printRef.current.dom.current,
  });

  const mutiPrint = useReactToPrint({
    content: () => mutiPrintRef.current.dom.current,
  });
  const PrintButton = (
    <Button
      disabled={!selectKeys.length}
      onClick={() => {
        mutiPrint();
      }}
    >
      打印
    </Button>
  );

  useEffect(() => {
    const detail = defaultFields.detail(setSelectKeys, PrintButton);
    setdrawprops((s) => ({
      ...s,
      ...detail,
    }));
  }, [selectKeys]);

  const columns = useMemo(() => {
    if (activeTabKey == "1") {
      return [
        {
          title: "任务单号",
          dataIndex: "taskNo",
          key: "taskNo",
          search: false,
          render: (dom, record) => {
            return (
              <a
                onClick={() => {
                  const detail = defaultFields.detail(
                    setSelectKeys,
                    PrintButton
                  );
                  setdrawprops((s) => ({
                    ...s,
                    visible: true,
                    //查看详情 props
                    val: "detail",
                    title: `查看详情`,
                    ...detail,
                    totalPath:
                      "/ngic-workmanship/wmsMaterieOutstore/getOutStoreInfoById",
                    totalParams: { id: record.id },
                    extra: (
                      <Button
                        onClick={async () => {
                          handlePrint();
                        }}
                      >
                        打印
                      </Button>
                    ),
                  }));
                }}
              >
                {dom}
              </a>
            );
          },
        },
        {
          title: "物料名称",
          dataIndex: "materieName",
          key: "materieName",
        },
        {
          title: "规格型号",
          dataIndex: "specificationModel",
          key: "specificationModel",
          search: false,
          fieldProps: {
            allowClear: true,
            showSearch: true,
          },
          options: {
            database: () =>
              doFetch({
                url: "/ngic-auth/sysStore/selectionBox",
                params: { factoryIdList: [] },
              }),
            params: {},
          },
          valueType: "select",
        },
        {
          title: "批次号",
          dataIndex: "materieControlNo",
          key: "materieControlNo",
          search: false,
        },
        {
          title: "来源库位",
          dataIndex: "sourceStorePositionName",
          key: "sourceStorePositionName",
          search: false,
        },
        {
          title: "目标库位",
          dataIndex: "targetStorePositionName",
          key: "targetStorePositionName",
          search: false,
        },
        {
          title: "任务类型",
          dataIndex: "taskTypeName",
          key: "taskType",
          valueType: "select",
          options: [
            {
              label: "生产叫料单",
              value: "1",
            },
            {
              label: "来料入库单",
              value: "2",
            },
            {
              label: "生产退料单",
              value: "3",
            },
            {
              label: "移库",
              value: "4",
            },
          ],
        },
        {
          title: "单据状态",
          dataIndex: "statusName",
          key: "status",
          valueType: "select",
          options: [
            {
              label: "待执行",
              value: "0",
            },
            {
              label: "执行中",
              value: "1",
            },
            {
              label: "已执行",
              value: "2",
            },
            {
              label: "待分配",
              value: "3",
            },
          ],
        },
        {
          title: "下发时间",
          dataIndex: "distributeTime",
          key: "distributeTime",
          search: false,
        },
        {
          title: "操作",
          dataIndex: "options",
          key: "options",
          search: false,
          render: (text, record, _, action) => {
            return [
              getPrem("equipmentCustomer_deleteById", action, "关单", null, {
                title: "确认关单？",
                onConfirm: () => {
                  doFetch({
                    url: "/ngic-workmanship/wmsTaskManagement/close",
                    params: { id: record.id },
                  }).then((res) => {
                    if (res.code == "0000") {
                      reload();
                    }
                  });
                },
              }),
            ];
          },
        },
      ];
    } else {
      return [
        {
          title: "任务单号",
          dataIndex: "taskNo",
          key: "taskNo",
          search: false,
          // render: (dom, record) => {
          //   return (
          //     <a
          //       onClick={() => {
          //         const detail = defaultFields.detail(
          //           setSelectKeys,
          //           PrintButton
          //         );
          //         setdrawprops((s) => ({
          //           ...s,
          //           visible: true,
          //           //查看详情 props
          //           val: "detail",
          //           title: `查看详情`,
          //           ...detail,
          //           totalPath:
          //             "/ngic-workmanship/wmsMaterieOutstore/getOutStoreInfoById",
          //           totalParams: { id: record.id },
          //           extra: (
          //             <Button
          //               onClick={async () => {
          //                 handlePrint();
          //               }}
          //             >
          //               打印
          //             </Button>
          //           ),
          //         }));
          //       }}
          //     >
          //       {dom}
          //     </a>
          //   );
          // },
        },
        {
          title: "物料名称",
          dataIndex: "materieName",
          key: "materieName",
          search: false,
        },
        {
          title: "规格型号",
          dataIndex: "specificationModel",
          key: "specificationModel",
          search: false,
          fieldProps: {
            allowClear: true,
            showSearch: true,
          },
          options: {
            database: () =>
              doFetch({
                url: "/ngic-auth/sysStore/selectionBox",
                params: { factoryIdList: [] },
              }),
            params: {},
          },
          valueType: "select",
        },
        {
          title: "批次号",
          dataIndex: "materieControlNo",
          key: "materieControlNo",
        },
        {
          title: "来源库位",
          dataIndex: "sourceStorePositionName",
          key: "sourceStorePositionName",
          search: false,
        },
        {
          title: "目标库位",
          dataIndex: "targetStorePositionName",
          key: "targetStorePositionName",
          search: false,
        },
        {
          title: "任务类型",
          dataIndex: "taskTypeName",
          key: "taskTypeName",
          search: false,
        },
        {
          title: "单据状态",
          dataIndex: "statusName",
          key: "status",
          search: false,
          valueType: "select",
          options: [
            {
              label: "待执行",
              value: "0",
            },
            {
              label: "执行中",
              value: "1",
            },
            {
              label: "已执行",
              value: "2",
            },
            {
              label: "待分配",
              value: "3",
            },
          ],
        },
        {
          title: "下发时间",
          dataIndex: "distributeTime",
          key: "distributeTime",
          search: false,
        },
      ];
    }
  }, [activeTabKey]);

  const tableprops = {
    ...props,
    tabList: [
      {
        tab: "未完成",
        key: "1",
      },
      {
        tab: "已完成",
        key: "2",
      },
    ],
    activeTabKey,
    onTabChange,
    columns,
    path:
      activeTabKey == "1"
        ? "/ngic-workmanship/wmsTaskManagement/queryList"
        : "/ngic-workmanship/wmsTaskManagementHis/queryList",
  };

  return (
    <div>
      <div style={{ position: "fixed", bottom: -100000 }}>
        <PrintDom ref={printRef} {...drawprops} />
      </div>
      <div style={{ display: "none" }}>
        <PrintQrCode ref={mutiPrintRef} selectedItems={selectKeys} />
      </div>
      <AutoTable
        {...tableprops}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
      ></AutoTable>
      <DrawInitForm
        {...drawprops}
        submitData={async (value) => {
          if (drawprops.val == "add") {
            let newfileds = JSON.parse(JSON.stringify(value));
            newfileds.materialList = newfileds?.materialList?.map((it) => {
              delete it.usableNum;
              delete it.id;
              return it;
            });
            let res = await doFetch({
              url: "/ngic-workmanship/wmsMaterieOutstore/saveOutStore",
              params: { ...newfileds, outstoreType: drawprops.outstoreType },
            });
            if (res.code == "0000") {
              reload();
            }
          }
        }}
        onChange={async (changedValues, allValues) => {
          for (let i in changedValues) {
            if (i == "storeId") {
              let res = await doFetch({
                  url: "/ngic-workmanship/wmsMaterieStockStore/selectbox/usableStock",
                  params: { storeId: changedValues["storeId"] },
                }),
                options = res?.data?.dataList;
              setdrawprops((s) => {
                let fields = JSON.parse(JSON.stringify(s.fields));
                for (let i in fields) {
                  fields[i].value = allValues[i];
                }
                fields["materialList"].linkconfig = {
                  urlchangeval: {
                    //根据url接口 改变某个value
                    database: (params) =>
                      doFetch({
                        url: "/ngic-workmanship/wmsMaterieStockStore/queryStoreOne",
                        params,
                      }),
                    params: { materieId: "linked", storeId: changedValues[i] },
                    effectresult: {
                      productionUnit: "productionUnit", //key 为列表更新值  value为response 返回值
                      productionUnitName: "productionUnitName",
                      usableNum: "usableNum",
                      outstroeNum: "outstroeNum",
                    },
                  },
                };
                fields["materialList"].columns = [
                  {
                    title: (
                      <span>
                        物料编码-名称 <b style={{ color: "red" }}>*</b>
                      </span>
                    ),
                    dataIndex: "materieId",
                    key: "materieId",
                    valueType: "select",
                    fieldProps: {
                      allowClear: true,
                      showSearch: true,
                      options,
                    },
                    formItemProps: () => {
                      return {
                        rules: [{ required: true, message: "此项为必填项" }],
                      };
                    },
                    editable: true,
                  },
                  {
                    title: (
                      <span>
                        出库数量 <b style={{ color: "red" }}>*</b>
                      </span>
                    ),
                    dataIndex: "outstroeNum",
                    key: "outstroeNum",
                    formItemProps: () => {
                      return {
                        rules: [{ required: true, message: "此项为必填项" }],
                      };
                    },
                    valueType: "digit",
                    editable: true,
                  },
                  {
                    title: "可用库存",
                    dataIndex: "usableNum",
                    key: "usableNum",
                    readonly: "usableNum",
                  },
                  {
                    title: "库存单位",
                    dataIndex: "productionUnitName",
                    key: "productionUnitName",
                    readonly: "productionUnitName",
                  },
                  {
                    title: "操作",
                    valueType: "option",
                    width: 70,
                    render: (text, record, _, action) => [
                      <a key="delete" onClick={() => {}}>
                        删除
                      </a>,
                    ],
                  },
                ];
                fields["materialList"].value = undefined;
                let newfields = {
                  ...fields,
                };
                return {
                  ...s,
                  fields: newfields,
                };
              });
            }
          }
        }}
        reload={reload}
      />
    </div>
  );
}

export default Outstore;
