<template>
  <div class="app-container">


    <!-- 商品报价信息 -->
    <el-card shadow="never" class="form-card">
      <div class="section-title">
        <el-button type="primary" @click="handleAddProduct">添加商品报价</el-button>
        <el-button type="success" icon="Upload" @click="handleImport">导入</el-button>
        <el-button icon="Download" @click="handleDownloadTemplate">下载模板</el-button>
      </div>

      <el-table :data="productList" border style="width: 100%; margin-top: 20px;">
        <el-table-column prop="productNo" label="产品编号" align="center" width="120" />
        <el-table-column label="产品图片" align="center" width="100">
          <template #default="scope">
            <el-image
              v-if="scope.row.productImage"
              :src="scope.row.productImage"
              style="width: 60px; height: 60px;"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column prop="itemName" label="产品名称" align="center" show-overflow-tooltip />
        <el-table-column label="产品分类" align="center" width="180" show-overflow-tooltip>
          <template #default="scope"> 
            <span>{{ scope.row.topCategoryName }}-{{ scope.row.mediumCategoryName }}-{{ scope.row.bottomCategoryName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="brandName" label="品牌" align="center" width="100" />
        <el-table-column prop="unitName" label="单位" align="center" width="80" />
        <el-table-column label="市场价" align="center" width="100">
          <template #default="scope">
            <span>¥{{ scope.row.marketPrice || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="官网价" align="center" width="100">
          <template #default="scope">
            <span>¥{{ scope.row.memberPrice || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="供应价(元)" align="center" width="120">
          <template #default="scope">
            <span>¥{{ scope.row.supplyPrice || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleDeleteProduct(scope.row, scope.$index)">删除</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="getProductData"
      />
    </el-card>

    <!-- 添加商品对话框 -->
    <Product
      v-model:visible="productDialog.visible"
      v-model:modelValue="productList"
    />

    <!-- 导入对话框 -->
    <el-dialog v-model="upload.open" title="合同产品导入" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :auto-upload="false"
        :http-request="customUpload"
        :on-change="handleFileChange"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="handleFileError"
        drag
      >
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <span>仅允许导入 xls、xlsx 格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="handleDownloadTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="upload.isUploading" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { getContractProductList, delContracproductBySupplier, importTemplate, importData } from '@/api/product/contracproduct';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { UploadFile, UploadInstance, UploadRequestOptions } from 'element-plus';
import Product from './components/Product.vue';
import { useUserStore } from '@/store/modules/user';

const { proxy } = getCurrentInstance() as any;
const router = useRouter();
const userStore = useUserStore();

const productList = ref<any[]>([]);
const total = ref(0);
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10
});

// 商品对话框相关
const productDialog = reactive({
  visible: false
});

// 导入相关
const uploadRef = ref<UploadInstance>();
const upload = reactive({
  open: false,
  isUploading: false
});

/** 返回上一页 */
const goBack = () => {
  router.back();
};

/** 获取商品列表 */
const getProductData = async () => {
  try {
    const res = await getContractProductList({
      supplierId: userStore.supplierId,
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize
    } as any);
    productList.value = res.rows || []
    total.value = (res as any).total || 0;
  } catch (e) {
    console.error('获取商品列表失败:', e);
    ElMessage.error('获取商品列表失败');
  }
};

/** 添加商品 */
const handleAddProduct = () => {
  productDialog.visible = true;
};

/** 删除商品 */
const handleDeleteProduct = async (row: any, index: number) => {
  console.log('handleDeleteProduct', row, index);
  try {
    await proxy?.$modal.confirm('是否确认删除该商品报价数据项？');
    await delContracproductBySupplier(row.id, userStore.supplierId as any);
    proxy?.$modal.msgSuccess('删除成功');
    await getProductData();
  } catch (e) {
    // 用户取消或请求失败时不提示
  }
};

/** 打开导入弹窗 */
const handleImport = () => {
  uploadRef.value?.clearFiles();
  upload.open = true;
};

/** 下载导入模板 */
const handleDownloadTemplate = async () => {
  try {
    const data: any = await importTemplate();
    const blob = new Blob([data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = `contracproduct_template_${new Date().getTime()}.xlsx`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(link.href);
  } catch (e) {
    console.error('下载模板失败:', e);
    ElMessage.error('下载模板失败');
  }
};

/** 文件选择变更 */
const handleFileChange = () => {
  // 占位：用于触发响应（element-plus 类型需要）
};

/** 自定义上传：直接调用后端 importData 接口 */
const customUpload = async (options: UploadRequestOptions) => {
  upload.isUploading = true;
  try {
    const res: any = await importData(options.file as File);
    options.onSuccess?.(res);
  } catch (err: any) {
    options.onError?.(err);
  }
};

/** 文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  const msg = response?.msg || '导入成功';
  ElMessageBox.alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + msg + '</div>',
    '导入结果',
    { dangerouslyUseHTMLString: true }
  );
  queryParams.pageNum = 1;
  getProductData();
};

/** 文件上传失败处理 */
const handleFileError = () => {
  upload.isUploading = false;
  ElMessage.error('导入失败');
};

/** 提交导入 */
const submitFileForm = () => {
  uploadRef.value?.submit();
};

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

<style scoped>
.app-container {
  background: #f0f2f5;
  min-height: 100vh;
  padding: 0;
}

.detail-header {
  background: #fff;
  padding: 16px 24px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #e8e8e8;
  margin-bottom: 16px;
}

.back-icon {
  font-size: 18px;
  cursor: pointer;
  margin-right: 12px;
  color: #666;
}

.back-icon:hover {
  color: #409eff;
}

.header-title {
  font-weight: 500;
  color: #333;
}

.form-card {
  margin: 16px;
  padding: 24px;
}

.section-title {
  margin: 20px 0;
  padding-bottom: 12px;
  border-bottom: 1px solid #e8e8e8;
}
</style>
