<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-input v-model="form.name" placeholder="请输入设备名称"></el-input>
          </el-form-item>
          <el-form-item label="设备尺寸">
            <el-select v-model="form.receiptSize">
              <el-option label="58mm" value="58mm"></el-option>
              <el-option label="80mm" value="80mm"></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.address">
              <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="商品分类">
            <div style="cursor: pointer" @click="classifyRef.show()">
              <span style="color: #409eff" v-if="form.categoryList.length">
                {{form.categoryList.map(item => item.name).join(',')}}
              </span>
              <span style="color: #e65d6e" v-else>
                请选择分类
              </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="printData.ticketLogo || logo" />
            <!-- <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.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 { printerAdd, printerDetail } from "@/api/account.js";
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";
import { useGoods } from '@/store/goods.js'
import logo from '@/assets/prinnt_label_logo.png';

const goodsStore = useGoods()
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: "",
  name: '', // 设备名称
  connectionType: 'USB', // 现在打印机支持USB 和 网络、蓝牙
  address: '', // 打印机名称
  port: '', // 端口
  subType: 'label', // 打印类型（分类）label标签cash小票kitchen出品
  contentType: '', // 打印机品牌
  categoryIds: [], // 打印分类Id
  categoryList: [], // 分类
  sort: '',
  receiptSize: '58mm', // 小票尺寸 58mm 80mm
  classifyPrint: 1, // 分类打印 0-所有 1-部分分类 2-部分商品
  printQty: '', // 打印数量 c1m1^2 = 顾客+商家[2张] m1^1 = 商家[1张] c1^1顾客[1张] c2m1^3顾客2+商家1[3张]
  printMethod: 'all', // 打印方式 all-全部打印 normal-仅打印结账单「前台」one-仅打印制作单「厨房」queue-仅打印排队取号
  printType: [], // 打印类型，JSON数组 refund-确认退款单 handover-交班单 queue-排队取号
  status: 1
});

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

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

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

// 提交打印机
async function submitHandle() {
  try {
    if (!form.value.name) {
      ElMessage.error("请输入设备名称");
      return;
    }
    if (!form.value.address) {
      ElMessage.error("请选择打印设备");
      return;
    }
    if (!form.value.categoryList.length) {
      ElMessage.error("请选择商品分类");
      return;
    }
    Loading.value = true;
    form.value.categoryIds = form.value.categoryList.map(item => item.id)
    await printerAdd(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 printerDetail({ id: route.query.id });
    form.value = res;

    let arr = []
    goodsStore.originCategoryList.map(item => {
      res.categoryList.map(val => {
        if (item.id == val) {
          arr.push({
            id: item.id,
            name: item.name
          })
        }
      })
    })
    form.value.categoryList = arr
  } 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;
          height: 30px;
          object-fit: cover;
        }

        .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>
