<template>
  <div class="device_container">
    <div class="header" @click="router.back()">
      <el-icon style="position: relative; top: 2px; margin-right: 4px" size="22">
        <ArrowLeft />
      </el-icon>
      <el-text>{{ form.id ? "编辑便签打印机" : "添加便签打印机" }}</el-text>
    </div>
    <div class="d_content">
      <div class="d_list">
        <el-form :model="form" label-position="left" label-width="60%">
          <!-- <el-form-item label="设备尺寸">
            <el-select v-model="form.config.width">
              <el-option label="58mm" value="58"></el-option>
              <el-option label="80mm" value="80"></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="设备类型">
            <el-select v-model="form.connectionType">
              <el-option label="USB" value="USB"></el-option>
              <el-option label="网络" value="network"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择设备">
            <el-select v-model="form.config.deviceName">
              <el-option :label="item.name" :value="item.name" v-for="item in printList" :key="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备名称">
            <el-input v-model="form.name" placeholder="请输入设备名称"></el-input>
          </el-form-item>
          <el-form-item label="打印份数">
            <el-select v-model="form.config.printerNum">
              <el-option :label="item" :value="item" v-for="item in 4" :key="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品模式">
            <el-select v-model="form.config.model">
              <el-option label="普通出单" value="normal"></el-option>
              <el-option label="分类出单" value="category"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品分类">
            <div style="cursor: pointer" @click="classifyRef.show()">
              <span style="color: #409eff" v-for="item in form.config.categoryList">
                {{ item.name }},
              </span>
              <span style="color: #e65d6e" v-if="!form.config.categoryList.length">
                请选择分类
              </span>
            </div>
          </el-form-item>
          <!-- <el-form-item label="打印子订单">
            <el-select v-model="form.config.printSub">
              <el-option label="是" :value="0"></el-option>
              <el-option label="否" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="自动切刀">
            <el-select v-model="form.config.autoCut">
              <el-option label="是" :value="1"></el-option>
              <el-option label="否" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="尾部留空">
            <el-select v-model="form.config.feet">
              <el-option
                :label="`${item}行`"
                :value="`${item}`"
                v-for="item in feets"
                :key="item"
              ></el-option>
            </el-select>
          </el-form-item> -->
        </el-form>
      </div>
      <div class="menu_wrap">
        <div class="print_view">
          <canvas class="ewm" ref="canvasRef"></canvas>
          <div class="header">
            <img class="logo" src="../../assets/prinnt_label_logo.png" />
            <!-- <span class="title">双屿Pisces</span> -->
          </div>
          <div class="number_wrap">
            <div class="num" v-if="printData.outNumber">{{ printData.outNumber }}</div>
            <div class="info" v-if="printData.masterId">座位号：{{ printData.masterId }}</div>
          </div>
          <div class="shop_info">
            <div class="name">{{ printData.name }}</div>
            <div class="text" v-if="printData.skuName">【{{ printData.skuName }}】</div>
          </div>
          <div class="time">{{ printData.createdAt }}</div>
          <div class="tips">建议尽快享用，风味更佳 {{ printData.count }}</div>
        </div>
        <div class="btn_wrap">
          <div class="btn">
            <el-button plain style="width: 100%" @click="printHandle">
              打印测试小票
            </el-button>
          </div>
          <div class="btn">
            <el-button type="primary" style="width: 100%" :loading="loading" @click="submitHandle">
              保存
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
  <classify ref="classifyRef" @success="(e) => (form.config.categoryList = e)" />
</template>

<script setup>
import _ from 'lodash'
import { ipcRenderer } from "electron";
import { onMounted, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, dayjs } from "element-plus";
import { tbPrintMachinePost, tbPrintMachineDetail } from "@/api/device";
import { useUser } from "@/store/user.js";
import { Loading } from "element-plus/es/components/loading/src/service";
import classify from "@/components/classify/index.vue";
import QRCode from 'qrcode'
import { usePrint } from "@/store/print.js";

const printStore = usePrint();

const store = useUser();

const router = useRouter();
const route = useRoute();

const classifyRef = ref(null);
const printList = ref([]);
const feets = ref([0, 1, 2, 3, 4, 5, 8]);
const loading = ref(false);
const form = ref({
  id: "",
  contentType: "",
  connectionType: "USB",
  config: {
    deviceName: "",
    width: "40", // 设备尺寸毫米mm
    printerNum: 1, //打印份数
    categoryList: [], // 商品分类
    model: "normal", // 出品模式,
    feet: "2",
    autoCut: 0,
    printSub: 1,
  },
  name: "标签打印机",
  subType: "label", // 打印类型
  status: 1,
  sort: "",
  shopId: store.userInfo.shopId,
});

const canvasRef = ref(null)
const printData = ref({
  deviceName: '',
  outNumber: '123',
  name: '甜橙马黛茶',
  skuName: '加奶、加珍珠',
  masterId: '#A9',
  createdAt: dayjs().format('YYYY-MM-DD HH:mm:ss')
})

// 获取打印机列表
function getPrintList() {
  ipcRenderer.send("getPrintList");
  ipcRenderer.on("printList", (event, arg) => {
    printList.value = arg;
  });
}

// 测试打印
const printHandle = _.throttle(function () {
  if (!form.value.config.deviceName) {
    ElMessage.error("请选择打印设备");
    return;
  }
  printData.value.deviceName = form.value.config.deviceName
  ipcRenderer.send(
    "printerTagSync",
    JSON.stringify(printData.value)
  );
}, 1500, { leading: true, trailing: false })

// 提交打印机
async function submitHandle() {
  try {
    if (!form.value.config.deviceName) {
      ElMessage.warning("请选择打印设备");
      return;
    }
    Loading.value = true;
    await tbPrintMachinePost(form.value, form.value.id ? "put" : "post");
    Loading.value = false;
    ElMessage.success(form.value.id ? "编辑成功" : "添加成功");
    printStore.init();
    router.back();
  } catch (error) {
    console.log(error);
  }
}

// 查询打印机详情
async function tbPrintMachineDetailAjax() {
  try {
    const res = await tbPrintMachineDetail(route.query.id);
    form.value = res;
    printData.value.deviceName = res.config.deviceName
  } catch (error) {
    console.log(error);
  }
}

onMounted(() => {
  getPrintList();
  if (route.query.id) {
    tbPrintMachineDetailAjax(route.query.id);
  }

  QRCode.toCanvas(canvasRef.value, printData.value.outNumber, function (error) {
    if (error) console.error(error)
    // console.log('success!');
  })
});
</script>

<style scoped lang="scss">
.device_container {
  width: 100vw;
  height: 100vh;
  padding: 15px;
  background-color: #f1f1f1;
}

.header {
  height: 50px;
  background-color: #fff;
  border-radius: 10px;
  display: flex;
  align-items: center;
  padding: 0 10px;
}

.d_content {
  padding-top: 15px;
  display: flex;
  height: calc(100vh - 15px * 2 - 50px);

  .d_list {
    flex: 2;
    border-radius: 10px;
    background-color: #fff;
    padding: 15px;
  }

  .menu_wrap {
    flex: 1.5;
    margin-left: 15px;
    background-color: #fff;
    border-radius: 10px;
    padding: 0 15px;

    .print_view {
      position: relative;

      .ewm {
        $size: 50px;
        width: $size;
        height: $size;
        position: absolute;
        top: 0;
        right: 0;
        z-index: 99;
      }

      .header {
        display: flex;
        align-items: center;

        .logo {
          $size: 90px;
          width: $size;
        }

        .title {
          margin-left: 6px;
        }
      }

      .number_wrap {
        display: flex;
        align-items: flex-end;

        .num {
          font-size: 18px;
          font-weight: bold;
        }

        .info {
          margin-left: 12px;
          padding-bottom: 4px;
        }
      }

      .time {
        font-weight: bold;
      }
    }

    .btn_wrap {
      display: flex;
      gap: 20px;
      padding: 20px 0;

      .btn {
        flex: 1;
      }
    }
  }
}
</style>
