<template>
  <div class="app-container">
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryRef" inline label-width="80px">
        <el-form-item label="客户编号" prop="customerNo">
          <el-input v-model="queryParams.customerNo" placeholder="请输入客户编号" clearable style="width: 320px;" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable style="width: 320px;" />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable style="width: 320px;" />
        </el-form-item>
        <el-form-item label-width="0">
          <div class="search-btns">
            <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" class="btn-new">新增</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="table-heading">报价单信息列表</div>

    <el-card shadow="never" class="table-card">
      <el-table ref="quotationTable" v-loading="loading" :data="dataList" border class="standard-table">
        <el-table-column label="客户编号" align="center" prop="customerNo" width="180" />
        <el-table-column label="客户名称" align="center" prop="customerName" min-width="200" show-overflow-tooltip />
        <el-table-column label="项目名称" align="center" prop="projectName" min-width="200" show-overflow-tooltip />
        <el-table-column label="联系人名称" align="center" prop="contactName" width="120" />
        <el-table-column label="归属公司" align="center" prop="companyName" width="180" />
        <el-table-column label="报价负责人" align="center" prop="managerName" width="120" />
        <el-table-column label="状态" align="center" prop="status" width="100">
           <template #default="scope">
             <el-tag :type="scope.row.status === '已成交' ? 'success' : 'info'" plain>{{ scope.row.status }}</el-tag>
           </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template #default="scope">
            <el-button link type="primary">详情</el-button>
            <el-button link type="primary">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)">删除</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="getList" />
    </el-card>

    <!-- 抽屉：报价单录入 -->
    <el-drawer title="报价单录入" v-model="open" size="1250px" append-to-body>
       <el-form ref="formRef" :model="form" :rules="rules" label-width="110px" class="large-form-nowrap">
          <div class="form-section">
             <div class="section-header">基本信息</div>
             <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="归属公司：" prop="companyId" required>
                       <el-select v-model="form.companyId" placeholder="请选择" style="width: 100%" clearable>
                          <el-option v-for="item in companyOptions" :key="item.id || item.companyCode" :label="item.companyName" :value="item.id || item.companyCode" />
                       </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="客户名称：" prop="customerName" required>
                       <el-select v-model="form.customerName" placeholder="请选择" style="width: 100%" filterable @change="handleCustomerChange">
                          <el-option v-for="item in customerOptions" :key="item.id" :label="item.customerName" :value="item.customerName" />
                       </el-select>
                    </el-form-item>
                </el-col>
             </el-row>
             <el-row :gutter="20">
                <el-col :span="8">
                   <el-form-item label="项目类型：" prop="projectType">
                      <el-radio-group v-model="form.projectType">
                        <el-radio label="项目商机">项目商机</el-radio>
                        <el-radio label="年度入围">年度入围</el-radio>
                      </el-radio-group>
                   </el-form-item>
                </el-col>
                <el-col :span="8">
                   <el-form-item label="关联项目：" prop="projectId">
                      <el-select v-model="form.projectId" placeholder="请选择" style="width: 100%">
                         <el-option label="新高速改造配套用品" value="1" />
                      </el-select>
                   </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="联系人：" prop="contactId">
                       <el-select v-model="form.contactId" placeholder="请选择" style="width: 100%" clearable>
                          <el-option v-for="item in contactOptions" :key="item.id" :label="item.name" :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="contactPhone">
                      <el-input v-model="form.contactPhone" placeholder="请输入联系方式" />
                   </el-form-item>
                </el-col>
                <el-col :span="8">
                   <el-form-item label="报价类型：" prop="quoteType">
                      <el-radio-group v-model="form.quoteType">
                         <el-radio label="准确报价">准确报价</el-radio>
                         <el-radio label="模糊报价">模糊报价</el-radio>
                      </el-radio-group>
                   </el-form-item>
                </el-col>
                <el-col :span="8">
                   <el-form-item label="报价时限：" prop="quoteDeadline">
                      <el-date-picker v-model="form.quoteDeadline" type="date" placeholder="请选择" style="width: 100%" />
                   </el-form-item>
                </el-col>
             </el-row>
             <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="报价负责人：" prop="managerId">
                       <el-select v-model="form.managerId" placeholder="请选择" style="width: 100%" clearable filterable>
                          <el-option v-for="item in managerOptions" :key="item.staffId || item.userId" :label="item.staffName || item.nickName" :value="String(item.staffId || item.userId)" />
                       </el-select>
                    </el-form-item>
                </el-col>
             </el-row>
             <el-form-item label="说明：" prop="remark">
                <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入内容" />
             </el-form-item>
          </div>

          <div class="form-section goods-section">
             <div class="section-header flex-header">
                <span>报价清单</span>
                <el-button type="primary" link icon="Plus" @click="handleAddGoods">添加清单</el-button>
             </div>
             <el-table :data="form.goodsList" border class="file-table goods-table" size="small">
               <el-table-column label="商品编码" align="center" prop="goodsCode" width="100" />
               <el-table-column label="商品图片" align="center" width="80">
                  <template #default="scope">
                    <el-image v-if="scope.row.goodsImage" :src="scope.row.goodsImage" fit="cover" style="width: 40px; height: 40px" />
                    <span v-else>无</span>
                  </template>
               </el-table-column>
               <el-table-column label="商品信息" align="center" prop="goodsInfo" min-width="150" show-overflow-tooltip />
               <el-table-column label="单位" align="center" prop="unit" width="60" />
               <el-table-column label="市场价" align="center" prop="marketPrice" width="80" />
               <el-table-column label="平台售价" align="center" prop="platformPrice" width="80" />
               <el-table-column label="最低价" align="center" prop="minPrice" width="80" />
               <el-table-column label="起订量" align="center" prop="minOrder" width="70" />
               
               <el-table-column align="center" width="90">
                  <template #header><span class="red-header">采购数量</span></template>
                  <template #default="scope">
                    <el-input v-model="scope.row.purchaseNum" size="small" />
                  </template>
               </el-table-column>
               
               <el-table-column align="center" width="90">
                  <template #header><span class="red-header">报价</span></template>
                  <template #default="scope">
                    <el-input v-model="scope.row.quotePrice" size="small" />
                  </template>
               </el-table-column>

               <el-table-column label="折扣率" align="center" prop="discountRate" width="80" />
               <el-table-column label="操作" align="center" width="60">
                  <template #default="scope">
                    <el-button link type="danger" @click="removeGoods(scope.$index)">删除</el-button>
                  </template>
               </el-table-column>
               <template #empty>暂无数据</template>
             </el-table>
          </div>

          <div class="form-section no-border">
             <div class="section-header flex-header">
                <span>附件</span>
                <el-button type="primary" link icon="Upload">上传附件</el-button>
             </div>
             <el-table :data="[]" border class="file-table" size="small">
               <el-table-column label="文件名称" align="center" />
               <el-table-column label="文件类型" align="center" />
               <el-table-column label="上传时间" align="center" />
               <el-table-column label="操作" align="center" />
               <template #empty>暂无数据</template>
             </el-table>
          </div>
       </el-form>
       <template #footer>
         <div class="drawer-footer" style="text-align: right; padding: 20px 20px 20px 0;">
           <el-button type="primary" @click="submitForm">保存</el-button>
           <el-button @click="open = false">取消</el-button>
         </div>
       </template>
    </el-drawer>
  </div>
</template>

<script setup name="Quotation">
import { ref, reactive, onMounted, getCurrentInstance, watch } from 'vue';
import { listQuotation, addQuotation, delQuotation } from '@/api/saleManage/quotation/index';
import { listCompanyOption, listCustomerInfo } from "@/api/customer/customerInfo/index";
import { selectStaffOptionList } from "@/api/system/comStaff/index";
import { listContact } from "@/api/customer/crmContact";

const { proxy } = getCurrentInstance();

const loading = ref(false);
const total = ref(0);
const dataList = ref([]);
const open = ref(false);

const companyOptions = ref([]);
const customerOptions = ref([]);
const contactOptions = ref([]);
const managerOptions = ref([]);

const queryParams = reactive({
  pageNum: 1, pageSize: 10,
  customerNo: undefined, customerName: undefined, projectName: undefined
});

const form = ref({
   companyId: '', customerName: '', projectType: '项目商机', projectId: '',
   contactId: '', contactPhone: '', quoteType: '准确报价', quoteDeadline: '',
   managerId: '', remark: '', goodsList: []
});

const rules = reactive({
  companyId: [{ required: true, message: "归属公司不能为空", trigger: "change" }],
  customerName: [{ required: true, message: "客户名称不能为空", trigger: "change" }],
});

/** 获取下拉选项 */
const getOptions = () => {
  listCompanyOption().then(res => {
    companyOptions.value = res.data;
  });
  listCustomerInfo({ pageNum: 1, pageSize: 1000 }).then(res => {
    customerOptions.value = res.rows;
  });
  selectStaffOptionList().then(res => {
    managerOptions.value = res.data;
  });
};

/** 客户变更逻辑 */
const handleCustomerChange = (customerName) => {
  form.value.contactId = '';
  contactOptions.value = [];
  const customer = customerOptions.value.find(item => item.customerName === customerName);
  if (customer) {
    listContact({ customerId: customer.id }).then(res => {
      contactOptions.value = res.rows;
    });
  }
};

const getList = async () => {
  loading.value = true;
  try {
    const res = await listQuotation(queryParams);
    dataList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (err) {
    console.error('获取报价单列表失败', err);
    dataList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => { queryParams.pageNum = 1; getList(); };
const resetQuery = () => { proxy.resetForm("queryRef"); handleQuery(); };
const handleAdd = () => { 
  form.value = { 
    companyId: '', customerName: '', projectType: '项目商机', projectId: '',
    contactId: '', contactPhone: '', quoteType: '准确报价', quoteDeadline: '',
    managerId: '', remark: '', goodsList: [] 
  };
  open.value = true; 
};

/** 清单操作逻辑 */
const handleAddGoods = () => {
  form.value.goodsList.push({
    goodsCode: '', goodsInfo: '', unit: '',
    marketPrice: 0, platformPrice: 0, minPrice: 0, minOrder: 1,
    purchaseNum: 0, quotePrice: 0, discountRate: '0%'
  });
};
const removeGoods = (index) => { form.value.goodsList.splice(index, 1); };

/** 提交报价单表单 */
const submitForm = () => {
  proxy.$refs["formRef"].validate(async (valid) => {
    if (valid) {
      try {
        await addQuotation(form.value);
        proxy.$modal.msgSuccess("报价单保存成功");
        open.value = false;
        getList();
      } catch (err) {
        console.error('保存报价单失败', err);
      }
    }
  });
};

/** 删除报价单 */
const handleDelete = (row) => {
  proxy.$modal.confirm(`确认删除该报价单吗？`).then(async () => {
    try {
      await delQuotation(row.id);
      proxy.$modal.msgSuccess("删除成功");
      getList();
    } catch (err) {
      console.error('删除报价单失败', err);
    }
  });
};

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

<style scoped lang="scss">
.app-container { padding: 20px; background-color: #f7f9fb; min-height: calc(100vh - 84px); }

.search-card { 
  margin-bottom: 20px; border: none; background: #fff; border-radius: 8px;
  :deep(.el-form-item) { margin-bottom: 0px; }
}

.search-btns { margin-left: 20px; display: flex; gap: 12px; }

.table-heading {
  font-size: 16px; font-weight: 600; color: #475569; padding: 10px 5px; margin-bottom: 10px; border-bottom: 1px solid #e2e8f0;
}

.table-card { border: none; }
.standard-table :deep(th.el-table__cell) { background-color: #f8fafc !important; color: #475569; font-weight: 600; }

.form-section {
  border-bottom: 1px dashed #e2e8f0; padding-bottom: 20px; margin-bottom: 20px;
  &.no-border { border-bottom: none; }
  .section-header {
    background-color: #f0f7ff; padding: 10px 15px; margin-bottom: 20px; font-weight: 600; color: #3b82f6; border-left: 4px solid #3b82f6;
    &.flex-header { display: flex; justify-content: space-between; align-items: center; }
  }
}

.large-form-nowrap { :deep(.el-form-item__label) { white-space: nowrap !important; } }

.goods-table {
  .red-header { color: #ef4444; font-weight: bold; }
}

.dialog-footer { display: flex; justify-content: center; gap: 20px; }
</style>
