<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="批次编号" prop="batchSn">
        <el-input
          v-model="queryParams.batchSn"
          placeholder="请输入批次编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="酒款" prop="beerId">
        <el-select
          v-model="queryParams.beerId"
          placeholder="请选择酒款"
          style="width: 200px"
        >
          <el-option
            v-for="item in allBeersList"
            :key="item.id"
            :label="item.beerName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="生成日期" prop="">
        <el-input
          v-model="queryParams.generateNum"
          placeholder="请输入生成数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="打印日期" prop="generateState"> </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:batch:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['brewery:batch:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['brewery:batch:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['brewery:batch:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="batchList"
      class="zd-table"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" width="80" />
      <el-table-column
        label="批次编号"
        align="center"
        prop="batchSn"
        show-overflow-tooltip
      />
      <el-table-column label="酒款名称" align="center" prop="beerName" />
      <el-table-column label="生成数量" align="center" prop="generateNum" />
      <el-table-column label="生成状态" align="center" prop="generateState">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.generateState === 1"
            >已生成</el-tag
          >
          <el-tag type="warning" v-else-if="scope.row.generateState == 0"
            >未生成</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            v-if="scope.row.generateState === 0"
            link
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['brewery:batch:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            @click="handleInfo(scope.row)"
            v-hasPermi="['brewery:batch:edit']"
            >详情</el-button
          >
          <el-button
            v-if="scope.row.generateState === 0"
            link
            type="primary"
            @click="handleQrcode(scope.row)"
            v-hasPermi="['brewery:batch:edit']"
            >生成二维码</el-button
          >
          <el-button
            v-if="scope.row.generateState === 0"
            link
            type="danger"
            @click="handleDelete(scope.row)"
            v-hasPermi="['brewery:batch: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="500px" append-to-body>
      <el-form ref="batchRef" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="酒款" prop="beerId">
          <el-select v-model="form.beerId" placeholder="请选择酒款">
            <el-option
              v-for="item in allBeersList"
              :key="item.id"
              :label="item.beerName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生产日期" prop="productionDate">
          <el-date-picker
            v-model="form.productionDate"
            type="date"
            placeholder="请选择生产日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="可生成二维码数量" prop="printCount">
          <el-input v-model="form.printCount" placeholder="请输入生成数量" />
        </el-form-item>
      </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-drawer v-model="showDrawer" title="批次详情" size="600">
      <el-descriptions border :column="1" style="margin-bottom: 20px">
        <el-descriptions-item label="批次编号">{{
          batchInfo.batchSn
        }}</el-descriptions-item>
        <el-descriptions-item label="酒款名称">{{
          batchInfo.beerName
        }}</el-descriptions-item>
        <el-descriptions-item label="生成数量">{{
          batchInfo.generateNum
        }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          batchInfo.createTime
        }}</el-descriptions-item>
      </el-descriptions>
      <el-table
        v-if="
          batchInfo.wyBeerQrcodeList && batchInfo.wyBeerQrcodeList.length > 0
        "
        :data="batchInfo.wyBeerQrcodeList"
        border
        style="width: 100%"
      >
        <el-table-column label="skuSn" prop="skuSn" />
        <el-table-column label="二维码图片" prop="qrcodeUrl" width="150px">
          <template #default="scope">
            <el-image
              style="width: 60px; height: 60px"
              :src="scope.row.qrcodeUrl"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="[scope.row.qrcodeUrl]"
              :initial-index="4"
              fit="cover"
              title="点击查看大图"
              preview-teleported
            />
          </template>
        </el-table-column>
        <el-table-column label="核销状态" prop="qrcodeStatus" width="100px">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.qrcodeStatus === 1"
              >已核销</el-tag
            >
            <el-tag type="warning" v-else-if="scope.row.qrcodeStatus === 0"
              >未核销</el-tag
            >
            <el-tag type="info" v-else-if="scope.row.qrcodeStatus === 2"
              >已失效</el-tag
            >
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
  </div>
</template>

<script setup name="Batch">
import {
  listBatch,
  getBatch,
  delBatch,
  addBatch,
  updateBatch,
} from "@/api/brewery/batch";
import { allBeers } from "@/api/brewery/beer";
import { generateQrcodeByBatch } from "@/api/brewery/qrcode";

const { proxy } = getCurrentInstance();

const batchList = 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 allBeersList = ref([]); // 所有啤酒列表
const batchInfo = ref({}); // 批次详情
const showDrawer = ref(false); // 批次详情抽屉框
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    breweryId: null,
    batchSn: null,
    beerId: null,
    generateNum: null,
  },
  rules: {
    breweryId: [{ required: true, message: "品牌方不能为空", trigger: "blur" }],
  },
});

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

/** 查询批次列表 */
function getList() {
  loading.value = true;
  listBatch(queryParams.value).then((response) => {
    batchList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    breweryId: null,
    batchSn: null,
    beerId: null,
    generateNum: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
  };
  proxy.resetForm("batchRef");
}

/** 搜索按钮操作 */
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 = "添加批次";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getBatch(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改批次";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["batchRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateBatch(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBatch(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 delBatch(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "brewery/batch/export",
    {
      ...queryParams.value,
    },
    `batch_${new Date().getTime()}.xlsx`
  );
}
// 获取所有啤酒列表
function getAllBeersFun() {
  allBeers().then((response) => {
    allBeersList.value = response.data;
  });
}
// 查看详情
function handleInfo(row) {
  const _id = row.id || ids.value;
  getBatch(_id).then((response) => {
    batchInfo.value = response.data;
    showDrawer.value = true;
  });
}

// 生成二维码
function handleQrcode(row) {
  generateQrcodeByBatch(row.id).then((response) => {
    proxy.$modal.msgSuccess("生成成功");
    getList();
  });
}

getAllBeersFun();
getList();
</script>
