<template>
  <div class="hot-custom-page">
    <div class="hot-custom-container">
      <!-- 搜索区域 -->
      <div class="search-card">
        <el-form :model="queryParams" :inline="true">
          <el-form-item label="楼层名称">
            <el-input v-model="queryParams.name" placeholder="请输入楼层名称" clearable style="width: 240px" />
          </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" icon="Plus" @click="handleAdd">添加热门楼层</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <div class="table-card">
        <div class="table-header">
          <span class="table-title">热门楼层信息列表</span>
          <el-button icon="Refresh" circle size="small" @click="getList" />
        </div>

        <el-table v-loading="loading" :data="floorList" border>
          <el-table-column label="楼层名称" align="center" prop="name" min-width="120" />
          <el-table-column label="链接地址" align="center" prop="link" min-width="280">
            <template #default="scope">
              <el-link v-if="scope.row.link" type="primary" :href="scope.row.link" target="_blank">{{ scope.row.link }}</el-link>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.isShow === '1' ? 'primary' : 'info'" size="small">
                {{ scope.row.isShow === '1' ? '显示' : '隐藏' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="排序" align="center" prop="sort" width="80" />
          <el-table-column label="更新时间" align="center" width="180">
            <template #default="scope">
              {{ scope.row.updateTime || scope.row.createTime || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200">
            <template #default="scope">
              <span class="action-link primary" @click="handleEdit(scope.row)">编辑</span>
              <span class="action-link primary" @click="handleConfigProduct(scope.row)">配置商品</span>
              <span class="action-link danger" @click="handleDelete(scope.row)">删除</span>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          :total="total"
          @pagination="getList"
        />
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="700px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="楼层名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入楼层名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="链接地址" prop="link">
              <el-input v-model="form.link" placeholder="请输入链接地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" :max="999" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="isShow">
              <el-switch v-model="form.isShow" active-value="1" inactive-value="0" active-text="显示" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="封面图片" prop="mainImg">
          <upload-image v-model="form.mainImg" :limit="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 认</el-button>
        <el-button @click="dialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 配置商品对话框 -->
    <el-dialog v-model="productDialog.visible" title="推荐商品" width="900px" append-to-body>
      <div class="product-dialog-header">
        <el-button type="primary" @click="handleAddProduct">新增商品</el-button>
        <el-button type="primary" @click="handleImportProduct">导入商品</el-button>
        <el-button icon="Refresh" circle size="small" @click="getLinkedProducts" style="margin-left: auto" />
      </div>
      <el-table v-loading="productDialog.loading" :data="linkedProducts" border>
        <el-table-column label="商品编号" align="center" prop="productNo" width="120" />
        <el-table-column label="商品名称" align="center" prop="itemName" min-width="200" show-overflow-tooltip />
        <el-table-column label="商品图片" align="center" width="100">
          <template #default="scope">
            <el-image v-if="scope.row.productImage" :src="scope.row.productImage" fit="cover" style="width: 60px; height: 60px" />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="价格" align="center" width="100">
          <template #default="scope">
            {{ scope.row.minSellingPrice || scope.row.marketPrice || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="80">
          <template #default="scope">
            <span class="action-link danger" @click="handleRemoveLinked(scope.row)">删除</span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button type="primary" @click="productDialog.visible = false">确 认</el-button>
        <el-button @click="productDialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 选择商品对话框 -->
    <el-dialog v-model="selectDialog.visible" title="商品信息" width="900px" append-to-body>
      <div class="select-dialog-header">
        <el-input v-model="selectDialog.keyword" placeholder="请输入商品编号名称输入搜索" style="width: 300px" />
        <el-button type="primary" @click="searchProducts">搜 索</el-button>
      </div>
      <el-table v-loading="selectDialog.loading" :data="productList" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="商品编号" align="center" prop="productNo" width="120" />
        <el-table-column label="商品名称" align="center" prop="itemName" min-width="180" show-overflow-tooltip />
        <el-table-column label="商品图片" align="center" width="100">
          <template #default="scope">
            <el-image v-if="scope.row.productImage" :src="scope.row.productImage" fit="cover" style="width: 60px; height: 60px" />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="价格" align="center" width="100">
          <template #default="scope">
            {{ scope.row.minSellingPrice || scope.row.marketPrice || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" width="100">
          <template #default="scope">
            <el-input-number v-model="scope.row.sort" :min="0" size="small" controls-position="right" style="width: 80px" />
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="selectDialog.total > 0"
        v-model:page="selectDialog.pageNum"
        v-model:limit="selectDialog.pageSize"
        :total="selectDialog.total"
        @pagination="getProductList"
      />
      <template #footer>
        <el-button type="primary" @click="confirmSelectProducts">确 定</el-button>
        <el-button @click="selectDialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GiftHotCustom" lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import type { FormInstance } from 'element-plus';
import { listGiftFloor, addGiftFloor, updateGiftFloor, delGiftFloor } from '@/api/product/giftFloor';
import { listGiftFloorLinkWithProduct, addGiftFloorLink, delGiftFloorLink } from '@/api/product/giftFloorLink';
import { listProduct } from '@/api/product/productBase';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 楼层类型：2=热门定制
const FLOOR_TYPE = 2;

const queryParams = reactive({
  name: '',
  type: FLOOR_TYPE,
  pageNum: 1,
  pageSize: 10
});

const floorList = ref<any[]>([]);
const loading = ref(false);
const total = ref(0);

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

const formRef = ref<FormInstance>();
const initForm = {
  id: undefined as number | undefined,
  name: '',
  link: '',
  mainImg: '',
  sort: 0,
  isShow: '1',
  type: FLOOR_TYPE
};
const form = ref({ ...initForm });

const rules = {
  name: [{ required: true, message: '请输入楼层名称', trigger: 'blur' }]
};

// 配置商品弹框
const productDialog = reactive({
  visible: false,
  loading: false,
  floorId: null as number | null,
  floorName: ''
});
const linkedProducts = ref<any[]>([]);

// 选择商品弹框
const selectDialog = reactive({
  visible: false,
  loading: false,
  keyword: '',
  pageNum: 1,
  pageSize: 10,
  total: 0
});
const productList = ref<any[]>([]);
const selectedProducts = ref<any[]>([]);

const getList = async () => {
  loading.value = true;
  try {
    const res = await listGiftFloor(queryParams);
    floorList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error('加载列表失败', error);
  } finally {
    loading.value = false;
  }
};

const reset = () => {
  form.value = { ...initForm };
  formRef.value?.resetFields();
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryParams.name = '';
  handleQuery();
};

const handleAdd = () => {
  reset();
  dialog.title = '添加热门楼层';
  dialog.visible = true;
};

const handleEdit = (row: any) => {
  reset();
  form.value = {
    id: row.id,
    name: row.name || '',
    link: row.link || '',
    mainImg: row.mainImg || '',
    sort: row.sort || 0,
    isShow: row.isShow || '1',
    type: FLOOR_TYPE
  };
  dialog.title = '编辑热门楼层';
  dialog.visible = true;
};

const handleConfigProduct = (row: any) => {
  productDialog.floorId = row.id;
  productDialog.floorName = row.name;
  productDialog.visible = true;
  getLinkedProducts();
};

// 获取已关联的商品（调用后端联表查询接口）
const getLinkedProducts = async () => {
  if (!productDialog.floorId) return;
  productDialog.loading = true;
  try {
    const res = await listGiftFloorLinkWithProduct(productDialog.floorId);
    linkedProducts.value = res.data || [];
  } catch (error) {
    console.error('加载关联商品失败', error);
  } finally {
    productDialog.loading = false;
  }
};

// 删除关联商品
const handleRemoveLinked = (row: any) => {
  proxy?.$modal.confirm('是否确认删除该商品？').then(() => {
    delGiftFloorLink(row.id).then(() => {
      proxy?.$modal.msgSuccess('删除成功');
      getLinkedProducts();
    });
  });
};

// 新增商品
const handleAddProduct = () => {
  selectDialog.keyword = '';
  selectDialog.pageNum = 1;
  selectDialog.visible = true;
  getProductList();
};

// 导入商品
const handleImportProduct = () => {
  handleAddProduct();
};

// 获取商品列表
const getProductList = async () => {
  selectDialog.loading = true;
  try {
    const res = await listProduct({
      keyword: selectDialog.keyword,
      pageNum: selectDialog.pageNum,
      pageSize: selectDialog.pageSize
    });
    productList.value = (res.rows || []).map((item: any) => ({ ...item, sort: 0 }));
    selectDialog.total = res.total || 0;
  } catch (error) {
    console.error('加载商品列表失败', error);
  } finally {
    selectDialog.loading = false;
  }
};

// 搜索商品
const searchProducts = () => {
  selectDialog.pageNum = 1;
  getProductList();
};

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedProducts.value = selection;
};

// 确认选择商品
const confirmSelectProducts = async () => {
  if (selectedProducts.value.length === 0) {
    proxy?.$modal.msgWarning('请选择商品');
    return;
  }

  // 检查是否有重复商品
  const existingProductNos = linkedProducts.value.map((item: any) => item.productNo);
  const duplicates = selectedProducts.value.filter((p: any) => existingProductNos.includes(p.productNo));

  if (duplicates.length > 0) {
    const duplicateNames = duplicates.map((p: any) => p.itemName || p.productNo).join('、');
    proxy?.$modal.msgWarning(`商品 ${duplicateNames} 已存在，请勿重复添加`);
    return;
  }

  try {
    for (const product of selectedProducts.value) {
      await addGiftFloorLink({
        floorId: productDialog.floorId,
        productId: product.id,
        productNo: product.productNo,
        sort: product.sort || 0,
        status: '0'
      });
    }
    proxy?.$modal.msgSuccess('添加成功');
    selectDialog.visible = false;
    getLinkedProducts();
  } catch (error) {
    proxy?.$modal.msgError('添加失败');
  }
};

const handleDelete = (row: any) => {
  proxy?.$modal.confirm(`是否确认删除楼层"${row.name}"？`).then(() => {
    delGiftFloor(row.id).then(() => {
      proxy?.$modal.msgSuccess('删除成功');
      getList();
    });
  });
};

const submitForm = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      const api = form.value.id ? updateGiftFloor : addGiftFloor;
      api(form.value).then(() => {
        proxy?.$modal.msgSuccess(form.value.id ? '修改成功' : '添加成功');
        dialog.visible = false;
        getList();
      });
    }
  });
};

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

<style scoped lang="scss">
.hot-custom-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20px;
}

.hot-custom-container {
  max-width: 1200px;
  margin: 0 auto;
}

.search-card {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 12px;
}

.table-card {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.action-link {
  cursor: pointer;
  margin: 0 6px;

  &.primary {
    color: #409eff;
    &:hover {
      color: #66b1ff;
    }
  }

  &.danger {
    color: #f56c6c;
    &:hover {
      color: #f78989;
    }
  }
}

.product-dialog-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.select-dialog-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}
</style>
