<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="detail-header">
      <el-icon class="back-icon" @click="goBack"><ArrowLeft /></el-icon>
      <span class="header-title">新增合约供货</span>
    </div>

    <!-- 表单卡片 -->
    <el-card shadow="never" class="form-card">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="所属公司" prop="companyId">
              <el-select v-model="form.companyId" placeholder="请选择" style="width: 100%">
                <el-option v-for="item in companyList" :key="item.id" :label="item.companyName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="form.supplierId" placeholder="请选择" style="width: 100%" @change="handleSupplierChange">
                <el-option v-for="item in supplierList" :key="item.id" :label="item.enterpriseName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="date"
                placeholder="请选择"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled-date="disabledStartDate"
                @change="onStartTimeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="date"
                placeholder="请选择"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled-date="disabledEndDate"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="附件" prop="attachment">
              <FileUpload
                v-model="form.proFile"
                :limit="10"
                :file-size="50"
                :file-type="['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'pdf']"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 商品列表 -->
        <div class="section-title">
          <el-button type="primary" @click="handleAddProduct">添加商品信息</el-button>
        </div>

        <el-table :data="productList" border style="width: 100%; margin-top: 20px">
          <el-table-column prop="productCode" 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="productName" label="产品名称" align="center" show-overflow-tooltip />
          <el-table-column prop="productType" label="产品类型" align="center" width="120" />
          <el-table-column prop="brand" label="品牌" align="center" width="100" />
          <el-table-column prop="unit" 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.platformPrice || '0.00' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="供应价" align="center" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.offerPrice" placeholder="请输入" />
            </template>
          </el-table-column>
          <el-table-column label="供应时效（天）" align="center" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.supplyCycle" placeholder="请输入" />
            </template>
          </el-table-column>
          <el-table-column label="上架状态" align="center" width="100">
            <template #default="scope">
              <span>{{ scope.row.upPrice }}</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.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-row style="margin-top: 20px">
          <el-col :span="24" style="text-align: center">
            <el-button type="primary" @click="handleSubmit">提交</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

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

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ArrowLeft } from '@element-plus/icons-vue';
import { addContractsupply } from '@/api/supplier/contractsupply';
import { getCompanyList, listInfo } from '@/api/customer/info';
import { ElMessage } from 'element-plus';
import FileUpload from '@/components/FileUpload/index.vue';
import Product from './components/Product.vue';
import type { BaseVO } from '@/api/product/base/types';

const router = useRouter();

const formRef = ref();
const productList = ref<any[]>([]);
const companyList = ref<any[]>([]);
const supplierList = ref<any[]>([]);

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

const form = ref({
  companyId: '',
  supplierId: '',
  supplyNo: '',
  startTime: '',
  endTime: '',
  attachment: '',
  proFile: '',
  remark: '',
  isSubmit: false
});

const rules = {
  supplierId: [{ required: true, message: '请选择供应商', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
};

/** 禁用开始时间早于今天 */
const disabledStartDate = (time: Date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() < today.getTime();
};

/** 禁用结束时间早于开始时间 */
const disabledEndDate = (time: Date) => {
  if (!form.value.startTime) {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    return time.getTime() < today.getTime();
  }
  const start = new Date(form.value.startTime);
  start.setHours(0, 0, 0, 0);
  return time.getTime() < start.getTime();
};

/** 选择开始时间后清空结束时间 */
const onStartTimeChange = () => {
  form.value.endTime = '';
};

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

/** 获取公司列表 */
const getCompanyData = async () => {
  try {
    const res = await getCompanyList({ pageNum: 1, pageSize: 1000 });
    companyList.value = res.rows || res.data || [];
  } catch (e) {
    console.error('获取公司列表失败:', e);
  }
};

/** 获取供应商列表 */
const getSupplierData = async () => {
  try {
    const res = await listInfo();
    supplierList.value = res.rows || [];
  } catch (e) {
    console.error('获取供应商列表失败:', e);
  }
};

/** 供应商选择变化 */
const handleSupplierChange = (value: any) => {
  const supplier = supplierList.value.find((item) => String(item.id) === String(value));
  if (supplier) {
    form.value.supplyNo = supplier.supplierNo || '';
  }
};

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

/** 处理商品选择确认 */
const handleProductConfirm = (selectedProducts: BaseVO[]) => {
  if (selectedProducts.length === 0) {
    ElMessage.warning('请选择要添加的商品');
    return;
  }

  productList.value = selectedProducts;
  ElMessage.success(`成功添加${selectedProducts.length}个商品`);
};

/** 删除商品 */
const handleDeleteProduct = (index: number) => {
  productList.value.splice(index, 1);
};

/** 提交表单 */
const handleSubmit = async () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 从表格中收集最新的数据
        const tableInputs = document.querySelectorAll('.el-table input');
        let inputIndex = 0;

        productList.value.forEach((item, index) => {
          // 每行有两个输入框：供应价和供应时效
          if (tableInputs[inputIndex]) {
            item.offerPrice = (tableInputs[inputIndex] as HTMLInputElement).value;
            inputIndex++;
          }
          if (tableInputs[inputIndex]) {
            item.supplyCycle = (tableInputs[inputIndex] as HTMLInputElement).value;
            inputIndex++;
          }
        });

        // 组装提交数据，包含表单数据和商品列表
        const submitData = {
          ...form.value,
          contractProduct: productList.value.map((item) => ({
            productId: item.productId,
            productNo: item.productCode,
            offerPrice: item.offerPrice || '',
            supplyCycle: item.supplyCycle || ''
          }))
        };

        console.log('提交的数据:', submitData);
        console.log('商品列表:', productList.value);

        await addContractsupply(submitData);
        ElMessage.success('新增成功');
        router.back();
      } catch (e) {
        console.error('新增失败:', e);
        ElMessage.error('新增失败');
      }
    }
  });
};

onMounted(() => {
  getCompanyData();
  getSupplierData();
});
</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>
