<template>
  <el-drawer
    title="编辑年度入围项目"
    v-model="visible"
    direction="rtl"
    size="80%"
    :close-on-click-modal="false"
    class="selection-drawer"
  >
    <template #default>
      <div class="drawer-body" v-loading="loading">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="110px" class="selection-form" label-position="left">
          <!-- 基本信息 -->
          <div class="section-block">
            <div class="section-title">基本信息</div>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="归属公司" prop="companyNo">
                  <el-select v-model="form.companyNo" placeholder="请选择" style="width: 100%" clearable filterable>
                    <el-option v-for="item in computedCompanyOptions" :key="item.companyCode || item.id"
                      :label="item.companyName" :value="String(item.companyCode || item.id)" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客户名称" prop="customerName">
                  <el-select 
                    v-model="form.customNo" 
                    placeholder="搜索客户" 
                    style="width: 100%" 
                    filterable 
                    clearable
                    @change="handleCustomerChange"
                  >
                    <el-option 
                      v-for="item in computedCustomerOptions" 
                      :key="item.id || item.customerNo" 
                      :label="item.customerName || item.customName" 
                      :value="String(item.customerNo || item.id)" 
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="项目类型" prop="businessType">
                  <el-select v-model="form.businessType" placeholder="请选择" style="width: 100%" clearable>
                    <el-option v-for="item in projectTypeOptions" :key="item.value" :label="item.label" :value="String(item.value)" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="项目类别" prop="projectLevel">
                  <el-select v-model="form.projectLevel" placeholder="请选择" style="width: 100%" clearable>
                    <el-option v-for="item in projectLevelOptions" :key="item.value" :label="item.label" :value="String(item.value)" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="项目负责人" prop="leader">
                    <el-select v-model="form.leader" placeholder="请选择" style="width: 100%" clearable filterable @change="handleLeaderChange">
                      <el-option v-for="item in computedUserOptions" :key="item.staffId || item.userId" :label="(item.staffCode || item.userName ? '(' + (item.staffCode || item.userName) + ') ' : '') + (item.staffName || item.nickName)" :value="String(item.staffId || item.userId)" />
                    </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="产品支持" prop="productSupport">
                    <el-select v-model="form.productSupport" placeholder="请选择" style="width: 100%" clearable filterable @change="handleProductSupportChange">
                      <el-option v-for="item in computedProductSupportOptions" :key="item.staffId || item.userId" :label="(item.staffCode || item.userName ? '(' + (item.staffCode || item.userName) + ') ' : '') + (item.staffName || item.nickName)" :value="String(item.staffId || item.userId)" />
                    </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入项目名称" maxlength="200" show-word-limit />
            </el-form-item>
          </div>

          <!-- 项目情况 -->
          <div class="section-block">
            <div class="section-title">项目情况</div>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="金额(万)" prop="amount">
                  <el-input-number v-model="form.amount" :precision="2" :step="1" :min="0" controls-position="right" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="报名费" prop="entryFee">
                  <el-input-number v-model="form.entryFee" :precision="2" :step="1" :min="0" controls-position="right" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="投标保证金" prop="bidBond">
                  <el-input-number v-model="form.bidBond" :precision="2" :step="1" :min="0" controls-position="right" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="赢单率(%)" prop="winningRate">
                  <el-input v-model="form.winningRate" placeholder="请输入" type="number">
                    <template #append>%</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="报名截止时间" prop="signUpDeadline">
                  <el-date-picker v-model="form.signUpDeadline" type="date" value-format="YYYY-MM-DD" placeholder="请选择" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="投标截止时间" prop="tenderDeadline">
                  <el-date-picker v-model="form.tenderDeadline" type="date" value-format="YYYY-MM-DD" placeholder="请选择" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
               <el-col :span="8">
                 <el-form-item label="服务期(年)" prop="standardPeriod">
                   <el-input v-model="form.standardPeriod" placeholder="请输入" maxlength="50" />
                 </el-form-item>
               </el-col>
               <el-col :span="8">
                 <el-form-item label="服务时间段" prop="serviceTime">
                   <el-input v-model="form.serviceTime" placeholder="请输入" maxlength="100" />
                 </el-form-item>
               </el-col>
              <el-col :span="8">
                <el-form-item label="入围类型" prop="shortlistedType">
                  <el-select v-model="form.shortlistedType" placeholder="请选择" style="width: 100%" clearable>
                    <el-option v-for="item in shortlistedTypeOptions" :key="item.value" :label="item.label" :value="String(item.value)" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="物资类目" prop="profession">
                  <el-select v-model="form.profession" placeholder="请选择" style="width: 100%" clearable>
                    <el-option v-for="item in professionOptions" :key="item.id" :label="item.industryCategoryName" :value="String(item.id)" />
                  </el-select>
                </el-form-item>
              </el-col>
               <el-col :span="8">
                 <el-form-item label="招标代理机构" prop="biddingAgency">
                   <el-input v-model="form.biddingAgency" placeholder="请输入" maxlength="100" />
                 </el-form-item>
               </el-col>
               <el-col :span="8">
                 <el-form-item label="代理机构联系方式" prop="agencyContact" class="label-nowrap">
                   <el-input v-model="form.agencyContact" placeholder="请输入" maxlength="50" />
                 </el-form-item>
               </el-col>
            </el-row>
            <el-form-item label="标期类型" prop="bidPeriodType">
              <el-radio-group v-model="form.bidPeriodType">
                <el-radio :value="1">单项目入围</el-radio>
                <el-radio :value="2">周期性框架</el-radio>
              </el-radio-group>
            </el-form-item>
             <el-form-item label="招标链接" prop="biddingLink" v-if="form.bidPeriodType === 2">
               <el-input v-model="form.biddingLink" placeholder="请输入/粘贴链接" maxlength="500" />
             </el-form-item>
            <el-form-item label="入围要求" prop="condition">
              <el-input v-model="form.condition" type="textarea" :rows="3" placeholder="请输入" maxlength="500" show-word-limit />
            </el-form-item>
            <el-form-item label="项目描述" prop="projectDesc">
              <el-input v-model="form.projectDesc" type="textarea" :rows="3" placeholder="请输入项目描述" maxlength="500" show-word-limit />
            </el-form-item>
          </div>

          <!-- 附件 -->
          <div class="section-block no-border">
            <div class="section-title attachment-header">
              <span>附件</span>
              <el-upload
                :action="uploadFileUrl"
                :headers="headers"
                :on-success="handleUploadSuccess"
                :show-file-list="false"
                multiple
                class="upload-btn"
              >
                <el-button link type="primary" icon="Upload">上传附件</el-button>
              </el-upload>
            </div>
            <el-table :data="fileList" border class="file-table">
              <el-table-column label="文件名称" prop="name" show-overflow-tooltip />
              <el-table-column label="操作" width="100" align="center">
                 <template #default="scope">
                   <el-button link type="danger" @click="handleDeleteFile(scope.$index)">删除</el-button>
                 </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
      </div>
    </template>
    <template #footer>
      <div class="drawer-footer">
        <el-button type="primary" @click="submitForm" :loading="submitting">保存</el-button>
        <el-button @click="visible = false">取消</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, watch, computed, getCurrentInstance } from 'vue';
import { getProjectSelection, updateProjectSelection } from '@/api/saleManage/projectSelection/index';
import { listCustomerInfo } from "@/api/customer/customerInfo/index";
import { listByIds } from "@/api/system/oss/index";
import { globalHeaders } from '@/utils/request';
import { Upload } from '@element-plus/icons-vue';

const props = defineProps({
  modelValue: Boolean,
  id: [String, Number],
  companyOptions: Array,
  userOptions: Array,
  projectLevelOptions: Array,
  projectTypeOptions: Array,
  shortlistedTypeOptions: Array,
  professionOptions: Array
});

const emit = defineEmits(['update:modelValue', 'success']);
const proxy = getCurrentInstance().proxy;

const visible = ref(false);
const loading = ref(false);
const submitting = ref(false);
const customerLoading = ref(false);
const customerOptions = ref([]);
const formRef = ref(null);
const fileList = ref([]);
const uploadFileUrl = import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload';
const headers = globalHeaders();

const form = reactive({});

const rules = reactive({
  companyNo: [{ required: true, message: '归属公司不能为空', trigger: 'change' }],
  customName: [{ required: true, message: '客户名称不能为空', trigger: 'change' }],
  businessType: [{ required: true, message: '项目类型不能为空', trigger: 'change' }],
  projectLevel: [{ required: true, message: '项目类别不能为空', trigger: 'change' }],
  projectName: [
    { required: true, message: '项目名称不能为空', trigger: 'blur' },
    { max: 200, message: '项目名称不能超过200个字符', trigger: 'blur' }
  ],
  amount: [{ required: true, message: '金额不能为空', trigger: 'blur' }],
  entryFee: [{ required: true, message: '报名费不能为空', trigger: 'blur' }],
  winningRate: [{ required: true, message: '赢单率不能为空', trigger: 'blur' }],
  signUpDeadline: [{ required: true, message: '报名截止时间不能为空', trigger: 'change' }],
  tenderDeadline: [{ required: true, message: '投标截止时间不能为空', trigger: 'change' }],
  standardPeriod: [
    { required: true, message: '服务期不能为空', trigger: 'blur' },
    { max: 50, message: '服务期不能超过50个字符', trigger: 'blur' }
  ],
  shortlistedType: [{ required: true, message: '入围类型不能为空', trigger: 'change' }],
  profession: [{ required: true, message: '物资类目不能为空', trigger: 'change' }],
  bidPeriodType: [{ required: true, message: '标期类型不能为空', trigger: 'change' }],
  condition: [
    { required: true, message: '入围要求不能为空', trigger: 'blur' },
    { max: 200, message: '入围要求不能超过200个字符', trigger: 'blur' }
  ],
  serviceTime: [{ max: 100, message: '服务时间段不能超过100个字符', trigger: 'blur' }],
  biddingAgency: [{ max: 100, message: '招标代理机构不能超过100个字符', trigger: 'blur' }],
  agencyContact: [{ max: 50, message: '代理机构联系方式不能超过50个字符', trigger: 'blur' }],
  biddingLink: [
    { pattern: /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([\/\w .-]*)*\/?$/, message: '请输入正确的招标链接地址', trigger: 'blur' }
  ],
  projectDesc: [{ max: 200, message: '项目描述不能超过200个字符', trigger: 'blur' }]
});

// 【回显增强】处理选项列表中不存在当前项的情况
const computedCompanyOptions = computed(() => {
  const options = [...(props.companyOptions || [])];
  if (form.companyNo && form.companyName) {
    const exists = options.some(i => String(i.companyCode || i.id) === String(form.companyNo));
    if (!exists) options.unshift({ companyCode: form.companyNo, companyName: form.companyName });
  }
  return options;
});

const computedUserOptions = computed(() => {
  const options = [...(props.userOptions || [])];
  if (form.leader && form.leaderName) {
    const exists = options.some(i => String(i.staffId || i.userId) === String(form.leader));
    if (!exists) options.unshift({ staffId: form.leader, staffName: form.leaderName });
  }
  return options;
});

const computedProductSupportOptions = computed(() => {
  const options = [...(props.userOptions || [])];
  if (form.productSupport && form.productSupportName) {
    const exists = options.some(i => String(i.staffId || i.userId) === String(form.productSupport));
    if (!exists) options.unshift({ staffId: form.productSupport, staffName: form.productSupportName });
  }
  return options;
});

const computedCustomerOptions = computed(() => {
  const options = [...customerOptions.value];
  if (form.customNo && form.customName) {
    const exists = options.some(i => String(i.customerNo || i.id) === String(form.customNo));
    if (!exists) options.unshift({ customerNo: form.customNo, customerName: form.customName });
  }
  return options;
});

watch(() => props.modelValue, (val) => {
  visible.value = val;
  if (val && props.id) loadDetail(props.id);
});
watch(() => visible.value, (val) => { emit('update:modelValue', val); });

const loadDetail = (id) => {
  loading.value = true;
  getProjectSelection(id).then(res => {
    const data = res.data || res;
    Object.assign(form, data);
    
    // 强制转字符串以适配回显
    form.companyNo = data.companyNo ? String(data.companyNo) : '';
    form.leader = data.leader ? String(data.leader) : '';
    form.productSupport = data.productSupport ? String(data.productSupport) : '';
    form.projectLevel = data.projectLevel ? String(data.projectLevel) : '';
    form.businessType = data.businessType ? String(data.businessType) : '';
    form.shortlistedType = data.shortlistedType ? String(data.shortlistedType) : '';
    form.profession = data.profession ? String(data.profession) : '';

    // 补全 productSupportName
    if (data.productSupport) {
      const user = props.userOptions.find(u => String(u.staffId || u.userId) === String(data.productSupport));
      form.productSupportName = user ? (user.staffName || user.nickName) : '';
    }

    // 字段回显增强：将 VO/DTO 字段名映射回 Entity 字段名
    if (data.customerName && !data.customName) form.customName = data.customerName;
    if (data.winRate && !data.winningRate) form.winningRate = data.winRate;
    if (data.registrationDeadline && !data.signUpDeadline) form.signUpDeadline = data.registrationDeadline;

    // 字段映射增强，适配列表页与新增/编辑页字段名不一致的情况
    if (data.winRate && !data.winningRate) form.winningRate = data.winRate;
    if (data.registrationDeadline && !data.signUpDeadline) form.signUpDeadline = data.registrationDeadline;

    if (form.fileNo) {
      listByIds(form.fileNo).then(ossRes => {
        fileList.value = (ossRes.data || []).map(i => ({ name: i.originalName, url: i.url, ossId: i.ossId }));
      });
    } else {
      fileList.value = [];
    }
  }).finally(() => { loading.value = false; });
};

const remoteLoadCustomers = async (query) => {
  customerLoading.value = true;
  try {
    const res = await listCustomerInfo({ 
      pageNum: 1,
      pageSize: 500,
      isHighSeas: 'all'
    });
    customerOptions.value = res.rows || [];
  } catch (e) {
    customerOptions.value = [];
  } finally {
    customerLoading.value = false;
  }
};

onMounted(() => {
  remoteLoadCustomers('');
});

const handleCustomerChange = (val) => {
  const customer = computedCustomerOptions.value.find(item => String(item.customerNo || item.id) === String(val));
  if (customer) {
    form.customName = customer.customerName || customer.customName;
    form.customNo = String(customer.customerNo || customer.id);
    // 联动带出行业信息
    if (customer.industryCategoryId) {
      form.profession = String(customer.industryCategoryId);
    }
  } else {
    form.customName = undefined;
    form.customNo = undefined;
  }
};

const handleLeaderChange = (val) => {
  const user = computedUserOptions.value.find(u => String(u.staffId || u.userId) === String(val));
  if (user) {
    form.leaderName = user.staffName || user.nickName;
  } else {
    form.leaderName = undefined;
  }
};

const handleProductSupportChange = (val) => {
  const user = computedProductSupportOptions.value.find(u => String(u.staffId || u.userId) === String(val));
  if (user) {
    form.productSupportName = user.staffName || user.nickName;
  } else {
    form.productSupportName = undefined;
  }
};

const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    fileList.value.push({ name: res.data.fileName, url: res.data.url, ossId: res.data.ossId });
    form.fileNo = fileList.value.map(f => f.ossId).join(',');
    proxy.$modal.msgSuccess("上传成功");
  }
};

const handleDeleteFile = (index) => {
  fileList.value.splice(index, 1);
  form.fileNo = fileList.value.map(f => f.ossId).join(',');
};

const submitForm = () => {
  formRef.value.validate(valid => {
    if (valid) {
      submitting.value = true;
      updateProjectSelection(form).then(() => {
        proxy.$modal.msgSuccess("修改成功");
        visible.value = false;
        emit('success');
      }).finally(() => { submitting.value = false; });
    }
  });
};
</script>

<style scoped lang="scss">
.selection-drawer {
  :deep(.el-drawer__header) {
    margin-bottom: 0; padding: 15px 20px; border-bottom: 1px solid #f0f0f0;
    span { font-size: 16px; font-weight: normal !important; color: #333; }
  }
}
.drawer-body {
  padding: 10px 20px;
}
.selection-form {
  :deep(.el-form-item__label) {
    font-weight: normal !important;
    color: #666;
  }
}
.section-block {
  margin-bottom: 15px;
  .section-title {
    font-size: 14px;
    font-weight: normal !important;
    color: #409eff;
    margin-bottom: 10px;
    padding-bottom: 6px;
    border-bottom: 1px solid #f0f2f5;
  }
}
.attachment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.drawer-footer {
  padding: 10px 20px;
  border-top: 1px solid #f0f2f5;
  text-align: right;
  .el-button { font-weight: normal !important; }
}
.label-nowrap :deep(.el-form-item__label) { white-space: nowrap !important; }
.file-table {
  :deep(.el-table__cell) {
    font-weight: normal !important;
  }
}
</style>
