<template>
  <div class="app-container">
    <div
      style="
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
      "
    >
      <span>酒款管理</span>
      <el-button
        type="primary"
        @click="handleAdd"
        v-hasPermi="['brewery:beer:add']"
        >新增酒款</el-button
      >
    </div>
    <!-- <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商品名称" prop="beerName">
        <el-input
          v-model="queryParams.beerName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品编码" prop="beerSn">
        <el-input
          v-model="queryParams.beerSn"
          placeholder="请输入商品编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="酒款风格" prop="beerStyles">
        <el-select
          v-model="queryParams.beerStyles"
          placeholder="请选择酒款风格"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="style in beerStyles"
            :key="style.value"
            :label="style.name"
            :value="style.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="市售状态" prop="onSale">
        <el-select
          v-model="queryParams.onSale"
          placeholder="请选择状态"
          clearable
          style="width: 150px"
        >
          <el-option label="在售款" :value="1"></el-option>
          <el-option label="已停产" :value="0"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="上市日期" prop="launchDate">
        <el-date-picker
          clearable
          v-model="queryParams.launchDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择上市日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['brewery:beer:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['brewery:beer:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['brewery:beer:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['brewery:beer:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row> -->

    <el-table
      v-loading="loading"
      :data="beerList"
      @selection-change="handleSelectionChange"
      class="zd-table"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="酒款ID" align="center" prop="id" />
      <!-- <el-table-column label="品牌方id" align="center" prop="breweryId" /> -->
      <el-table-column label="酒款图片" align="center" prop="cover" width="90">
        <template #default="scope">
          <el-image
            style="width: 60px; height: 60px"
            :src="scope.row.cover"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="[scope.row.cover]"
            :initial-index="4"
            fit="cover"
            title="点击查看大图"
            preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column
        label="酒款名称"
        align="center"
        prop="beerName"
        show-overflow-tooltip
      />
      <el-table-column
        label="啤酒风格"
        align="center"
        prop="beerStyles"
        show-overflow-tooltip
      />
      <el-table-column
        label="近30天核销桶数"
        align="center"
        prop="scanCount"
        show-overflow-tooltip
      />
      <el-table-column
        label="参与中活动数量"
        align="center"
        show-overflow-tooltip
        prop="activityCount"
      />
      <!-- <el-table-column
        label="品牌logo"
        align="center"
        prop="brandLogo"
        width="90"
      >
        <template #default="scope">
          <el-image
            style="width: 60px; height: 60px"
            :src="scope.row.brandLogo"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="[scope.row.brandLogo]"
            :initial-index="4"
            fit="cover"
            title="点击查看大图"
            preview-teleported
          />
        </template>
      </el-table-column> -->
      <!-- <el-table-column
        label="酒款编码"
        align="center"
        prop="beerSn"
        show-overflow-tooltip
      /> -->

      <!-- <el-table-column
        label="酒精度"
        align="center"
        prop="beerAbv"
        show-overflow-tooltip
      />
      <el-table-column
        label="苦度值"
        align="center"
        prop="beerIbus"
        show-overflow-tooltip
      />
      <el-table-column
        label="产品条形码"
        align="center"
        prop="barcode"
        show-overflow-tooltip
        width="120"
      /> -->
      <!-- <el-table-column label="市售状态" align="center" prop="onSale">
        <template #default="scope">
          <el-tag v-if="scope.row.onSale === 1" type="success"> 在售款</el-tag>
          <el-tag v-else type="danger"> 已停产</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="approval">
        <template #default="scope">
          <el-tag v-if="scope.row.approval === 1" type="success"> 通过</el-tag>
          <el-tag v-else-if="scope.row.approval === 2" type="danger"> 拒绝</el-tag>
          <el-tag v-else type="info"> 待审核</el-tag>
        </template>
      </el-table-column> -->
      <!-- <el-table-column
        label="原麦汁浓度"
        align="center"
        prop="beerOg"
        width="100"
      /> -->
      <!-- <el-table-column
        label="市场零售价"
        align="center"
        prop="marketPrice"
        width="100"
      /> -->
      <!-- <el-table-column label="市售规格" align="center" prop="specs" /> -->
      <!-- <el-table-column label="描述" align="center" prop="desc" /> -->
      <el-table-column
        label="扫码领取啤酒币数量"
        align="center"
        prop="scanCoinCount"
        min-width="120"
      >
        <template #default="scope">
          <template v-if="currentScanCoinId === scope.row.id">
            <el-input
              v-model="scanCoinCount"
              type="number"
              placeholder="请输入数量"
              style="width: 80px"
            />
            <el-button link type="primary" @click="saveScanCoinCount"
              >保存</el-button
            >
            <el-button link @click="cancelScanCoin">取消</el-button>
          </template>
          <template v-else>
            <span>{{ scope.row.scanCoinCount }}</span>
            <el-icon
              size="16"
              class="edit-icon"
              @click="handleScanCoin(scope.row)"
              ><EditPen
            /></el-icon>
          </template>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="上市日期"
        align="center"
        prop="launchDate"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.launchDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column
        label="审核意见"
        align="center"
        prop="approvalReason"
      ></el-table-column> -->
      <el-table-column
        label="写酒评送啤酒币数量"
        align="center"
        prop="firstReviewCoin"
        min-width="120"
      >
        <template #default="scope">
          <template v-if="reviewCoinId === scope.row.id">
            <el-input
              v-model="reviewCoinCount"
              type="number"
              placeholder="请输入数量"
              style="width: 80px"
            />
            <el-button link type="primary" @click="saveReviewCoinCount"
              >保存</el-button
            >
            <el-button link @click="cancelReviewCoin">取消</el-button>
          </template>
          <template v-else>
            <span>{{ scope.row.firstReviewCoin }}</span>
            <el-icon
              size="16"
              class="edit-icon"
              @click="handleReviewCoin(scope.row)"
              ><EditPen
            /></el-icon>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        label="酒评分数"
        align="center"
        prop="beerOverallRating"
      ></el-table-column>

      <el-table-column
        label="操作"
        align="center"
        width="300"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['brewery:beer:edit']"
            >查看详情</el-button
          >
          <!-- <el-button
            link
            type="primary"
            @click="handleSaleStatus(scope.row)"
            v-hasPermi="['brewery:beer:edit']"
            >{{ scope.row.onSale === 1 ? "下架" : "上架" }}</el-button
          > -->
          <el-button
            link
            type="primary"
            @click="handlePrint(scope.row)"
            v-hasPermi="['brewery:beer:edit']"
            >打印标签</el-button
          >
          <!-- <el-button
            link
            type="primary"
            @click="handleScanCoinCount(scope.row)"
            v-hasPermi="['brewery:beer:edit']"
            >啤酒币兑换数量</el-button
          > -->
          <!-- <el-button
            link
            type="danger"
            @click="handleDelete(scope.row)"
            v-hasPermi="['brewery:beer:remove']"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改啤酒对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="900px"
      append-to-body
      fullscreen
    >
      <el-form ref="beerRef" :model="form" :rules="rules" label-width="130px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="啤酒名称" prop="beerName">
              <el-input v-model="form.beerName" placeholder="请输入啤酒名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="啤酒编码" prop="beerSn">
              <el-input v-model="form.beerSn" placeholder="请输入啤酒编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="啤酒风格" prop="beerStyles">
              <el-select v-model="form.beerStyles" placeholder="请选择啤酒风格">
                <el-option
                  v-for="style in beerStyles"
                  :key="style.value"
                  :label="style.name"
                  :value="style.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="条码" prop="barcode">
              <el-input v-model="form.barcode" placeholder="请输入条码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="酒精度" prop="beerAbv">
              <el-input v-model="form.beerAbv" placeholder="请输入酒精度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="苦度值" prop="beerIbus">
              <el-input v-model="form.beerIbus" placeholder="请输入苦度值" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="原麦汁浓度" prop="beerOg">
              <el-input v-model="form.beerOg" placeholder="请输入原麦汁浓度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格" prop="specs">
              <el-input v-model="form.specs" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上架状态" prop="onSale">
              <el-radio-group v-model="form.onSale">
                <el-radio :label="1">上架</el-radio>
                <el-radio :label="0">下架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="市场价" prop="marketPrice">
              <el-input v-model="form.marketPrice" placeholder="请输入市场价" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上市日期" prop="launchDate">
              <el-date-picker
                clearable
                v-model="form.launchDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择上市日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="扫码获得啤酒币数" prop="scanCoinCount">
              <el-input
                v-model="form.scanCoinCount"
                type="number"
                min="1"
                max="9999"
                placeholder="请输入扫码获得啤酒币数（范围：1～9999）"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="封面图" prop="cover">
              <ImageUpload v-model="form.cover" :fileSize="5" :limit="1" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="品牌logo" prop="brandLogo">
              <ImageUpload v-model="form.brandLogo" :fileSize="5" :limit="1" />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="描述" prop="desc">
              <editor v-model="form.desc" :min-height="250" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 标签打印对话框 -->
    <el-dialog
      title="标签打印"
      v-model="openPrint"
      width="500px"
      append-to-body
      align-center
    >
      <el-form
        ref="tempRef"
        :model="formPrint"
        :rules="printRules"
        label-width="130px"
      >
        <el-form-item label="标签模板" prop="templateId">
          <el-select
            v-model="formPrint.templateId"
            placeholder="请选择标签模板"
            style="width: 280px"
          >
            <el-option
              v-for="template in templateList"
              :key="template.id"
              :label="template.templateName"
              :value="template.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生产日期" prop="productionDate">
          <el-date-picker
            clearable
            v-model="formPrint.productionDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择生产日期"
            style="width: 280px"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="打印数量" prop="printCount">
          <el-input
            v-model="formPrint.printCount"
            type="number"
            :min="1"
            :max="10"
            placeholder="请输入打印数量（范围：1～10）"
            style="width: 280px"
          />
        </el-form-item>
        <!-- <el-form-item label="批次号" prop="batchNo">
          <el-input
            v-model="formPrint.batchNo"
            placeholder="请输入批次号"
            style="width: 280px"
          />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer" style="text-align: center">
          <el-button type="primary" @click="startPrint">开始打印</el-button>
          <el-button @click="cancelPrint">取消打印</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      title="标签打印"
      v-model="showPrintDialog"
      width="320px"
      :append-to-body="false"
      align-center
    >
      <div
        id="hiprint-printTemplate"
        style="
          position: relative;
          overflow-y: auto;
          width: 300px;
          height: 800px;
        "
      ></div>

      <template #footer>
        <div class="dialog-footer" style="text-align: center">
          <el-button type="primary" @click="myprint2">开始打印</el-button>
          <el-button @click="cancelPrint2">取消打印</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Beer">
import {
  listBeer,
  getBeer,
  delBeer,
  addBeer,
  updateBeer,
  updateBeerIcons,
  updateBeerSaleStatus,
  updateReviewIcons, // 首评赠送啤酒币
} from "@/api/brewery/beer";
import { addBatch, getBatch } from "@/api/brewery/batch";
import { generateQrcodeByBatch } from "@/api/brewery/qrcode";
import {
  allTemplate,
  getBreweryTagPrintTemplate,
} from "@/api/brewery/printTemplate";
import {
  hiprint,
  defaultElementTypeProvider,
  disAutoConnect,
} from "vue-plugin-hiprint";
import { ElMessageBox } from "element-plus";
const { proxy } = getCurrentInstance();
hiprint.init();
disAutoConnect();
const router = useRouter();
const beerStyles = [
  { name: "皮尔森（Pristner）", value: "皮尔森（Pristner" },
  {
    name: "美式淡拉格（American Light Lager）",
    value: "美式淡拉格（American Light Lager）",
  },
  { name: "烟熏啤酒（Rauchbier）", value: "烟熏啤酒（Rauchbier）" },
  { name: "德式黑啤（Schwarzbier）", value: "德式黑啤（Schwarzbier）" },
  { name: "博克（Bock）", value: "博克（Bock）" },
  { name: "淡色艾尔（Pale Ale）", value: "淡色艾尔（Pale Ale）" },
  { name: "印度淡色艾尔（IPA）", value: "印度淡色艾尔（IPA）" },
  { name: "小麦啤酒（Wheat beer）", value: "小麦啤酒（Wheat beer）" },
  { name: "棕色艾尔（Brown Ale）", value: "棕色艾尔（Brown Ale）" },
  { name: "波特（Porter）", value: "波特（Porter）" },
  { name: "司陶特（Stout）", value: "司陶特（Stout）" },
  { name: "酸啤酒（Sour beer）", value: "酸啤酒（Sour beer）" },
  { name: "修道院啤酒（Trappist Ale）", value: "修道院啤酒（Trappist Ale）" },
  { name: "西打酒（Cider）", value: "西打酒（Cider）" },
  { name: "兰比克（Lambic）", value: "兰比克（Lambic）" },
];
const beerList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    breweryId: null,
    beerName: null,
    cover: null,
    brandLogo: null,
    beerSn: null,
    beerStyles: null,
    beerAbv: null,
    beerIbus: null,
    barcode: null,
    onSale: null,
    beerOg: null,
    marketPrice: null,
    specs: null,
    desc: null,
    scanCoinCount: null,
    launchDate: null,
  },
  rules: {
    beerName: [{ required: true, message: "请输入啤酒名称", trigger: "blur" }],
    launchDate: [
      { required: true, message: "请选择上市日期", trigger: "change" },
    ],
    scanCoinCount: [
      { required: true, message: "请输入扫码获得啤酒币数", trigger: "blur" },
    ],
    cover: [{ required: true, message: "请上传封面图", trigger: "change" }],
    // brandLogo: [
    //   { required: true, message: "请上传品牌logo", trigger: "change" },
    // ],

    beerStyles: [
      { required: true, message: "请选择啤酒风格", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询啤酒列表 */
function getList() {
  loading.value = true;
  listBeer(queryParams.value).then((response) => {
    beerList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    breweryId: null,
    beerName: null,
    cover: null,
    // brandLogo: null,
    beerSn: null,
    beerStyles: null,
    beerAbv: null,
    beerIbus: null,
    barcode: null,
    onSale: null,
    beerOg: null,
    marketPrice: null,
    specs: null,
    desc: null,
    scanCoinCount: null,
    launchDate: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
  };
  proxy.resetForm("beerRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  // reset();
  // open.value = true;
  // title.value = "添加啤酒";
  router.push("/product/addBeer");
}

/** 修改按钮操作 */
function handleUpdate(row) {
  // reset();
  // const _id = row.id || ids.value;
  // getBeer(_id).then((response) => {
  //   form.value = response.data;
  //   open.value = true;
  //   title.value = "修改啤酒";
  // });
  router.push("/product/beerInfo?id=" + row.id);
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["beerRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateBeer(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBeer(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除啤酒编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delBeer(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "brewery/beer/export",
    {
      ...queryParams.value,
    },
    `beer_${new Date().getTime()}.xlsx`
  );
}
// 设置兑换啤酒数
function handleScanCoinCount(row) {
  ElMessageBox.prompt("扫码兑换啤酒币个数（范围：1～9999）", "设置", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /^[1-9][0-9]{0,3}$/,
    inputErrorMessage: "请输入有效的数字（范围：1～9999）",
  })
    .then(({ value }) => {
      updateBeerIcons({ beerId: row.id, icons: value }).then((response) => {
        proxy.$modal.msgSuccess("设置成功");
        getList();
      });
    })
    .catch(() => {
      console.log("取消");
    });
}
/** 啤酒上架按钮操作 */
function handleSaleStatus(row) {
  let str = "";
  if (row.onSale == 1) {
    str = "下架";
  } else {
    str = "上架";
  }

  proxy.$modal
    .confirm("是否确认" + str + '编号为"' + row.id + '"的数据项？')
    .then(() => {
      updateBeerSaleStatus({
        beerId: row.id,
        state: row.onSale == 1 ? 0 : 1,
      }).then(() => {
        getList();
        proxy.$modal.msgSuccess(`${str}成功`);
      });
    })
    .catch(() => {});
}
//========== 扫码送啤酒币 ==========
const currentScanCoinId = ref(null);
const scanCoinCount = ref(0);
function handleScanCoin(row) {
  currentScanCoinId.value = row.id;
  scanCoinCount.value = row.scanCoinCount;
}
function saveScanCoinCount() {
  updateBeerIcons({
    beerId: currentScanCoinId.value,
    icons: scanCoinCount.value,
  }).then((response) => {
    proxy.$modal.msgSuccess("修改成功");
    scanCoinCount.value = 0;
    currentScanCoinId.value = null;
    getList();
  });
}
function cancelScanCoin() {
  currentScanCoinId.value = null;
  scanCoinCount.value = 0;
}

//==========

//========= 首评赠送啤酒币
const reviewCoinId = ref(null);
const reviewCoinCount = ref(0);
function handleReviewCoin(row) {
  reviewCoinId.value = row.id;
  reviewCoinCount.value = row.firstReviewCoin;
}
function saveReviewCoinCount() {
  updateReviewIcons({
    beerId: reviewCoinId.value,
    icons: reviewCoinCount.value,
  }).then((response) => {
    proxy.$modal.msgSuccess("修改成功");
    reviewCoinCount.value = 0;
    reviewCoinId.value = null;
    getList();
  });
}
function cancelReviewCoin() {
  reviewCoinId.value = null;
  reviewCoinCount.value = 0;
}
//=========
// 获取所有标签模板
function getAllTemplate() {
  allTemplate().then((res) => {
    templateList.value = res.data;
  });
}
// 标签打印
const templateList = ref([]); // 标签模板列表
const printRules = {
  productionDate: [
    { required: true, message: "请选择生产日期", trigger: "change" },
  ],
  printCount: [{ required: true, message: "请输入打印数量", trigger: "blur" }],
  batchNo: [{ required: false, message: "请输入批次号", trigger: "blur" }],
  templateId: [
    { required: true, message: "请选择标签模板", trigger: "change" },
  ],
};
let hiprintTemplate;
const currentBeer = ref({});
const openPrint = ref(false);
const formPrint = ref({});
const showPrintDialog = ref(false);
function handlePrint(row) {
  openPrint.value = true;
  currentBeer.value = row;
}
// 开始打印
function startPrint() {
  proxy.$refs["tempRef"].validate((valid) => {
    if (valid) {
      showPrintDialog.value = true;
      // setTimeout(() => {
      //   buildDesigner();
      // }, 500);
      formPrint.value.beerId = currentBeer.value.id;
      addBatch(formPrint.value).then((response) => {
        const batchNo = response.data;
        generateQrcodeByBatch(batchNo).then((response) => {
          // proxy.$modal.msgSuccess("生成成功");
          getBatch(batchNo).then((resBatch) => {
            let batchInfo = resBatch.data;

            getBreweryTagPrintTemplate(formPrint.value.templateId || 3).then(
              (res) => {
                const template = JSON.parse(res.data.elements);
                console.log(template, template.panels[0].printElements);
                // printData.value = template.panels[0].printElements;
                // setTimeout(() => {
                //   hiprintTemplate.update(template);
                // }, 500);
                // hiprint.print({ templates: [template.panels[0].printElements] }, {}, {});
                // printDataFun(
                //   template.panels[0].printElements,
                //   batchInfo,
                //   res.data.pageWidth,
                //   res.data.pageHeight
                // );
                myPrint(template.panels[0].printElements, batchInfo);
              }
            );
          });
        });
      });
    }
  });
}
function myPrint(dataList, batchInfo) {
  const printTemplate = document.getElementById("hiprint-printTemplate");
  // console.log(batchInfo);
  batchInfo.wyBeerQrcodeList.forEach((it, index) => {
    let box = document.createElement("div");
    box.style.position = "relative";
    box.style.left = 0;

    // 不重叠，得加上高度
    // 获取box元素的实际高度
    // 130mm 转换成px
    let realHeight = (130 * 96) / 25.4;
    let realWidth = (76 * 96) / 25.4;
    box.style.top = index * realHeight + "px";
    box.style.width = realWidth + "px";

    // box.style.top = index * 800 + "px";
    // box.style.width = "100%";
    dataList.forEach((item) => {
      let options = item.options;
      let value = currentBeer.value[options.field];

      if (options.field == "batchSn") {
        value = batchInfo.batchSn;
      } else if (options.field == "productionDate") {
        value = batchInfo.productionDate;
      }
      if (item.printElementType.type == "text") {
        let el = document.createElement("div");
        el.innerHTML = options.title + ":" + (value || "");

        el.style.position = "absolute";
        el.style.left = options.left + "px";
        el.style.top = options.top + "px";
        el.style.width = options.width + "px";
        el.style.height = options.height + "px";

        box.append(el);

        //文本
      } else if (item.printElementType.type == "barcode") {
      } else if (item.printElementType.type == "qrcode") {
        let el = document.createElement("img");
        el.style.position = "absolute";

        el.src = it.qrcodeUrl;
        el.style.left = options.left + "px";
        el.style.top = options.top + "px";
        el.style.width = options.width + "px";
        el.style.height = options.height + "px";

        box.append(el);
      }
      let userBox = document.createElement("div");
      userBox.style.position = "absolute";
      // userBox.style.bottom = 40 + "px";
      userBox.style.top = 360 + "px";
      userBox.style.left = 16 + "px";
      userBox.style.width = "100%";
      let coustom = document.createElement("div");
      coustom.innerHTML = `<div style="font-size: 12px;font-weight: bold;margin-bottom: 0px;">枝点酒掌柜</div>
        <div style="font-size: 10px;margin-bottom: 10px;">BrewPivot</div>
        <div style="font-size: 10px;margin-bottom: 0px;">手机扫码解锁专属活动！</div>
        <div style="font-size: 10px;margin-bottom: 0px;">更新酒单、领取啤酒币、享受返利、一扫搞定！</div>
        <img src="https://ma.zdtap.com/profile/upload/2025/03/12/gh_e063633f8600_258_20250312115041A005.jpg" style="width: 50px;height: 50px;position: absolute;bottom: 0px;right: 20px;">`;
      userBox.append(coustom);
      box.append(userBox);
      printTemplate.append(box);
    });
  });
}
function myprint2() {
  const printTemplate = document.getElementById("hiprint-printTemplate");
  // printTemplate.style.width = '76mm'
  let newstr = document.getElementById("hiprint-printTemplate").innerHTML;
  let oldWidth = printTemplate.style.width;
  let oldstr = document.body.innerHTML;
  document.body.innerHTML = newstr;
  // document.style.width = "76mm";
  window.print();
  document.body.innerHTML = oldstr;
  // ocument.body.style.width = oldWidth;
  // window.print();
}
function printDataFun(dataList, batchInfo, pageWidth, pageHeight) {
  let hiprintTemplate = new hiprint.PrintTemplate();
  let panel = hiprintTemplate.addPrintPanel({
    width: pageWidth,
    height: pageHeight,
    // width: 76,
    // height: 130,
    paperFooter: 10,
    paperHeader: 10,
  });

  batchInfo.wyBeerQrcodeList.forEach((it) => {
    dataList.forEach((item) => {
      let options = item.options;
      let value = currentBeer.value[options.field];
      console.log(value);
      if (options.field == "batchNo") {
        value = batchInfo.batchNo;
      } else if (options.field == "qrcode") {
        value = it.qrcodeUrl;
      } else if (options.field == "productionDate") {
        value = batchInfo.productionDate;
      }
      if (item.printElementType.type == "text") {
        // bottom: 47.2500057220459;
        // field: "beerName";
        // hCenter: 42.3750057220459;
        // height: 9.75;
        // left: 15;
        // qid: "beerName";
        // right: 135.75;
        // testData: "小麦啤酒";
        // title: "产品名称";
        // top: 37.5;
        // vCenter: 75.75;
        // width: 120;
        //文本
        panel.addPrintText({
          options: {
            width: options.width,
            height: options.height,
            top: options.top,
            left: options.left,
            title: options.title + ":" + (value || ""),
            // text: value,
            textAlign: "left",
          },
        });
      } else if (item.printElementType.type == "barcode") {
        //条形码
        panel.addPrintText({
          options: {
            width: options.width,
            height: options.height,
            top: options.top,
            left: options.left,
            title: options.title + ":" + (value || ""),
            textType: "barcode",
          },
        });
      } else if (item.printElementType.type == "qrrcode") {
        //条形码
        panel.addPrintText({
          options: {
            width: options.width,
            height: options.height,
            top: options.top,
            left: options.left,
            title: value || "",
            textType: "barcode",
          },
        });
      }
    });
  });

  hiprintTemplate.print({
    title: "标签打印",
    generateHTMLInterval: 30,
    printByFragments: true,
  });
}

const buildDesigner = (val) => {
  // eslint-disable-next-line no-undef
  $("#hiprint-printTemplate").empty(); // 先清空, 避免重复构建
  hiprintTemplate = new hiprint.PrintTemplate({
    settingContainer: "#PrintElementOptionSetting", // 元素参数容器
    fontList: [
      { title: "微软雅黑", value: "Microsoft YaHei" },
      { title: "黑体", value: "STHeitiSC-Light" },
      { title: "思源黑体", value: "SourceHanSansCN-Normal" },
      { title: "王羲之书法体", value: "王羲之书法体" },
      { title: "宋体", value: "SimSun" },
      { title: "华为楷体", value: "STKaiti" },
      { title: "cursive", value: "cursive" },
    ],
    onDataChanged: (type, json) => {
      // 模板发生改变回调
      console.log(type); // 新增、移动、删除、修改(参数调整)、大小、旋转
      console.log(json); // 返回 template
    },
  });
  // 构建 并填充到 容器中
  hiprintTemplate.design("#hiprint-printTemplate");
  hiprintTemplate.setPaper(300, 400);

  // hiprintTemplate.print()
};
// 取消打印
function cancelPrint() {
  openPrint.value = false;
  formPrint.value = {};
}
function cancelPrint2() {
  showPrintDialog.value = false;
}
getAllTemplate();
getList();
</script>
<style lang="scss" scoped>
.edit-icon {
  margin-left: 4px;
  vertical-align: middle;
  cursor: pointer;
}
</style>
