import React, { useEffect, useRef, useReducer, useState, useMemo } from "react";
import {
  Button,
  Tooltip,
  Row,
  Divider,
  Drawer,
  Modal,
  Space,
  message,
} from "antd";
import AutoTable from "@/components/AutoTable";
import { useRequest } from "umi";
import { getColumns } from "./fields.js";
import { doFetch } from "@/utils/doFetch";
import InitForm from "@/components/NewInitForm";
import { start } from "@/utils/printHandle.js";
import { ExclamationCircleFilled } from "@ant-design/icons";
const { confirm } = Modal;

const Station = (props) => {
  let actionRef = useRef(),
    formRef = 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" });
        }
      },
    }),
    columns = [
      {
        title: "物料编码",
        dataIndex: "materieCode",
        key: "materieCode",
      },
      {
        title: "物料名称",
        dataIndex: "materieName",
        key: "materieName",
      },
      {
        title: "规格型号",
        dataIndex: "specificationModel",
        key: "specificationModel",
      },
      {
        title: "数量",
        dataIndex: "weight",
        key: "weight",
        search: false,
      },
      {
        title: "批次号",
        dataIndex: "materieControlNo",
        key: "materieControlNo",
      },
      {
        title: "供应商",
        dataIndex: "supplierName",
        key: "supplierName",
        search: false,
      },
      {
        title: "宽度",
        dataIndex: "width",
        key: "width",
        search: false,
      },
      {
        title: "片厚",
        dataIndex: "sheetThickness",
        key: "sheetThickness",
        search: false,
      },
      {
        title: "铁损",
        dataIndex: "ironLoss",
        key: "ironLoss",
        search: false,
      },
      {
        title: "单边厚度",
        dataIndex: "unilateralThickness",
        key: "unilateralThickness",
        search: false,
      },
      {
        title: "创建人",
        dataIndex: "createUserName",
        key: "createUserName",
        search: false,
      },
      {
        title: "单据日期",
        dataIndex: "orderDate",
        key: "orderDate",
        search: false,
      },
    ];

  const [drawer, setDrawer] = useState({
    visible: false,
  });
  const [selectIds, setselectIds] = useState([]);

  const formFields = useMemo(() => {
    return getColumns(setDrawer, formRef);
  });
  const saveAndPrint = () => {
    confirm({
      title: `当前已完成信息填写，是否保存并立即打印？`,
      icon: <ExclamationCircleFilled />,
      width: 500,
      okText: "确定",
      cancelText: "取消",
      onOk() {
        formRef?.current?.validateFields().then((formData) => {
          start("/ngic-workmanship/wmsMaterieLabel/save", formData).then(
            (res) => {
              console.log(res);
              setDrawer((v) => ({
                ...v,
                visible: false,
              }));
              message.success("保存成功！", 2);
              reload();
            }
          );
        });
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  const saveData = (type) => {
    if (type === 1) {
      formRef?.current?.validateFields().then((formData) => {
        if (formData?.list && formData?.list.length > 0) {
          doFetch({
            url: "/ngic-workmanship/wmsMaterieLabel/save",
            params: formData,
          }).then((res) => {
            if (res?.code == "0000") {
              reload();
              setDrawer((v) => ({
                ...v,
                visible: false,
              }));
            }
          });
        } else {
          message.destroy();
          message.warning("请添加列表数据！", 2);
        }
      });
    } else {
      reload();
      saveAndPrint();
    }
    //新增&修改
    // let difrid = iftype.val == "edit" ? { id: curitem.id } : {};
    // run({
    //   url: "/ngic-auth/sysStation/save",
    //   params: { ...newfields, ...difrid },
    // });
  };

  const showConfirm = () => {
    confirm({
      title: `当前已选择 ${selectIds?.length} 条标签数据，是否全部打印？`,
      icon: <ExclamationCircleFilled />,
      width: 500,
      okText: "确定",
      cancelText: "取消",
      onOk() {
        start("/ngic-workmanship/wmsMaterieLabel/queryByIds", {
          ids: selectIds,
        });
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  const OptionsBtn = () => {
    return (
      <>
        <Button
          type="primary"
          style={{ marginRight: 8 }}
          onClick={() => {
            setDrawer((v) => ({ ...v, visible: true, title: " 卷料分卷打码" }));
          }}
        >
          卷料分卷打码
        </Button>
        <Button
          type="primary"
          onClick={() => {
            if (selectIds.length == 0) {
              message.destroy();
              message.warning("请选择数据！", 2);
              return;
            }
            showConfirm();
          }}
        >
          子卷补码
        </Button>
      </>
    );
  };

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(selectedRowKeys, selectedRows);
      setselectIds(selectedRowKeys);
    },
    preserveSelectedRowKeys: true,
  };
  return (
    <div>
      <AutoTable
        pagetitle={props.route.name} //页面标题
        pageextra={OptionsBtn()} //页面操作 新增or批量删除
        columns={columns}
        path="/ngic-workmanship/wmsMaterieLabel/page"
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        rowSelection={{
          type: "checkbox",
          ...rowSelection,
        }}
      ></AutoTable>
      <Drawer
        title={drawer?.title}
        open={drawer?.visible}
        onClose={() => setDrawer((v) => ({ ...v, visible: false }))}
        footer={false}
        destroyOnClose={true}
        getContainer={false}
        style={{ position: "absolute" }}
        width={"100%"}
      >
        <InitForm
          formRef={formRef}
          fields={formFields}
          onChange={(changedValues, allValues) => {}}
          actions={() => {
            return null;
          }}
          submitter={false}
        ></InitForm>
        <Button
          type="primary"
          //   loading={loading || !vs}
          style={{ marginRight: 16 }}
          onClick={() => saveData(1)}
        >
          保存
        </Button>
        <Button
          type="primary"
          //   loading={loading || !vs}
          onClick={() => saveData(2)}
        >
          保存并打印
        </Button>
      </Drawer>
    </div>
  );
};
export default Station;
