<template>
  <div class="page-container row-container">
    <!-- 左侧区域 -->
    <section class="list-part-container">
      <!-- 搜索区域 -->
      <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item class="section-title" label="载具类别" />
        <el-form-item>
          <!-- <el-button type="success" icon="Refresh" @click="handleQueryCategory">刷新</el-button> -->
          <el-button type="primary" icon="Plus" @click="handleShowCategoryDialog(null)"
            v-hasPermi="['business:carrier:add']">新增
          </el-button>
        </el-form-item>
        <el-form-item>
          <!-- <el-button type="success" icon="Refresh" @click="handleQueryCategory">刷新</el-button> -->
          <el-button type="primary" icon="Plus" @click="handleMultipleCategoryDialog(null)" v-hasPermi="['*:*:*']">批量新增
          </el-button>
        </el-form-item>
      </el-form>
      <!-- 列表区 -->
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-tree ref="categoryTable" v-loading="categoryLoading" :data="carrierCategoryList"
            :props="{ label: 'name', children: 'children' }" :expand-on-click-node="false" default-expand-all
            node-key="id" highlight-current @node-click="handleCurrentCategoryChange">
            <template #default="{ node, data }">
              <div style="
                  display: flex;
                  width: 100%;
                  justify-content: space-between;
                ">
                <span>
                  <span v-if="data.parentId == 0" style="display: inline-block; width: 20px">{{ getNodeIndex(data) }}.
                  </span>
                  <span>{{ node.label }}</span>
                </span>
                <span>
                  <el-button link type="warning" icon="Edit" @click="handleShowCategoryDialog(data)"
                    v-hasPermi="['business:carrier:edit']">编辑
                  </el-button>
                  <el-button link type="danger" icon="Delete" @click="handleDeleteCategory(data)"
                    v-hasPermi="['business:carrier:remove']">删除
                  </el-button>
                </span>
              </div>
            </template>
          </el-tree>
        </div>
      </div>
    </section>

    <!-- 右侧区域 -->
    <section class="list-part-container" style="flex: 2">
      <el-form class="list-search-container" :model="carrierParams" ref="queryRef" :inline="true">
        <el-form-item class="section-title" label="载具管理" />
        <el-form-item label="载具编号：">
          <el-input placeholder="请输入载具编号" :disabled="!carrierFlag" clearable style="width: 120px"
            v-model.trim="carrierParams.code" @keydown.enter.prevent />
        </el-form-item>
        <el-form-item label="载具状态：">
          <el-select placeholder="请选择载具状态" clearable style="width: 140px" v-model.trim="carrierParams.isAbandoned">
            <el-option v-for="dict in carrier_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="打印状态：">
          <el-select placeholder="请选择打印状态" clearable style="width: 140px" v-model.trim="carrierParams.isPrint">
            <el-option v-for="dict in printStatus" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="info" icon="Search" :disabled="carrierCategoryList.length == 0" @click="handleQueryCarrier">
            搜索
          </el-button>
          <!-- <el-button type="primary" icon="Plus" @click="handleShowCarrierDialog(null)" v-hasPermi="['business:carrier:add']">新增</el-button> -->
          <el-button :disabled="selections.length == 0" type="warning" icon="Download"
            @click="handleBatchDownloadQrCode">批量下载二维码</el-button>
          <el-button :disabled="selections.length == 0" type="warning" icon="Printer"
            @click="handleBatchPrintQrCode">打印</el-button>
          <!-- <el-button :disabled="selections.length == 0" type="warning" icon="Printer" @click="handleBatchPrintPdf">pdf</el-button> -->
        </el-form-item>
      </el-form>

      <!-- 列表区 -->
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-table v-loading="carrierLoading" row-key="id" @selection-change="handleSelectionChange"
            :data="carrierList" height="100%">
            <el-table-column type="selection" width="40" align="center" :reserve-selection="true" />
            <el-table-column type="index" label="行号" width="50" align="center" />
            <el-table-column prop="code" label="载具编号" width="80" align="center" />
            <el-table-column label="载具状态" width="80" prop="isAbandoned" align="center">
              <template #default="scope">
                <dict-tag :options="carrier_status" :value="scope.row.isAbandoned" />
              </template>
            </el-table-column>
            <!--            <el-table-column label="是否多批" width="80" prop="isAllowMore" align="center">-->
            <!--              <template #default="scope">-->
            <!--                {{ scope.row.status }}-->
            <!--                <dict-tag :options="is_allow_more" :value="scope.row.isAllowMore" />-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <el-table-column prop="createTime" label="添加日期" align="center">
              <template #default="scope">
                {{
                  proxy
                    .moment(scope.row.createTime)
                    .format("YYYY-MM-DD HH:mm:ss")
                }}
              </template>
            </el-table-column>
            <!-- <el-table-column prop="remark" label="备注" align="center" /> -->
            <el-table-column label="打印状态" width="80" align="center">
              <template #default="scope">
                {{ scope.row.isPrint == 1 ? '已打印' : '未打印' }}
              </template>
            </el-table-column>
            <!-- <el-table-column prop="abandonmentDate" label="废弃日期" width="120" align="center">
              <template #default="scope">
                {{
                  scope.row.abandonmentDate && proxy.moment(scope.row.abandonmentDate).format('YYYY-MM-DD') !== '1970-01-01'
                    ? proxy.moment(scope.row.abandonmentDate).format('YYYY-MM-DD')
                    : '-'
                }}
              </template>
            </el-table-column>
            <el-table-column prop="abandonmentReason" label="废弃原因" align="center">
              <template #default="scope">
                {{ scope.row.abandonmentReason ? scope.row.abandonmentReason : '-' }}
              </template>
            </el-table-column> -->
            <el-table-column label="操作" width="180" align="center">
              <template #default="scope">
                <!--                <el-button-->
                <!--                  link-->
                <!--                  type="warning"-->
                <!--                  icon="Edit"-->
                <!--                  @click="handleShowCarrierDialog(scope.row.id)"-->
                <!--                  v-hasPermi="['business:carrier:edit']"-->
                <!--                >-->
                <!--                  编辑-->
                <!--                </el-button>-->
                <el-button  link type="primary" icon="Comment"
                  @click="handleCheckHidtory(scope.row)" >
                  废弃明细
                </el-button>
                <el-button v-if="scope.row.isAbandoned === 0" link type="danger" icon="Delete"
                  @click="handleShowAbandonDialog(scope.row.id)" v-hasPermi="['business:carrier:abandonment']">
                  废弃
                </el-button>
                <el-button v-else link type="success" icon="CircleCheck" @click="handleUnAbandoned(scope.row)"
                  v-hasPermi="['business:carrier:unAbandonment']">取消废弃
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 分页 -->
      <pagination v-show="carrierTotal > 0" :total="carrierTotal" v-model:page="carrierParams.pageNum"
        v-model:limit="carrierParams.pageSize" @pagination="getCarriers" />
    </section>

    <!-- 载具类别表单 -->
    <carrier-category-form ref="carrierCategoryRef" @handleSaveSuccess="handleQueryCategory" />
    <multiple-category-form ref="multipleCategoryRef" @handleSaveSuccess="handleQueryCategory" />

    <!-- 载具表单 -->
    <carrier-form ref="carrierRef" @handleSaveSuccess="handleRefreshCarrier" />

    <!-- 废弃弹窗 -->
    <carrier-abandonment-form ref="carrierAbandonmentRef" @handleSaveSuccess="handleRefreshCarrier" />
    <div id="image-group" style="height: 0px; width: 0px">
      <el-image v-for="item in selections" :key="item.id" :src="webHost + item.qcCode" fit="cover"
        style="width: 100mm; height: 100mm">
      </el-image>
    </div>
  </div>
</template>

<script setup name="Process">
import {
  listCategory,
  delCategory,
  listCarrier,
  saveCarrierReject,
  download,
  printQrcodePdf,
  whether,
  printUpdate
} from "@/api/business/carrier";
import carrierForm from "./form";
import printJS from "print-js";
import carrierCategoryForm from "./formCategory";
import carrierAbandonmentForm from "./formAbandonment";
import multipleCategoryForm from "./multipleForm";
import router from "@/router";
import { nextTick } from "vue";
import JSZip from "jszip";
import { saveAs } from "file-saver";
import carrierStore from "@/store/modules/carrier";
const { proxy } = getCurrentInstance();
const { carrier_status } = proxy.useDict("carrier_status");
const { is_allow_more } = proxy.useDict("is_allow_more");
const webHost = import.meta.env.VITE_APP_PRODUCTION_API;
const categoryTable = ref(null);
const carrierCategoryList = ref([]);
const carrierList = ref([]);
const currentCategory = ref({});
const carrierFlag = ref(true);
const categoryLoading = ref(false);
const carrierLoading = ref(false);
const carrierTotal = ref(0);
const selections = ref([]);
const printStatus = ref([{
  label: '未打印',
  value: 0
}, {
  label: '已打印',
  value: 1
}])
const data = reactive({
  form: {},
  queryParams: {
    code: "",
    pageNum: 1,
    pageSize: 10,
  },
  carrierParams: {
    code: "",
    pageNum: 1,
    pageSize: 10,
  },
});

const { queryParams, carrierParams } = toRefs(data);

/****************************  载具类别相关事件  ****************************/
/** 载具分类列表 */
const getCategories = () => {
  categoryLoading.value = true;
  listCategory().then((res) => {
    categoryLoading.value = false;
    carrierCategoryList.value = res.rows;
    if (carrierCategoryList.value.length > 0) {
      currentCategory.value = carrierCategoryList.value[0];
      nextTick(() => {
        proxy.$refs.categoryTable.setCurrentKey(currentCategory.value.id);
        handleCurrentCategoryChange(currentCategory.value);
      });
    }
  });
};

/**
 * 批量新增载具
 */
const handleMultipleCategoryDialog = () => {
  proxy.$refs.multipleCategoryRef.open();
};
//查看历史记录
function handleCheckHidtory(row) {
  carrierStore().setCategoryIdQueryParams(row.categoryId)
  carrierStore().setCarrierCodeQueryParams(row.code)
  router.push({ path: "/select/reject" });
}
/**载具类别点击事件 */
const handleCurrentCategoryChange = (row) => {
  if (row) {
    currentCategory.value = row;
  } else {
    currentCategory.value = {};
    if (carrierCategoryList.value.length > 0) {
      currentCategory.value = carrierCategoryList.value[0];
    }
  }
  if (currentCategory.value.id) {
    getCarriers();
  } else {
    carrierList.value = [];
    carrierTotal.value = 0;
  }
};
/**载具类别编号 */
function getNodeIndex(data) {
  const index = carrierCategoryList.value.findIndex(
    (item) => item.id === data.id
  );
  return index + 1;
}
/**打开载具类别弹窗 */
function handleShowCategoryDialog(data) {
  if (data) {
    proxy.$refs.carrierCategoryRef.open(data.id);
  } else {
    proxy.$refs.carrierCategoryRef.open();
  }
}

/** 删除按钮操作 */
const handleDeleteCategory = (data) => {
  // 禁用按钮点击
  disableButtons();
  var showErrorMessage = false;
  proxy.$modal
    .confirm("确定删除选中项？")
    .then(() => {
      categoryLoading.value = true;
      carrierLoading.value = true;
      if (data.children) {
        showErrorMessage = true;
        return Promise.reject(new Error("HasChildrenError"));
      }
      return delCategory(data.id);
    })
    .then(() => {
      if (!showErrorMessage) {
        proxy.$modal.msgSuccess("操作成功！");
        getCategories();
      }
    })
    .catch(() => {
      categoryLoading.value = false;
      carrierLoading.value = false;
    })
    .finally(() => {
      if (showErrorMessage) {
        proxy.$modal.msgError("该载具类别下有子类别，不能删除");
      }
      categoryLoading.value = false;
      carrierLoading.value = false;
      // 启用按钮点击
      enableButtons();
    });
};
/**禁用按钮 */
function disableButtons() {
  //禁用按钮同时，禁用载具编号的输入框
  carrierFlag.value = false;
  // 禁用页面上所有按钮的点击事件
  const buttons = document.querySelectorAll("button");
  buttons.forEach((button) => {
    button.disabled = true;
  });
}
/**取消禁用按钮 */
function enableButtons() {
  carrierFlag.value = true;
  // 启用页面上所有按钮的点击事件
  const buttons = document.querySelectorAll("button");
  buttons.forEach((button) => {
    button.disabled = false;
  });
}
/**载具类别查询 */
const handleQueryCategory = () => {
  getCategories();
};
/****************************  载具相关事件  ****************************/
/**获取载具数据 */
const getCarriers = () => {
  disableButtons();
  categoryLoading.value = true;
  carrierLoading.value = true;
  carrierParams.value.categoryId = currentCategory.value.id;
  listCarrier(carrierParams.value).then((res) => {
    enableButtons();
    categoryLoading.value = false;
    carrierLoading.value = false;
    carrierList.value = res.rows;
    carrierTotal.value = res.total;
  });
};

/**
 * 列表checkbox列选择 事件
 */
function handleSelectionChange(selection) {
  selections.value = selection;
  console.log(selections.value);
}
/**刷新载具 */
const handleRefreshCarrier = () => {
  getCarriers();
};
/**载具查询 */
const handleQueryCarrier = () => {
  carrierParams.value.pageNum = 1;
  handleRefreshCarrier();
};

/** 修改按钮操作 */
const handleShowCarrierDialog = (id) => {
  proxy.$refs.carrierRef.open({ categoryId: currentCategory.value.id, id: id });
};
/**打开废弃弹窗 */
const handleShowAbandonDialog = (id) => {
  proxy.$refs.carrierAbandonmentRef.open({ id: id });
};
/** 取消废弃*/
const handleUnAbandoned = (row) => {
  proxy.$modal
    .confirm("确定取消废弃选中项？")
    .then(() => {
      var carrierReject = {};
      carrierReject.carrierId = row.id;
      carrierReject.isAbandoned = 0;
      carrierReject.operaionDate = proxy.moment().format("YYYY-MM-DD");
      return saveCarrierReject(carrierReject);
    })
    .then(() => {
      proxy.$modal.msgSuccess("操作成功！");
      handleRefreshCarrier();
    })
    .catch(() => { });
};

const handleBatchPrintQrCode = async () => {
  // whether(selections.value).then((res) => {
  //   if (res.code == 200) {
  //     const imageGroup = document.getElementById("image-group");
  //     // for (var i = 0; i < selections.value.length; i++) {
  //     //   console.log(webHost + selections.value[i].qcCode);
  //     //   const img = document.createElement('img');
  //     //   img.src = webHost + selections.value[i].qcCode
  //     //   imageGroup.appendChild(img);
  //     // }
  //     printJS({
  //       printable: "image-group", // 这里是你要打印内容的DOM元素的id
  //       type: "html",
  //       style: "@page { size: auto;  margin: 0mm; }", // 可以添加打印样式
  //     });
  //     // window.print();
  //   }

  // });
  if(selections.value.length >0){
  const res = await whether(selections.value)
  if (res.code == 200) {
    const imageGroup = document.getElementById("image-group");
    const res1 = await printUpdate(selections.value.map(e => e.id))
    if (res1.code == 200) {
      handleRefreshCarrier()
      printJS({
        printable: "image-group", // 这里是你要打印内容的DOM元素的id
        type: "html",
        style: "@page { size: auto;  margin: 0mm; }", // 可以添加打印样式
      });
    }
    // window.print();
  }
  }
};

const handleBatchPrintPdf = () => {
  printQrcodePdf(selections.value.map((v) => v.id)).then((res) => {
    const blob = new Blob([res], { type: "application/pdf" });
    var url = URL.createObjectURL(blob);
    window.open(url, "filename");
  });
};

// /** 批量下载二维码 */
// function handleBatchDownloadQrCode() {
//   console.log(selections.value)
//   for (var i = 0; i < selections.value.length; i++) {
//     console.log(webHost + selections.value[i].qcCode)

//     var link = document.createElement('a')
//     link.href = webHost + selections.value[i].qcCode
//     link.download = selections.value[i].code // 可以根据需要设置下载的文件名
//     link.target = '_blank' // 可以根据需要选择是否在新窗口中下载
//     link.click()
//   }
//   // download({}).then((res) => {
//   //   if (res.code === 200) {
//   //     proxy.$modal.msgSuccess('操作成功！')
//   //   }
//   // })
// }
/**批量下载二维码 */
async function handleBatchDownloadQrCode() {
  if(selections.value.length >0){
  console.log(selections.value);

  whether(selections.value).then(async (res) => {
    if (res.code == 200) {
      const zip = new JSZip();
      const zipFilename = "二维码.zip";
      for (var i = 0; i < selections.value.length; i++) {
        console.log(webHost + selections.value[i].qcCode);

        // 下载二维码图片数据
        const qrCodeResponse = await fetch(
          webHost + selections.value[i].qcCode
        );
        const qrCodeBlob = await qrCodeResponse.blob();

        // 将二维码图片添加到 ZIP 文件中
        zip.file(selections.value[i].code + ".png", qrCodeBlob);
      }
      // 生成 ZIP 文件并提供下载
      zip.generateAsync({ type: "blob" }).then((content) => {
        // 使用 FileSaver.js 将 ZIP 文件保存到本地
        saveAs(content, zipFilename);
      });
    }
  });
}
}

onMounted(() => {
  getCategories();
});
</script>
<style scoped>
:deep(.el-tree-node__label) {
  font-size: 14px !important;
  display: inline-block;
  width: 100%;
}

:deep(.el-tree-node__content) {
  height: 40px;
  border-bottom: 1px solid #ebeef5;
  padding: 8px 0;
  line-height: 23px;
}
</style>
