import React, { useEffect, useRef, useReducer, useState, useMemo } from "react";
import {
  Button,
  Tooltip,
  Row,
  Divider,
  Drawer,
  Modal,
  Space,
  message,
  Image,
} 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";
import PremButton from "@/components/PremButton/index.jsx";
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: "qrCodeUrl ",
        key: "qrCodeUrl ",
        search: false,
        render: (_, row) => {
          return <Image src={row?.qrCodeUrl} width={30} height={30}></Image>;
        },
      },
      {
        title: "创建人",
        dataIndex: "createUserName",
        key: "createUserName",
        search: false,
      },
      {
        title: "单据日期",
        dataIndex: "orderDate",
        key: "orderDate",
        search: false,
      },
      {
        title: "操作",
        valueType: "option",
        render: (_, row) => {
          return [
            <PremButton
              key="remove"
              pop={{
                title: "是否删除该条信息?",
                okText: "确认",
                cancelText: "取消",
                onConfirm: async () => {
                  let res = await doFetch({
                    url: "/ngic-workmanship/wmsMaterieLabel/deleteById",
                    params: {
                      id: row?.id,
                    },
                  });
                  if (res && res?.code === "0000") {
                    actionRef?.current?.reload();
                  }
                },
              }}
              btn={{
                size: "small",
                type: "danger",
              }}
            >
              删除
            </PremButton>,
          ];
        },
      },
    ];

  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 [data, setdata] = useState({});

//   useEffect(() => {
//     let el = document.getElementById("mydemo");
//     el.innerHTML = ` <div>
//     <div style="display:flex; width:100% ;height:100%; flex-direction: column;justify-self: space-between; font-family:'宋体'">
// <div style="display:flex; flex-direction: row;flex:2;">
//   <div style="display:flex;flex-direction: column;flex:2">
//     <div style="flex:1">卷料名称：${data?.materieName ?? "--"}</div>
//     <div style="flex:1">卷料编码：${data?.materieCode ?? "--"}</div>
//   </div>
// </div>
// <div style="display:flex; flex-direction: row;flex:1;">
//  <div style="flex:3;display:flex;flex-direction: row;">
//    <div style="flex:1">批次：${data?.materieControlNo ?? "--"}</div>  
//    <div style="flex:1">厚度：${data?.unilateralThickness ?? "--"}mm</div>
//  </div>
//  <div style="flex:1">
//  <img src=${data?.qrCodeUrl} style="width:100%"/>
//  </div>
// </div>
// <div style="display:flex; flex-direction: row;flex:1;">
//   <div style="flex:2">铁损：${data?.ironLoss ?? "--"}w/kg</div>
//   <div style="flex:3">牌号：${data?.shopSign ?? "--"}片</div>
// </div>
// <div style="display:flex; flex-direction: row;flex:1;">
// <div style="flex:2">宽度：${data?.width ?? "--"}mm</div>
//   <div style="flex:3">片厚：${data?.sheetThickness ?? "--"}mm</div>
// </div>
// <div style="display:flex; flex-direction: row;flex:1;">
// <div style="flex:2">重量：${data?.weight ?? "--"}KG</div>
//   <div style="flex:3">米数：${data?.length ?? "--"}M</div>
// </div>

// </div>
//     </div>`;
//   }, []);

  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>
      {/* <div id="mydemo" style={{width:500,height:250,border:'1px solid #000',backgroundColor:'#fff'}}></div> */}
      <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;
