<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:goods:add']"
        >发布兑换商品</el-button
      >
    </div>
    <el-form
      v-if="false"
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="规格" prop="specs">
        <el-input
          v-model="queryParams.specs"
          placeholder="请输入规格"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="使用场景" prop="purchaseMethod">
        <el-select v-model="queryParams.purchaseMethod" style="width: 150px">
          <el-option label="啤酒币兑换" :value="1"></el-option>
          <el-option label="营销返利兑换" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否可兑换" prop="redeemed">
        <el-select v-model="queryParams.redeemed" style="width: 150px">
          <el-option label="不可以" :value="0"></el-option>
          <el-option label="可以" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="啤酒币兑换数" prop="redeemedNum">
        <el-input
          v-model="queryParams.redeemedNum"
          placeholder="请输入啤酒币兑换数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="编号" prop="goodsSn">
        <el-input
          v-model="queryParams.goodsSn"
          placeholder="请输入编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="本店售价" prop="goodsPrice">
        <el-input
          v-model="queryParams.goodsPrice"
          placeholder="请输入本店售价"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="市场售价" prop="marketPrice">
        <el-input
          v-model="queryParams.marketPrice"
          placeholder="请输入市场售价"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库存数量" prop="stockNum">
        <el-input
          v-model="queryParams.stockNum"
          placeholder="请输入库存数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="冻结数量" prop="frozenNum">
        <el-input
          v-model="queryParams.frozenNum"
          placeholder="请输入冻结数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="上架" prop="onSale">
        <el-select v-model="queryParams.onSale" style="width: 150px">
          <el-option label="下架" :value="0"></el-option>
          <el-option label="上架" :value="1"></el-option>
        </el-select>
      </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:goods:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['brewery:goods:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['brewery:goods:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['brewery:goods:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row> -->
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="全部商品" name="1"></el-tab-pane>
      <el-tab-pane label="已售罄" name="2"></el-tab-pane>
      <el-tab-pane label="通用兑换" name="3"></el-tab-pane>
      <el-tab-pane label="限累积返利" name="4"></el-tab-pane>
    </el-tabs>
    <el-table
      v-loading="loading"
      :data="goodsList"
      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="50" /> -->
      <!-- <el-table-column label="编号" align="center" prop="goodsSn" /> -->
      <el-table-column label="商品名称" align="left" prop="goodsName">
        <template #default="scope">
          <div style="display: flex; align-items: center; gap: 16px">
            <el-image
              style="width: 60px; height: 60px"
              :src="scope.row.goodsCover"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="[scope.row.goodsCover]"
              :initial-index="4"
              fit="cover"
              title="点击查看大图"
              preview-teleported
            />
            <div>
              <div>名称：{{ scope.row.goodsName }} {{ scope.row.specs }}</div>
              <div>编码：{{ scope.row.goodsSn }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品类型" align="center" prop="purchaseMethod">
        <template #default="scope">
          <span v-if="scope.row.purchaseMethod == 1">啤酒币兑换</span>
          <span v-if="scope.row.purchaseMethod == 2">营销返利兑换</span>
        </template>
      </el-table-column>

      <el-table-column label="库存" align="center" prop="stockNum" />
      <el-table-column label="啤酒币兑换数量" align="center" prop="redeemedNum">
        <template #default="scope">
          <template v-if="currentGoodsCoinId === scope.row.id">
            <el-input
              v-model="goodsCoinCount"
              type="number"
              placeholder="请输入数量"
              style="width: 80px"
            />
            <el-button link type="primary" @click="saveGoodsCoinCount"
              >保存</el-button
            >
            <el-button link @click="cancelGoodsCoin">取消</el-button>
          </template>
          <template v-else>
            <span>{{ scope.row.redeemedNum }}</span>
            <el-icon
              size="16"
              class="edit-icon"
              @click="handleGoodsIcons(scope.row)"
              ><EditPen
            /></el-icon>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        label="关联活动数量"
        align="center"
        prop="activityCount"
      />
      <el-table-column
        label="待兑付数量"
        align="center"
        prop="exchangeWaitingCount"
      />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <!-- <el-table-column label="库存数量" align="center" prop="stockNum" />
      <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"
        width="200"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <!-- <el-button
            link
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['brewery:goods:edit']"
            >修改</el-button
          > -->
          <el-button
            link
            type="primary"
            @click="handleSaleStatus(scope.row)"
            v-hasPermi="['brewery:goods:edit']"
            >{{ scope.row.onSale === 1 ? "下架" : "上架" }}</el-button
          >
          <el-button link type="primary" @click="handleHistory(scope.row)"
            >兑换历史</el-button
          >

          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row)"
            v-hasPermi="['brewery:goods: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="800px" append-to-body>
      <el-form ref="goodsRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否可兑换" prop="redeemed">
              <el-radio-group v-model="form.redeemed">
                <el-radio :label="0">不可以</el-radio>
                <el-radio :label="1">可以</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12"
            ><el-form-item label="编号" prop="goodsSn">
              <el-input
                v-model="form.goodsSn"
                placeholder="请输入编号"
              /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="上下架" prop="onSale">
              <el-radio-group v-model="form.onSale">
                <el-radio :label="0">下架</el-radio>
                <el-radio :label="1">上架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="12">
            <el-form-item label="本店售价" prop="goodsPrice">
              <el-input
                v-model="form.goodsPrice"
                placeholder="请输入本店售价"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12"
            ><el-form-item label="购买方式" prop="purchaseMethod">
              <el-radio-group v-model="form.purchaseMethod">
                <el-radio :label="1">啤酒币兑换</el-radio>
                <el-radio :label="2">营销返利兑换</el-radio>
              </el-radio-group>
            </el-form-item></el-col
          >
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="规格" prop="specs">
              <el-input v-model="form.specs" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="啤酒币兑换数" prop="redeemedNum">
              <el-input
                v-model="form.redeemedNum"
                placeholder="请输入啤酒币兑换数"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="库存数量" prop="stockNum">
              <el-input v-model="form.stockNum" placeholder="请输入库存数量" />
            </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="goodsCover">
              <ImageUpload v-model="form.goodsCover" :fileSize="5" :limit="1" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="冻结数量" prop="frozenNum">
              <el-input
                v-model="form.frozenNum"
                placeholder="请输入冻结数量"
              /> </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>
  </div>
</template>

<script setup name="Goods">
import {
  listGoods,
  getGoods,
  delGoods,
  addGoods,
  updateGoods,
  updateGoodsSaleStatus,
  updateGoodsStockNum,
  updateGoodsIcons,
} from "@/api/brewery/goods";
import { ElMessageBox } from "element-plus";
const { proxy } = getCurrentInstance();
const router = useRouter();
const goodsList = 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,
    goodsName: null,
    goodsCover: null,
    specs: null,
    purchaseMethod: null,
    redeemed: null,
    redeemedNum: null,
    goodsSn: null,
    goodsPrice: null,
    marketPrice: null,
    stockNum: null,
    frozenNum: null,
    onSale: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);
const activeName = ref("1");
/** 查询兑换商品列表 */
function getList() {
  loading.value = true;
  listGoods(queryParams.value).then((response) => {
    goodsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
function handleClick(tab, event) {
  console.log(tab, activeName.value);
  queryParams.value.pageNum = 1;
  if (activeName.value == 1) {
    delete queryParams.value.stockNum;
    delete queryParams.value.purchaseMethod;
  }
  if (activeName.value == 2) {
    queryParams.value.stockNum = 0;
    delete queryParams.value.purchaseMethod;
  }
  if (activeName.value == 3) {
    queryParams.value.purchaseMethod = 1;
    delete queryParams.value.stockNum;
  }
  if (activeName.value == 4) {
    queryParams.value.purchaseMethod = 2;
    delete queryParams.value.stockNum;
  }
  getList();
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    breweryId: null,
    goodsName: null,
    goodsCover: null,
    specs: null,
    purchaseMethod: null,
    redeemed: null,
    redeemedNum: null,
    goodsSn: null,
    goodsPrice: null,
    marketPrice: null,
    stockNum: null,
    frozenNum: null,
    onSale: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
  };
  proxy.resetForm("goodsRef");
}

/** 搜索按钮操作 */
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/commodity/add");
}

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

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

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "brewery/goods/export",
    {
      ...queryParams.value,
    },
    `goods_${new Date().getTime()}.xlsx`
  );
}
// 设置库存数量
function handleStockNum(row) {
  ElMessageBox.prompt("请输入库存数量（范围：1～999999）", "设置", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /^[1-9][0-9]{0,5}$/,
    inputErrorMessage: "请输入有效的数字（范围：1～999999）",
  })
    .then(({ value }) => {
      updateGoodsStockNum({
        goodsId: row.id,
        stock: value,
      }).then((response) => {
        proxy.$modal.msgSuccess("设置成功");
        getList();
      });
    })
    .catch(() => {
      console.log("取消");
    });
}
// 设置兑换啤酒数
function handleScanCoinCount(row) {
  ElMessageBox.prompt("兑换所需啤酒币个数（范围：1～9999）", "设置", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /^[1-9][0-9]{0,3}$/,
    inputErrorMessage: "请输入有效的数字（范围：1～9999）",
  })
    .then(({ value }) => {
      updateGoodsIcons({ goodsId: 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(() => {
      updateGoodsSaleStatus({
        goodsId: row.id,
        state: row.onSale == 1 ? 0 : 1,
      }).then(() => {
        getList();
        proxy.$modal.msgSuccess(`${str}成功`);
      });
    })
    .catch(() => {});
}

// 修改兑换啤酒数
const currentGoodsCoinId = ref(null);
const goodsCoinCount = ref(0);
function handleGoodsIcons(row) {
  currentGoodsCoinId.value = row.id;
  goodsCoinCount.value = row.redeemedNum;
}
function saveGoodsCoinCount() {
  updateGoodsIcons({
    goodsId: currentGoodsCoinId.value,
    icons: goodsCoinCount.value,
  }).then(() => {
    proxy.$modal.msgSuccess("修改成功");
    currentGoodsCoinId.value = null;
    goodsCoinCount.value = 0;
    getList();
  });
}
function cancelGoodsCoin() {
  currentGoodsCoinId.value = null;
  goodsCoinCount.value = 0;
}
//==========//==========

function handleHistory(row) {
  router.push("/product/commodity/history?goodsId=" + row.id);
}
getList();
</script>
<style lang="scss" scoped>
.edit-icon {
  margin-left: 4px;
  vertical-align: middle;
  cursor: pointer;
}
</style>
