<template>
  <el-drawer
    v-model="visible"
    title="新增年度入围"
    direction="rtl"
    size="80%"
    :destroy-on-close="true"
    class="custom-edit-drawer"
  >
    <div class="edit-form-container">
      <el-form :model="drawerForm" :rules="drawerRules" ref="drawerFormRef" label-width="140px" label-position="right">
        <div class="form-section">
          <div class="section-title">基本信息</div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="归属公司" prop="companyNo">
                <el-select v-model="drawerForm.companyNo" style="width:100%" placeholder="请选择" filterable>
                  <el-option v-for="item in options.company" :key="item.companyCode" :label="item.companyName" :value="item.companyCode" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户名称" prop="customName">
                <el-select 
                  v-model="drawerForm.customName" 
                  style="width:100%" 
                  placeholder="搜索客户" 
                  filterable 
                  clearable
                >
                  <el-option 
                    v-for="item in computedCustomerOptions" 
                    :key="item.id || item.customerNo" 
                    :label="item.customerName || item.customName" 
                    :value="item.customerName || item.customName" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目级别" prop="projectLevel" label-for="projectLevelSelect">
                <el-select id="projectLevelSelect" v-model="drawerForm.projectLevel" style="width:100%" placeholder="请选择">
                  <el-option v-for="item in options.level" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="项目类型" prop="businessType" label-for="businessTypeSelect">
                <el-select id="businessTypeSelect" v-model="drawerForm.businessType" style="width:100%" placeholder="请选择">
                  <el-option v-for="item in options.type" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目名称" prop="projectName">
                <el-input v-model="drawerForm.projectName" placeholder="请输入项目名称" maxlength="200" show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目负责人" prop="leader" label-for="leaderSelect">
                <el-select id="leaderSelect" v-model="drawerForm.leader" style="width:100%" placeholder="请选择" filterable>
                  <el-option v-for="item in options.user" :key="item.userId || item.staffId" :label="(item.userName || item.staffCode ? '(' + (item.userName || item.staffCode) + ') ' : '') + (item.nickName || item.staffName)" :value="String(item.userId || item.staffId)" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="平台名称" prop="platformName">
                <el-input v-model="drawerForm.platformName" placeholder="请输入平台名称" maxlength="200" show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="产品支持" prop="productSupport" label-for="productSupportSelect">
                <el-select id="productSupportSelect" v-model="drawerForm.productSupport" style="width:100%" placeholder="请选择" filterable clearable>
                  <el-option v-for="item in options.user" :key="item.userId || item.staffId" :label="(item.userName || item.staffCode ? '(' + (item.userName || item.staffCode) + ') ' : '') + (item.nickName || item.staffName)" :value="String(item.userId || item.staffId)" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="平台链接" prop="platformLink">
                <el-input v-model="drawerForm.platformLink" placeholder="请输入平台链接" maxlength="500" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section">
          <div class="section-title">项目情况</div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="金额" prop="amount">
                <el-input v-model="drawerForm.amount" placeholder="请输入金额" maxlength="15">
                  <template #append>万</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="报名费" prop="entryFee">
                <el-input v-model="drawerForm.entryFee" placeholder="请输入报名费" maxlength="15" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="投标保证金" prop="bidBond">
                <el-input v-model="drawerForm.bidBond" placeholder="请输入投标保证金" maxlength="15" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="赢单率" prop="winningRate">
                <el-input v-model="drawerForm.winningRate" placeholder="请输入赢单率" maxlength="6">
                  <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="drawerForm.signUpDeadline" type="date" value-format="YYYY-MM-DD" style="width:100%" placeholder="请选择" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="投标截止时间" prop="tenderDeadline">
                <el-date-picker v-model="drawerForm.tenderDeadline" type="date" value-format="YYYY-MM-DD" style="width:100%" placeholder="请选择" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="服务期" prop="standardPeriod">
                <el-input v-model="drawerForm.standardPeriod" placeholder="请输入服务期" maxlength="50">
                  <template #append>年</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="服务时间段" prop="serviceTime">
                <el-input v-model="drawerForm.serviceTime" placeholder="请输入服务时间段" maxlength="100" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="入围类型" prop="shortlistedType">
                <el-select v-model="drawerForm.shortlistedType" style="width:100%" placeholder="请选择">
                  <el-option v-for="item in options.shortlisted" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="物资类目" prop="profession">
                <el-select v-model="drawerForm.profession" style="width:100%" placeholder="请选择">
                  <el-option v-for="item in options.material" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="招标代理机构" prop="biddingAgency">
                <el-input v-model="drawerForm.biddingAgency" placeholder="请输入代理机构" maxlength="100" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="代理机构联系方式" prop="agencyContact">
                <el-input v-model="drawerForm.agencyContact" placeholder="请输入联系方式" maxlength="50" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="标期类型" prop="bidPeriodType">
                <el-radio-group v-model="drawerForm.bidPeriodType">
                  <el-radio :value="1">单项目入围</el-radio>
                  <el-radio :value="2">周期性框架</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <template v-if="drawerForm.bidPeriodType === 2">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="预计下次投标时间" prop="nextBiddingTime">
                  <el-date-picker v-model="drawerForm.nextBiddingTime" type="date" value-format="YYYY-MM-DD" style="width:100%" placeholder="请选择" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="提前提醒天数" prop="noticeAdvanceDays">
                  <el-input v-model="drawerForm.noticeAdvanceDays" placeholder="请输入提醒天数" maxlength="5" />
                </el-form-item>
              </el-col>
            </el-row>
          </template>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="入围要求" prop="shortlistedRequirement">
                <el-input v-model="drawerForm.shortlistedRequirement" type="textarea" :rows="3" placeholder="请输入入围要求" maxlength="500" show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="项目描述" prop="projectDesc">
                <el-input v-model="drawerForm.projectDesc" type="textarea" :rows="3" placeholder="请输入项目描述" maxlength="500" show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section">
          <div class="section-header">
            <div class="section-title">附件</div>
            <el-upload
              :action="uploadFileUrl"
              :headers="uploadHeaders"
              :on-success="handleUploadSuccess"
              :show-file-list="false"
              :before-upload="handleBeforeUpload"
            >
              <el-button type="primary" link><el-icon><Upload /></el-icon> 上传附件</el-button>
            </el-upload>
          </div>
          <el-table :data="drawerForm.fileList" border class="custom-table">
            <el-table-column label="文件名称" prop="fileName" align="center" show-overflow-tooltip />
            <el-table-column label="文件类型" width="100" align="center">
              <template #default="scope">
                <el-tag size="small" type="info">{{ scope.row.fileName ? scope.row.fileName.split('.').pop().toUpperCase() : '' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="上传时间" prop="createTime" width="180" align="center" />
            <el-table-column label="操作" width="120" align="center">
              <template #default="scope">
                <el-button link type="danger" @click="handleFileDelete(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </div>
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">保存</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, getCurrentInstance } from 'vue';
import { addPlatformSelection } from '@/api/saleManage/platformSelection/index';
import { listCustomerInfo } from "@/api/customer/customerInfo/index";
import { getToken } from "@/utils/auth";
import { Upload } from '@element-plus/icons-vue';

const proxy = getCurrentInstance().proxy;

const props = defineProps({
  modelValue: Boolean,
  options: { type: Object, default: () => ({}) }
});

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

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
});

const submitting = ref(false);
const customerLoading = ref(false);
const customerOptions = ref([]);

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

const remoteSearchCustomer = 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;
  }
};

// 每次打开抽屉时刷新客户列表
watch(() => props.modelValue, (val) => {
  if (val) {
    remoteSearchCustomer('');
  }
});

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

const drawerFormRef = ref(null);
const drawerForm = ref({
  projectStatus: 1,
  bidPeriodType: 1,
  productSupport: undefined,
  fileList: [],
  memberList: []
});

const uploadHeaders = { Authorization: "Bearer " + getToken() };
const uploadFileUrl = import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload';

const drawerRules = {
  companyNo: [{ required: true, message: '请选择归属公司', trigger: 'change' }],
  customName: [{ required: true, message: '请选择客户名称', trigger: 'change' }],
  projectLevel: [{ required: true, message: '请选择项目级别', trigger: 'change' }],
  businessType: [{ required: true, message: '请选择项目类型', trigger: 'change' }],
  projectName: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { max: 200, message: '项目名称不能超过200个字符', trigger: 'blur' }
  ],
  platformName: [
    { max: 200, message: '平台名称不能超过200个字符', trigger: 'blur' }
  ],
  platformLink: [
    { max: 500, message: '平台链接不能超过500个字符', trigger: 'blur' },
    { pattern: /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([\/\w .-]*)*\/?$/, message: '请输入正确的平台链接地址', trigger: 'blur' }
  ],
  amount: [
    { required: true, message: '请输入金额', trigger: 'blur' },
    { pattern: /^\d+(\.\d+)?$/, message: '请输入正确的金额数字', trigger: 'blur' }
  ],
  entryFee: [
    { pattern: /^\d+(\.\d+)?$/, message: '请输入正确的报名费', trigger: 'blur' }
  ],
  bidBond: [
    { pattern: /^\d+(\.\d+)?$/, message: '请输入正确的投标保证金', trigger: 'blur' }
  ],
  winningRate: [
    { required: true, message: '请输入赢单率', trigger: 'blur' },
    { pattern: /^(100|[1-9]?\d(\.\d+)?)$/, message: '请输入正确的赢单率(0-100)', 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' }
  ],
  serviceTime: [
    { max: 100, message: '服务时间段不能超过100个字符', trigger: 'blur' }
  ],
  biddingAgency: [
    { max: 100, message: '招标代理机构不能超过100个字符', trigger: 'blur' }
  ],
  agencyContact: [
    { max: 50, message: '代理机构联系方式不能超过50个字符', trigger: 'blur' },
    { pattern: /^(1[3-9]\d{9}|[0-9-]{7,20})$/, message: '请输入正确的联系电话(手机或固话)', trigger: 'blur' }
  ],
  shortlistedType: [{ required: true, message: '请选择入围类型', trigger: 'change' }],
  profession: [{ required: true, message: '请选择物资类目', trigger: 'change' }],
  bidPeriodType: [{ required: true, message: '请选择标期类型', trigger: 'change' }],
  shortlistedRequirement: [
    { required: true, message: '请输入入围要求', trigger: 'blur' },
    { max: 500, message: '入围要求不能超过500个字符', trigger: 'blur' }
  ],
  projectDesc: [
    { required: true, message: '请输入项目描述', trigger: 'blur' },
    { max: 500, message: '项目描述不能超过500个字符', trigger: 'blur' }
  ],
  nextBiddingTime: [{ required: true, message: '请选择预计下次投标时间', trigger: 'change' }],
  noticeAdvanceDays: [
    { required: true, message: '请输入提前提醒天数', trigger: 'blur' },
    { pattern: /^[1-9]\d*$/, message: '请输入大于0的整数', trigger: 'blur' }
  ]
};

const handleSubmit = async () => {
  if (!drawerFormRef.value) return;
  await drawerFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        const leaderUser = props.options.user.find(u => String(u.userId || u.staffId) === String(drawerForm.value.leader));
        const postData = {
          ...drawerForm.value,
          leaderName: leaderUser ? (leaderUser.nickName || leaderUser.staffName) : '',
          condition: drawerForm.value.shortlistedRequirement,
          requirement: drawerForm.value.shortlistedRequirement,
          fileNo: drawerForm.value.fileList.map(f => f.ossId).filter(Boolean).join(','),
          finalizationType: drawerForm.value.shortlistedType // 双向映射，兼容后端字段不统一
        };
        await addPlatformSelection(postData);
        proxy.$modal.msgSuccess("新增成功");
        emit('success');
        visible.value = false;
      } finally {
        submitting.value = false;
      }
    }
  });
};

const handleUploadSuccess = (res, file) => {
  if (res.code === 200) {
    const item = res.data;
    drawerForm.value.fileList.push({
      fileName: item.originalName || item.fileName || file.name,
      fileUrl: item.url || item.fileName || item.ossId,
      ossId: item.ossId,
      createTime: new Date().toISOString()
    });
    proxy.$modal.msgSuccess("上传成功");
  } else {
    proxy.$modal.msgError(res.msg || "上传失败");
  }
};

const handleBeforeUpload = (file) => {
  if (file.size > 100 * 1024 * 1024) {
    proxy.$modal.msgError("文件大小不能超过 100MB");
    return false;
  }
  return true;
};

const handleFileDelete = (index) => { drawerForm.value.fileList.splice(index, 1); };
</script>

<style scoped lang="scss">
.edit-form-container {
  padding: 0 20px;
  background-color: #fff;
  .form-section {
    margin-bottom: 15px;
    padding: 0;
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      padding: 0 15px;
      background-color: #f8fbff;
      border-radius: 4px;
      .section-title {
        margin-bottom: 0;
        padding: 8px 0;
        background: transparent;
        border-bottom: none;
      }
    }
    .section-title {
      font-size: 14px;
      font-weight: normal !important;
      margin-bottom: 12px;
      padding: 8px 15px;
      color: #409eff;
      background-color: #f8fbff;
      border-radius: 4px;
    }
  }
}
.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  background: #fff;
  border-top: 1px solid #e5e6eb;
}

:deep(.el-form-item__label) {
  color: #4e5969;
  font-weight: normal !important;
  white-space: nowrap !important;
}

:deep(.el-input-group__append) {
  background-color: #f2f3f5;
  color: #4e5969;
  padding: 0 12px;
}

:deep(.el-drawer__header) {
  margin-bottom: 0 !important;
  padding: 16px 24px !important;
  border-bottom: 1px solid #e5e6eb !important;
  span {
    font-weight: normal !important;
    color: #333;
    font-size: 16px;
  }
}

:deep(.el-table), :deep(.el-table th), :deep(.el-table td), :deep(.el-table__cell) {
  font-weight: normal !important;
}
</style>
