import React, { FunctionComponent, useEffect, useMemo, useState } from "react";
import { Button, Input, InputNumber, Layout, Popover, Radio, Space, Tabs } from "antd";
import { EyeOutlined, LeftOutlined, RedoOutlined, RightOutlined } from "@ant-design/icons";
import Preview from "./components/preview";
import provider from "./components/custom/provider";
import { observer } from "mobx-react";
import { toJS } from "mobx";
import { useMobStore } from "@/hooks";
import * as hiprintConfig from "./config";
import classnames from "classnames";
import styles from "./index.less";
import Trans from "@/utils/locale";
const { Header, Sider, Content } = Layout;

interface OwnProps {}

type Props = OwnProps;

const Design: FunctionComponent<Props> = observer((props) => {
  const store = useMobStore("hiprintStore");
  const [designType, setDesignType] = useState<string>("default");
  const [cusPaper, setCusPaper] = useState<boolean>(false);
  const [collapsed, setCollapsed] = useState<boolean>(false);
  const [open, setOpen] = useState<boolean>(false);
  const [curPaper, setCurPaper] = useState<Partial<hiprintConfig.PaperObject>>({ value: "A4", width: 220, height: 80 });
  useEffect(() => {
    getPanel();
    init();
    return () => {};
  }, [designType]);
  /*
   * Author: 黎永顺
   * Description: 设计器初始化
   * Params:
   * Date: 2025/1/27
   */
  const init = () => {
    const f = _.find(provider, (o) => o.key === designType)?.f;
    const providerVal = _.find(provider, (o) => o.key === designType)?.value;
    store?.hiprint.init({ providers: f ? [f] : [] });
    // @ts-ignore
    $(".hiprintEpContainer").empty();
    store?.hiprint.PrintElementTypeManager.build(".hiprintEpContainer", providerVal);
    // @ts-ignore
    $("#hiprint-printTemplate").empty();
    store.setHiprintTemplate(
      new store.hiprint.PrintTemplate({
        template: {},
        settingContainer: "#PrintElementOptionSetting",
        paginationContainer: ".hiprint-printPagination"
      })
    );
    store?.hiprintTemplate.design("#hiprint-printTemplate", { grid: true });
    console.log(toJS(store?.hiprintTemplate));
  };
  /**
   * @description: 加载 panel
   */
  const getPanel = () => {
    // 加载所有 panel
    const panels = (require as any).context("./", true, /panel.*\.js$/);
    console.log(panels.keys());
  };
  /*
   * Author: 黎永顺
   * Description: 设置纸张大小
   * Params:[A3, A4, A5, B3, B4, B5, other] value {width,height} mm
   * Date: 2025/2/5
   */
  const paperType = useMemo(() => {
    const paperWidth = _.find(hiprintConfig.paperTypes, (o) => o.value === curPaper?.value)?.width,
      paperHeight = _.find(hiprintConfig.paperTypes, (o) => o.value === curPaper?.value)?.height;
    if (!_.isEmpty(_.find(hiprintConfig.paperTypes, (o) => o.value === curPaper?.value))) {
      store?.hiprintTemplate?.setPaper(paperWidth, paperHeight);
    } else {
      store?.hiprintTemplate?.setPaper(curPaper.width, curPaper.height);
    }
    return curPaper?.value;
  }, [curPaper]);
  return (
    <Layout className={styles.hiprintOuterLayout}>
      <Header className={styles.hiprintHeader}>
        <div className={styles.hiprintHeader_rightside}>
          <Space>
            {designType === "default" && (
              <Button type="ghost" icon={<RedoOutlined />} onClick={() => store?.hiprintTemplate?.rotatePaper()}>
                旋转
              </Button>
            )}
            <Button type="primary" icon={<EyeOutlined />} onClick={() => setOpen(true)}>
              预览<Trans>Address</Trans>
            </Button>
          </Space>
        </div>
      </Header>
      <Layout className={styles.hiprintInnerLayout}>
        <Sider className={classnames(styles.hiprintSider, styles.hiprint_design_ls, {})}>
          <Tabs
            activeKey={designType}
            size="small"
            onChange={setDesignType}
            items={[
              { label: "默认设计", key: "default" },
              { label: "自定义设计", key: "custom" }
            ]}
          />
          <Radio.Group size="small" value={paperType} onChange={(e) => setCurPaper({ ...curPaper, value: e.target.value })}>
            {_.map(hiprintConfig.paperTypes, (o) => (
              <Radio.Button value={o.value} key={o.value.toString()}>
                {o.label}
              </Radio.Button>
            ))}
            <Popover
              open={cusPaper}
              onOpenChange={setCusPaper}
              trigger="click"
              title="设置纸张宽高(mm)"
              content={
                <>
                  <Input.Group compact style={{ marginBottom: 10 }}>
                    <InputNumber placeholder="宽(mm)" value={curPaper.width} onChange={(val) => setCurPaper({ ...curPaper, width: val as number })} />
                    <Input
                      placeholder="~"
                      disabled
                      style={{
                        width: 30,
                        pointerEvents: "none"
                      }}
                    />
                    <InputNumber placeholder="高(mm)" value={curPaper.height} onChange={(val) => setCurPaper({ ...curPaper, height: val as number })} />
                  </Input.Group>
                </>
              }
            >
              <Radio.Button value="other" key="other">
                自定义纸张
              </Radio.Button>
            </Popover>
          </Radio.Group>
          <div className="rect-printElement-types hiprintEpContainer" />
        </Sider>
        <Content className={styles.hiprintContent}>
          <div id="hiprint-printTemplate" className="hiprint-printTemplate" />
          <Preview open={open} onClose={() => setOpen(false)} />
        </Content>
        <Sider
          className={classnames(styles.hiprintSider, styles.hiprint_design_rs, {})}
          width={249}
          collapsible
          collapsedWidth={0}
          onCollapse={setCollapsed}
          trigger={!collapsed ? <RightOutlined /> : <LeftOutlined />}
        >
          <div id="PrintElementOptionSetting" />
        </Sider>
      </Layout>
    </Layout>
  );
});

export default Design;
