<!-- 商品列表 -->
<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]" id="search_div">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="商品名称" prop="productName">
              <el-input class="inputWidth" v-model="queryParams.productName" placeholder="请输入商品名称" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="商品状态" prop="productShows">
              <el-select class="inputWidth" v-model="queryParams.status" placeholder="请选择商品状态" clearable>
                <el-option v-for="dict in sys_shelf_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </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-button type="primary" plain icon="Plus" @click="handleAdd"
                v-hasPermi="['manage:product:add']">新增</el-button>
              <!-- <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
                v-hasPermi="['manage:product:edit']">修改</el-button>
              <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                v-hasPermi="['manage:product:remove']">删除</el-button> -->
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-table v-loading="loading" border :height="autoTableHeight" :data="productList"
      @selection-change="handleSelectionChange">
      <el-table-column label="商品ID" align="center" prop="id" v-if="true" width="180px" />
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="商品类别" align="center" prop="categoryId">
        <template #default="scope">
          <span>{{ formatCategoryName(scope.row.categoryId)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品图片" align="center" prop="productImageUrl" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.productImageUrl" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="商品说明" align="center" prop="productShows" />
      <el-table-column label="排序" align="center" prop="sortNum" />
      <el-table-column label="商品状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_shelf_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="vendorId">
        <template #default="scope">
          <!-- <span>{{ formatVendorName(scope.row.vendorId) }}</span> -->
          <span>{{ scope.row.vendorName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作者" align="center" prop="updateByName" />
      <el-table-column label="操作时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <!-- <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span> -->
          <span>{{ scope.row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="handleStatus(scope.row,'1')" v-hasPermi="['manage:product:edit']"
            v-if="scope.row.status==0">上架</el-button>
          <el-button link type="primary" @click="handleStatus(scope.row,'0')" v-hasPermi="['manage:product:edit']"
            v-if="scope.row.status==1">下架</el-button>
          <el-tooltip content="修改" placement="top" v-if="scope.row.status==0">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['manage:product:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top" v-if="scope.row.status==0">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['manage:product:remove']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" id="table_page" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    <!-- 添加或修改商品信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="productFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="商品类别" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择商品类别" clearable>
                <el-option v-for="dict in productCategoryList" :key="dict.id" :label="dict.category" :value="dict.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sortNum">
              <el-input-number v-model="form.sortNum" :min="1" :max="10000" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="供应商" prop="vendorId">
          <el-select v-model="form.vendorId" placeholder="请选择供应商" clearable>
            <el-option v-for="item in listVendorList" :key="item.id" :label="item.vendorName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片" prop="productImage">
          <image-upload v-model="form.productImage" />
        </el-form-item>
        <el-form-item label="商品说明" prop="productShows">
          <el-input v-model="form.productShows" type="textarea" :rows="5" placeholder="请输入商品说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Product" lang="ts">
import { listProductCategory } from '@/api/manage/productCategory';
import { listVendor } from '@/api/manage/vendor';

import { listProduct, getProduct, delProduct, addProduct, updateProduct } from '@/api/manage/product';
import { ProductVO, ProductQuery, ProductForm } from '@/api/manage/product/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const autoTableHeight = ref(750);
const productList = ref<ProductVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const { sys_shelf_status } = toRefs<any>(
  proxy?.useDict('sys_shelf_status')
);
const queryFormRef = ref<ElFormInstance>();
const productFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
  type: ''
});

const initFormData: ProductForm = {
  id: undefined,
  categoryId: undefined,
  productName: undefined,
  productImage: undefined,
  productShows: undefined,
  vendorId: undefined,
  sortNum: 0,
  productStatus: undefined,
  remark: undefined,
  status: undefined
}
const data = reactive<PageData<ProductForm, ProductQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryId: undefined,
    productName: undefined,
    productImage: undefined,
    productShows: undefined,
    vendorId: undefined,
    sortNum: undefined,
    productStatus: undefined,
    params: {
    }
  },
  rules: {
    categoryId: [
      { required: true, message: "商品类别不能为空", trigger: "blur" }
    ],
    productName: [
      { required: true, message: "商品名称不能为空", trigger: "blur" }
    ],
    productImage: [
      { required: false, message: "商品图片不能为空", trigger: "blur" }
    ],
    productShows: [
      { required: true, message: "商品说明不能为空", trigger: "blur" }
    ],
    vendorId: [
      { required: true, message: "供应商不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ]
  }
});

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

/** 查询商品信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listProduct(queryParams.value);
  productList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  productFormRef.value?.resetFields();
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProductVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加商品信息";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ProductVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getProduct(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改商品信息";
}
/**
 * 上架 下架 商品
 * @param row 
 */
const handleStatus = async (row: ProductVO,type: string) => {
   await proxy?.$modal.confirm('是否确认' + (type == '0' ? '下架' : '上架') + '名称为"' + row.productName + '"的数据项？');
  row.status = type;
  buttonLoading.value = true;
          await updateProduct(row).finally(() =>  buttonLoading.value = false);
  proxy?.$modal.msgSuccess('操作成功');
  getList();
}
/** 提交按钮 */
const submitForm = () => {
  productFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateProduct(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        form.value.status = 0;
        await addProduct(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ProductVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除商品名称为"' + row.productName + '"的数据项？').finally(() => loading.value = false);
  await delProduct(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('manage/product/export', {
    ...queryParams.value
  }, `product_${new Date().getTime()}.xlsx`)
}
/**
 * 商品类别列表 
 */
const productCategoryList = ref([]);
const getProductCategoryList = async () => {
  let res = await listProductCategory({ pageNum: 1, pageSize: 9999 });
  productCategoryList.value = res.rows;
}
/**
 * 供应商列表
 */
const listVendorList = ref([]);
const getlistVendor = async () => {
  let res = await listVendor({ pageNum: 1, pageSize: 9999 });
  listVendorList.value = res.rows;
}
/**
 * 格式化商品类别名称
 * @param row 
 */
const formatCategoryName = (id:any) => {
  for (let i = 0; i < productCategoryList.value.length; i++) {
    const element = productCategoryList.value[i];
    if (element.id == id) {
      return element.category;
    }
  }
}
/**
 * 格式化 供应商名称
 * @param id 
 */
const formatVendorName = (id:any) => {
  for (let i = 0; i < listVendorList.value.length; i++) {
    const element = listVendorList.value[i];
    if (element.id == id) {
      return element.vendorName;
    }
  }
}
onMounted(() => {
  getList();
  getlistVendor(); //供应商列表
  getProductCategoryList(); //商品类别列表
  nextTick(() => {
    autoTableHeight.value = proxy?.autoTableHeight();
  });
  window.onresize = () => {
    autoTableHeight.value = proxy?.autoTableHeight();
  };
});
</script>
<style lang="scss" scoped>
.el-card :deep(.el-card__body) {
  padding-bottom: 0px !important;
}

#table_page {
  height: 50px !important;
  margin-top: 10px !important;
  padding-bottom: 10px !important;
}
</style>
