<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]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="产品编号" prop="productNo">
              <el-input v-model="queryParams.productNo" placeholder="请输入产品编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供应商名称" prop="enterpriseName">
              <el-input v-model="queryParams.enterpriseName" placeholder="请输入供应商名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供应区域" prop="provinceName">
              <el-input v-model="queryParams.provinceName" placeholder="请输入供应区域（省）" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供应区域" prop="cityName">
              <el-input v-model="queryParams.cityName" placeholder="请输入供应区域（市）" clearable @keyup.enter="handleQuery" />
            </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-card>
      </div>
    </transition>

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

      <el-table v-loading="loading" border :data="contracproductList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商品编号" align="center" prop="productNo" width="140" />
        <el-table-column label="商品信息" align="left" min-width="240">
          <template #default="scope">
            <div style="display: flex; gap: 10px; align-items: center;">
              <el-image
                :src="(scope.row.productImage || '').split(',').filter(Boolean)[0]"
                :preview-src-list="(scope.row.productImage || '').split(',').filter(Boolean)"
                preview-teleported
                style="width: 48px; height: 48px; flex: 0 0 auto;"
                fit="cover"
              />
              <div style="min-width: 0;">
                <div style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{{ scope.row.productName || '-' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品分类" align="center" prop="bottomCategoryName" min-width="160" />
        <el-table-column label="单位" align="left" width="120">
          <template #default="scope">
            <div>
              <div>单位：{{ scope.row.unitName || '-' }}</div>
              <div>起订量：{{ scope.row.minOrderQuantity ?? '-' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="SKU价格" align="left" width="140">
          <template #default="scope">
            <div>
              <div>市场价：¥{{ scope.row.marketPrice ?? '-' }}</div>
              <div style="color: #f56c6c;">会员价：¥{{ scope.row.memberPrice ?? '-' }}</div>
              <div>最低价：¥{{ scope.row.minSellingPrice ?? '-' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="库存情况" align="left" min-width="180">
          <template #default="scope">
            <div>
              <div>总库存数：{{ scope.row.totalInventory ?? '-' }}</div>
              <div>当前库存：{{ scope.row.nowInventory ?? '-' }}</div>
              <div>虚拟库存：{{ scope.row.virtualInventory ?? '-' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="供应商名称" align="center" prop="enterpriseName" min-width="180" />
        <el-table-column label="供应价" align="center" prop="offerPrice" width="120" />
        <el-table-column label="供货时效" align="center" prop="supplyCycle" width="120" />
        <el-table-column label="供应区域（省）" align="center" prop="provinceName" min-width="160" />
        <el-table-column label="供应区域（市）" align="center" prop="cityName" min-width="200" />
        <el-table-column label="报价截止日期" align="center" width="160">
          <template #default="scope">
            <span>{{ scope.row.endTime || scope.row.offerEndTime || '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="毛利率" align="center" width="120">
          <template #default="scope">
            <span v-if="(scope.row.grossProfitRate ?? scope.row.grossMarginRate) === null || (scope.row.grossProfitRate ?? scope.row.grossMarginRate) === undefined"></span>
            <span v-else>{{ scope.row.grossProfitRate ?? scope.row.grossMarginRate }}%</span>
          </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-card>
    <!-- 添加或修改供应链查询对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="contracproductFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="合同供货编号" prop="contractSupplyNo">
          <el-input v-model="form.contractSupplyNo" placeholder="请输入合同供货编号" />
        </el-form-item>
        <el-form-item label="产品编号" prop="productNo">
          <el-input v-model="form.productNo" placeholder="请输入产品编号" />
        </el-form-item>
        <el-form-item label="产品id" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入产品id" />
        </el-form-item>
        <el-form-item label="供货周期" prop="supplyCycle">
          <el-input v-model="form.supplyCycle" placeholder="请输入供货周期" />
        </el-form-item>
        <el-form-item label="库存属性" prop="inventoryProperties">
          <el-input v-model="form.inventoryProperties" placeholder="请输入库存属性" />
        </el-form-item>
        <el-form-item label="最小供货量" prop="minSupply">
          <el-input v-model="form.minSupply" placeholder="请输入最小供货量" />
        </el-form-item>
        <el-form-item label="报价" prop="offerPrice">
            <el-input v-model="form.offerPrice" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" 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="Contracproduct" lang="ts">
import { scmListContracproduct, getContracproduct, delContracproduct, addContracproduct, updateContracproduct } from '@/api/product/contracproduct';
import { ContracproductVO, ContracproductQuery, ContracproductForm } from '@/api/product/contracproduct/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const contracproductList = ref<ContracproductVO[]>([]);
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 queryFormRef = ref<ElFormInstance>();
const contracproductFormRef = ref<ElFormInstance>();

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

const initFormData: ContracproductForm = {
  id: undefined,
  contractSupplyNo: undefined,
  contractSupplyId: undefined,
  productNo: undefined,
  productName: undefined,
  enterpriseName: undefined,
  provinceName: undefined,
  cityName: undefined,
  province: undefined,
  city: undefined,
  productId: undefined,
  supplyCycle: undefined,
  inventoryProperties: undefined,
  minSupply: undefined,
  offerPrice: undefined,
  status: undefined,
  remark: undefined,
}
const data = reactive<PageData<ContracproductForm, ContracproductQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractSupplyNo: undefined,
    contractSupplyId: undefined,
    productNo: undefined,
    productName: undefined,
    enterpriseName: undefined,
    provinceName: undefined,
    cityName: undefined,
    province: undefined,
    city: undefined,
    productId: undefined,
    supplyCycle: undefined,
    inventoryProperties: undefined,
    minSupply: undefined,
    offerPrice: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
  }
});

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

/** 查询供应链查询列表 */
const getList = async () => {
  loading.value = true;
  const res = await scmListContracproduct(queryParams.value);
  contracproductList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

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

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: ContracproductVO[]) => {
  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?: ContracproductVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getContracproduct(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改供应链查询";
}

/** 提交按钮 */
const submitForm = () => {
  contracproductFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateContracproduct(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addContracproduct(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ContracproductVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除供应链查询编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delContracproduct(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('product/contracproduct/export', {
    ...queryParams.value
  }, `contracproduct_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
