<template>
  <my-layout v-loading="loading">
    <layout-item>
      <div class="py-10px px-10px mb-10px flex bg-white">
        <expand-filter-box v-model:can-expand="canExpand" :enable-expand="true" class="flex-grow" :expand="expand"
          @keyup.enter="search">
          <input-filter v-model="searchForm.name" label="店铺名称" placeholder="请输入店铺名称" :width="240" />
          <input-filter v-model="searchForm.storeId" label="药店ID" placeholder="请输入药店ID" :width="240" />
          <custom-filter label="所属区域">
            <el-cascader v-model="searchForm.region" clearable filterable :options="region"
              :props="{ checkStrictly: true }" :show-all-levels="false" />
          </custom-filter>
          <!-- <input-filter v-model="searchForm.area" label="所属区域" placeholder="" :width="200" /> -->
          <radio-filter v-model="searchForm.drugStoreType" label="店铺类型" :list="storeTypeList" />
          <radio-filter v-model="searchForm.status" label="店铺状态" :list="statusList" />
          <radio-filter v-model="searchForm.saleWine" label="中药饮片资质" :list="saleWineList" />
        </expand-filter-box>
        <div class="flex-shrink-0 flex items-center h-40px">
          <el-button v-if="canExpand" text plain @click="expand = !expand">
            <span class="mr-5px">{{ expand ? "收起筛选" : "更多筛选" }}</span>
            <el-icon v-if="expand">
              <ArrowUpBold />
            </el-icon>
            <el-icon v-else>
              <ArrowDownBold />
            </el-icon>
          </el-button>
          <el-button type="primary" class="w-80px" @click="search()">查询</el-button>
          <el-button plain class="w-80px" @click="reset">重置</el-button>
        </div>
      </div>
      <div class="p-15px flex items-center bg-white">
        <div class="flex-shrink-0">
          已选店铺：
          <span class="text-red-500">{{ selections.length }}</span>
        </div>
        <el-button class="ml-15px w-100px" type="primary" @click="setStatus(true)">启用</el-button>

        <el-button class="ml-15px w-100px" type="danger" @click="setStatus(false)">停用</el-button>

        <div class="flex-grow"></div>
        <el-button v-if="list.length" plain class="w-100px" :icon="Download" type="primary"
          @click="downloadZip()">批量下载</el-button>
        <el-button class="w-100px" :icon="Plus" type="primary" @click="edit()">新增</el-button>
      </div>
    </layout-item>
    <layout-main :scroll="false">
      <el-table border stripe :data="list" ref="tableRef" height="100%" @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" :width="55" />
        <el-common-column prop="index" label="序号" :width="80">
          <template #default="{ index }">
            <span>{{ index + 1 }}</span>
          </template>
        </el-common-column>
        <el-common-column prop="name" label="店铺名称" :min-width="180">
          <template #default="{ row }">
            <el-text class="text-blue-500 cursor-pointer hover:underline underline-offset-4"
              @click="previewStore(row)">{{ row.name }}</el-text>
          </template>
        </el-common-column>
        <el-common-column prop="store_id" label="店铺ID" :min-width="100" />
        <!-- <el-common-column prop="account" label="关联账号" :min-width="100" /> -->
        <el-common-column prop="fee" label="互联网诊查费" :min-width="100">
          <template #default="{ row: { chargeItems } }">
            <span>{{ chargeItems && chargeItems[0] ? chargeItems[0].fee : "" }}</span>
          </template>
        </el-common-column>
        <el-common-column prop="region" label="所属区域" :min-width="100">
          <template #default="{ row: { region } }">
            <span>{{ region && region[region.length - 1] ? region[region.length - 1] : "" }}</span>
          </template>
        </el-common-column>
        <el-common-column prop="type" label="店铺类型" :min-width="100" />
        <el-table-column prop="status" :width="160">
          <template #header>
            <el-tooltip effect="light" content="店铺停用后，所有店铺关联人员账号无法使用" placement="top">
              <div class="flex items-center">
                <span>店铺状态</span>
                <el-icon class="text-gray-500">
                  <QuestionFilled />
                </el-icon>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-common-column fixed="right" prop="action" label="操作" :width="140">
          <template #default="{ row }">
            <div class="text-center">
              <el-text type="primary" class="mr-10px cursor-pointer" @click="edit(row)">编辑</el-text>
              <el-text type="primary" class="cursor-pointer" @click="showQrcode(row)">下载</el-text>
            </div>
          </template>
        </el-common-column>
      </el-table>
    </layout-main>
    <layout-item>
      <pagination :totalRow="total" :pageSize="pageSize" :currentPage="page" @handle-size-change="changeSize"
        @handle-current-change="changePage" />
    </layout-item>
  </my-layout>
  <preview-modal :store="store" :visible="previewVisible" @close="previewVisible = false" />
  <store-drawer :data="store" :visible="visible" @change="search" @close="visible = false" />
  <store-qrcode :store="store" :visible="qrcodeVisible" @close="qrcodeVisible = false" />
</template>
<script setup>
import { ref, onMounted, computed, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import QRCode from "qrcode";
import JSZip from "jszip";
import { saveAs } from "file-saver";
import useElPagination from "@/hooks/useElPagination";
import { getDrugStoreList, setDrugStoreStatus } from "@/api/hlw";
import region from "@/baseData/region.js";
import { storeStatus, storeType } from "./dict.js";

import elCommonColumn from "@/components/el-common-column/el-common-column.vue";
import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import pagination from "@/components/pagination/pagination.vue";
import previewModal from "./preview-modal.vue";
import storeDrawer from "./store-drawer.vue";
import storeQrcode from "./store-qrcode.vue";
import { InputFilter, RadioFilter, expandFilterBox, CustomFilter } from "@/components/filter-bar";
import { Plus, Download } from "@element-plus/icons-vue";

const storeTypeList = storeType.map((i) => ({ label: i, value: i }));
const statusList = storeStatus.map((i) => ({ label: i, value: i }));
const saleWineList = [{ label: '有', value: 'Y' }, { label: '无', value: 'N' }]

const canExpand = ref(false);
const expand = ref(false);
const loading = ref(false);
const previewVisible = ref(false);
const qrcodeVisible = ref(false);
const searchForm = ref({});
const query = ref({});
const selections = ref([]);
const store = ref({});
const tableRef = ref(null);
const total = ref(0);
const visible = ref(false);
const { list, page, pageSize, changePage, changeSize } = useElPagination(getList);

function edit(row = {}) {
  store.value = row;
  visible.value = true;
}

function handleSelectionChange(val) {
  selections.value = val.map((i) => i._id);
}

function previewStore(row) {
  store.value = row;
  previewVisible.value = true;
}

function reset() {
  searchForm.value = {};
  search();
}

function search() {
  const { saleWine, ...rest } = searchForm.value;
  query.value = { ...rest };
  if (['Y', 'N'].includes(saleWine)) {
    query.value.saleWine = saleWine === 'Y'
  }
  changePage(1);
}

function showQrcode(row) {
  store.value = row;
  qrcodeVisible.value = true;
}

async function getList() {
  loading.value = true;
  const { success, data, message } = await getDrugStoreList({ ...query.value, page: page.value, pageSize: pageSize.value });
  loading.value = false;
  tableRef.value && tableRef.value.clearSelection();
  if (success) {
    list.value = Array.isArray(data.list) ? data.list : [];
    total.value = data.total || 0;
  } else {
    ElMessage.error(message);
  }
}

async function setStatus(bool) {
  if (selections.value.length === 0) {
    ElMessage.info(`请选择要${bool ? '启用' : '停用'}的店铺`);
    return;
  }
  await ElMessageBox.confirm(`确定要${bool ? '启用' : '停用'}选中的店铺吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
  const { success, message } = await setDrugStoreStatus({ ids: selections.value, status: bool });
  if (success) {
    ElMessage.success(message);
    search();
  } else {
    ElMessage.error(message);
  }
}

async function downloadZip() {
  const zip = new JSZip();
  for (const item of list.value) {
    // 设置更大的二维码尺寸和更高的清晰度
    const qrSize = 600; // 增大二维码尺寸提高清晰度
    const displaySize = 300; // 显示尺寸
    const padding = 20; // 边距
    const textHeight = 40; // 文本区域高度
    const totalWidth = displaySize + padding * 2;
    const totalHeight = displaySize + textHeight + padding * 2;

    // 创建canvas元素，使用2倍于显示尺寸的大小来增加清晰度
    const canvas = document.createElement("canvas");
    canvas.width = totalWidth * 2;
    canvas.height = totalHeight * 2;
    const context = canvas.getContext("2d");

    // 使用更高的缩放比例来提高渲染质量
    context.scale(2, 2);

    // 填充白色背景
    context.fillStyle = "#ffffff";
    context.fillRect(0, 0, totalWidth, totalHeight);

    // 生成高质量二维码
    const qrCodeDataURL = await QRCode.toDataURL(`https://zyt.youcan365.com/store?storeId=${item.store_id}`, {
      margin: 0,
      width: qrSize,
      scale: 8, // 更高的缩放比例
      errorCorrectionLevel: "H",
      quality: 1.0, // 最高质量
    });

    // 加载二维码图像
    const img = new Image();
    img.src = qrCodeDataURL;

    // 等待二维码图像加载完成
    await new Promise((resolve) => {
      img.onload = resolve;
    });

    // 绘制二维码到canvas上，居中显示
    context.drawImage(img, padding, padding, displaySize, displaySize);

    // 设置文本样式
    context.font = "bold 16px Arial";
    context.textAlign = "center";
    context.fillStyle = "#000";
    context.textBaseline = "middle";

    // 在二维码下方绘制文本
    context.fillText(item.name, totalWidth / 2, displaySize + padding + textHeight / 2);

    // 将canvas转换为高质量的PNG图像
    const qrCodeData = canvas.toDataURL("image/png", 1.0);

    // 将二维码添加到ZIP文件
    const fileName = `${item.name}.png`;
    zip.file(fileName, qrCodeData.split(",")[1], { base64: true });
  }
  zip.generateAsync({ type: "blob" }).then(function (content) {
    saveAs(content, "qr_codes.zip"); // 下载 ZIP 文件
  });
}

onMounted(() => {
  changePage(1);
});
</script>
<style lang="scss" scoped></style>
