<!-- 结算订单 -->

<template>
  <el-drawer size="100%" :with-header="false" direction="btt" v-model="dialogVisible">
    <div class="drawer_wrap">
      <div class="cart_list">
        <div class="nav_wrap card">
          <div class="return" @click="dialogVisible = false">
            <el-icon class="icon">
              <ArrowLeftBold />
            </el-icon>
          </div>
          <div class="info">
            <div class="master_id">
              <span>{{ props.masterId }}</span>
              <span class="member_info" v-if="memberInfo.telephone">会员：{{ memberInfo.telephone }}</span>
            </div>
            <div class="btm">
              <span class="p">服务员：{{ store.userInfo.shopName || "暂无" }}</span>
              <span class="t">{{
                props.orderInfo.createdAt &&
                dayjs(props.orderInfo.createdAt).format("MM-DD HH:mm")
              }}</span>
            </div>
          </div>
        </div>
        <div class="list_wrap card" style="margin-top: var(--el-font-size-base)">
          <div class="item" v-for="item in props.cart" :key="item.id">
            <div class="top">
              <span class="name">{{ item.name }}</span>
              <span class="n">x{{ item.number }}</span>
              <span class="p">￥{{ item.salePrice }}</span>
            </div>
            <div class="gift_wrap" v-if="item.isGift == 'true'">
              <span>[赠送]</span>
              <span>￥-{{ item.salePrice }}</span>
            </div>
            <div class="tag_wrap" v-if="item.skuName">
              <div class="tag" v-for="item in item.skuName.split(',')">
                {{ item }}
              </div>
            </div>
            <div class="packge_Wrap" v-if="item.isPack == 'true'">
              <div class="icon_item" v-if="item.isPack == 'true'" @click="giftPackHandle('isPack', item)">
                <el-icon class="icon" style="color: var(--primary-color)">
                  <Box />
                </el-icon>
              </div>
            </div>
          </div>
        </div>
        <div class="footer">
          <!-- <el-button icon="Edit"></el-button> -->
          <div class="button">
            <el-checkbox v-model="isPrint" border label="打印结算小票" style="width: 100%" />
          </div>
          <div class="print">
            <el-button type="primary" v-loading="printLoading" @click="printHandle">打印预结单</el-button>
          </div>
        </div>
      </div>
      <div class="pay_wrap">
        <payCard :amount="props.amount" :member="props.member" :orderId="props.orderInfo.id" @paySuccess="paySuccess" />
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import _ from 'lodash'
import { onMounted, ref } from "vue";
import { useUser } from "@/store/user.js";
import payCard from "@/components/payCard/payCard.vue";
import { print } from "@/api/pay";
import { bySubType } from "@/api/device";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import useStorage from '@/utils/useStorage'

import { ipcRenderer } from "electron";

const store = useUser();

const emit = defineEmits("paySuccess");

const printLoading = ref(false);

const dialogVisible = ref(false);
const props = defineProps({
  cart: {
    type: Array,
    default: [],
  },
  amount: {
    type: [Number, String],
    default: 0,
  },
  remark: {
    type: String,
    default: "",
  },
  orderInfo: {
    type: Object,
    default: "",
  },
  masterId: {
    type: String,
    default: "",
  },
  member: {
    type: Object,
    default: {}
  }
});

const isPrint = ref(true);

// 小票打印机列表
const printList = ref([]);

// 标签打印机列表
const printLabelList = ref([]);
const localPrintList = ref([])

// 获取打印机状态
async function bySubTypeAjax() {
  try {
    const res1 = await bySubType({
      shopId: store.userInfo.shopId,
      contentType: "local",
      subType: "cash",
    });
    const res2 = await bySubType({
      shopId: store.userInfo.shopId,
      contentType: "local",
      subType: "label",
    });
    printList.value = res1;
    printLabelList.value = res2;
  } catch (error) {
    console.log(error);
  }
}

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

// 检查本地打印机是否能正常使用
function checkLocalPrint(deviceName) {
  let print = ''
  for (let item of localPrintList.value) {
    if (item.name == deviceName) {
      print = item
    }
  }

  if (!print.name) {
    return false
  } else {
    return true
  }
}

// 检测是否打印标签小票
function checkLabelPrint(props) {
  console.log(props);
  if (!checkLocalPrint(printLabelList.value[0].config.deviceName)) {
    ElMessage.error("本地打印机无法使用，请检查打印机是否正确连接1");
  } else {
    let pids = printLabelList.value[0].config.categoryList.map(item => item.id)
    let labelList = []
    let count = 0
    let sum = 0

    props.carts.map(item => {
      if (pids.some(el => el == item.categoryId)) {
        for (let i = 0; i < item.number; i++) {
          sum++
        }
      }
    })

    props.carts.map(item => {
      if (pids.some(el => el == item.categoryId)) {
        for (let i = 0; i < item.number; i++) {
          count++
          labelList.push(
            {
              outNumber: props.outNumber,
              name: item.name,
              skuName: item.skuName,
              masterId: props.orderInfo.tableName,
              deviceName: printLabelList.value[0].config.deviceName,
              createdAt: dayjs(props.createdAt).format('YYYY-MM-DD HH:mm:ss'),
              count: `${count}/${sum}`
            }
          )
        }
      }
    })

    printLabel(labelList)
  }
}

// 打印标签
const printLabel = (list) => {
  if (!checkLocalPrint(printLabelList.value[0].config.deviceName)) {
    ElMessage.error("本地打印机无法使用，请检查打印机是否正确连接");
  } else {
    for (let i = 0; i <= list.length - 1; i++) {
      setTimeout(() => {
        ipcRenderer.send('printerTagSync', JSON.stringify(list[i]))
      }, i * 1000)
    }
  }
}

// 打印操作
async function printHandle() {
  try {
    if (!isPrint.value) return;
    if (printLabelList.value.length) {
      const data = {
        shop_name: store.userInfo.merchantName,
        carts: props.cart,
        amount: props.amount,
        remark: props.remark,
        orderInfo: props.orderInfo,
        deviceName: printLabelList.value[0].config.deviceName,
        createdAt: dayjs(props.orderInfo.createdAt).format(
          "YYYY-MM-DD HH:mm:ss"
        ),
        printTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
      };
      checkLabelPrint(data)
      // if (!checkLocalPrint(printList.value[0].config.deviceName)) {
      //   ElMessage.error("本地小票打印机无法使用，请检查打印机是否正确连接3");
      // } else {
      //   ipcRenderer.send("printerInfoSync", JSON.stringify(data));
      // }
    } else {
      // ElMessage.error("您还没有添加本地打印设备，将使用网络打印");
      try {
        printLoading.value = true;
        await print({
          type: "normal",
          ispre: true,
          orderId: props.orderInfo.id,
        });
        printLoading.value = false;
        // ElMessage.success("打印成功");
      } catch (error) {
        printLoading.value = false;
        console.log(error);
      }
    }
  } catch (error) {
    console.log(error);
  }
}

// 订单已支付
function paySuccess() {
  useStorage.del('memberInfo')
  dialogVisible.value = false;
  printHandle();
  emit("paySuccess");
}

function show() {
  dialogVisible.value = true;
}

defineExpose({
  show,
});


const memberInfo = ref('')

// 从本地获取会员信息
function getLocalMemberInfo() {
  let localMemberInfo = useStorage.get('memberInfo')
  if (localMemberInfo && localMemberInfo.telephone) {
    memberInfo.value = localMemberInfo
  } else {
    memberInfo.value = ''
  }
}

onMounted(() => {
  getPrintList();
  bySubTypeAjax();
  getLocalMemberInfo()
});
</script>

<style>
.el-drawer {
  background-color: #efefef !important;
}
</style>

<style scoped lang="scss">
.drawer_wrap {
  width: 100%;
  height: 100%;
  display: flex;
  padding: var(--el-font-size-base) 0;

  .cart_list {
    flex: 1;

    .nav_wrap {
      display: flex;
      align-items: center;
      padding: 0 var(--el-font-size-base);

      .return {
        $size: 50px;
        width: $size;
        height: $size;
        border-radius: 50%;
        border: 2px solid #333;
        display: flex;
        align-items: center;
        justify-content: center;

        .icon {
          color: #333;
          font-size: var(--el-font-size-base);
        }
      }

      .info {
        flex: 1;
        padding-left: var(--el-font-size-base);
        $padding: 10px;

        .master_id {
          font-size: calc(var(--el-font-size-base) + 10px);
          border-bottom: 1px solid #ececec;
          padding: $padding 0;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .member_info {
            color: #999;
            font-size: 16px;
          }
        }

        .btm {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: $padding 0;

          .p {
            color: #999;
          }
        }
      }
    }

    .list_wrap {
      padding: var(--el-font-size-base);
      height: calc(100vh - 200px);
      overflow-y: auto;

      .item {
        padding-bottom: var(--el-font-size-base);

        .top {
          display: flex;
          padding-bottom: 6px;

          .name {
            flex: 1;
          }

          .n {
            margin-right: 50px;
            color: #555;
          }

          .p {
            color: #555;
          }
        }

        .gift_wrap {
          display: flex;
          justify-content: space-between;
          color: #999;
          font-size: 16px;
        }

        .tag_wrap {
          display: flex;
          flex-wrap: wrap;
          padding-top: 10px;
          padding-bottom: 10px;

          .tag {
            padding: 2px 6px;
            background-color: var(--el-color-danger);
            color: #fff;
            margin-right: 10px;
            margin-bottom: 10px;
          }
        }

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

          .icon_item {
            $size: 40px;
            width: $size;
            height: $size;
            background-color: #e2e2e2;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
          }
        }
      }
    }

    .footer {
      display: flex;
      padding-top: var(--el-font-size-base);
      gap: var(--el-font-size-base);

      .editor {
        border: 1px solid #ececec;
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #555;
      }

      .button {
        flex: 1;

        :deep(.el-checkbox.el-checkbox--large) {
          height: var(--el-component-size-large);
          background-color: #fff;
        }

        :deep(.el-checkbox__inner) {
          width: 20px;
          height: 20px;

          &::after {
            border-width: 2px;
            top: 3px;
            left: 7px;
          }
        }

        :deep(.el-checkbox__label) {
          font-size: var(--el-font-size-base) !important;
        }
      }
    }
  }

  .pay_wrap {
    flex: 1.5;
    padding-left: 20px;
  }
}
</style>
