<template>
  <el-drawer
    v-model="visible"
    title="新增年度入围项目"
    direction="rtl"
    size="80%"
    :close-on-click-modal="false"
    class="custom-edit-drawer"
  >
        <div class="drawer-body">
        <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-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入项目名称" maxlength="200" show-word-limit />
            </el-form-item>
            <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 companyOptions" :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="customName">
                  <el-select 
                    v-model="form.customNo" 
                    placeholder="搜索客户" 
                    style="width: 100%" 
                    filterable 
                    clearable
                    @change="handleCustomerChange"
                  >
                    <el-option 
                      v-for="item in customerOptions" 
                      :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 userOptions" :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>
                      <el-option v-for="item in userOptions" :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>
          </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 || item.value" :label="item.industryCategoryName || item.label" :value="String(item.id || item.value)" />
                  </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="200" show-word-limit />
            </el-form-item>
            <el-form-item label="项目描述" prop="projectDesc">
              <el-input v-model="form.projectDesc" type="textarea" :rows="3" placeholder="请输入项目描述" maxlength="200" 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="文件类型" prop="type" width="120" align="center" />
              <el-table-column label="上传时间" prop="uploadTime" width="180" align="center" />
              <el-table-column label="操作" width="140" align="center">
                 <template #default="scope">
                   <el-button link type="primary" @click="handleDownload(scope.row)" style="margin-right: 10px;">下载</el-button>
                   <el-button link type="danger" @click="handleDeleteFile(scope.$index)">删除</el-button>
                 </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
      </div>
      <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, getCurrentInstance, onMounted } from 'vue';
import { addProjectSelection } from '@/api/saleManage/projectSelection/index';
import { listCustomerInfo } from "@/api/customer/customerInfo/index";
import { globalHeaders } from '@/utils/request';
import { Upload } from '@element-plus/icons-vue';

const props = defineProps({
  modelValue: Boolean,
  companyOptions: Array,
  userOptions: Array,
  projectLevelOptions: Array,
  projectTypeOptions: Array,
  shortlistedTypeOptions: Array,
  professionOptions: Array,
  industryOptions: Array
});

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

const visible = 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({
  bidPeriodType: 1,
  projectStatus: '0',
  finalizationType: 2,
  customName: undefined,
  customNo: undefined,
  winningRate: undefined,
  signUpDeadline: undefined,
  leader: undefined,
  leaderName: undefined,
  productSupport: undefined,
  serviceTime: undefined
});

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' }]
});

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

const reset = () => {
  Object.assign(form, {
    id: undefined,
    companyNo: undefined,
    customName: undefined,
    customNo: undefined,
    businessType: undefined,
    projectLevel: undefined,
    leader: undefined,
    productSupport: undefined,
    projectName: undefined,
    amount: undefined,
    entryFee: undefined,
    bidBond: undefined,
    winningRate: undefined,
    signUpDeadline: undefined,
    tenderDeadline: undefined,
    standardPeriod: undefined,
    serviceTime: undefined,
    serviceStartTime: undefined,
    serviceEndTime: undefined,
    shortlistedType: undefined,
    profession: undefined,
    biddingAgency: undefined,
    agencyContact: undefined,
    bidPeriodType: 1,
    biddingLink: undefined,
    condition: undefined,
    projectDesc: undefined,
    fileNo: '',
    projectStatus: '0'
  });
  fileList.value = [];
  customerOptions.value = [];
  if (formRef.value) formRef.value.resetFields();
};

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 = customerOptions.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);
  } else {
    form.customName = undefined;
    form.customNo = undefined;
  }
};

const resetQuery = () => {}; // 占位符或不需要

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

const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    fileList.value.push({ 
      name: res.data.fileName, 
      url: res.data.url, 
      ossId: res.data.ossId,
      type: res.data.fileName.split('.').pop().toUpperCase(),
      uploadTime: proxy.parseTime(new Date())
    });
    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 handleDownload = (row) => {
  if (row.ossId) {
    proxy.$download.oss(row.ossId);
  } else if (row.url) {
    window.open(row.url, '_blank');
  } else {
    proxy.$modal.msgError("下载地址不存在");
  }
};

const submitForm = () => {
  formRef.value.validate(valid => {
    if (valid) {
      // 字段冗余备份，解决后端接收字段名不一致的问题
      if (form.winRate) form.winningRate = form.winRate;
      if (form.winningRate) form.winRate = form.winningRate;
      if (form.registrationDeadline) form.signUpDeadline = form.registrationDeadline;
      if (form.signUpDeadline) form.registrationDeadline = form.signUpDeadline;
      
      submitting.value = true;
      addProjectSelection(form).then(() => {
        proxy.$modal.msgSuccess("新增成功");
        visible.value = false;
        emit('success');
      }).finally(() => { submitting.value = false; });
    }
  });
};
</script>

<style scoped lang="scss">
.selection-drawer {
  :deep(.el-drawer__body) { padding: 0 !important; background-color: #fff; }
}
.drawer-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.drawer-header-custom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 24px;
  border-bottom: 1px solid #f0f2f5;
  background-color: #fff;
  .header-title {
    .main-title {
      font-size: 16px;
      font-weight: normal;
      color: #333;
    }
  }
  .close-btn {
    cursor: pointer;
    font-size: 18px;
    color: #909399;
    transition: color 0.3s;
    &:hover {
      color: #409eff;
    }
  }
}
.drawer-body {
  flex: 1;
  padding: 15px 25px;
  overflow-y: auto;
  // 隐藏滚动条
  &::-webkit-scrollbar { display: none; }
  scrollbar-width: none;
  -ms-overflow-style: none;
}
.selection-form {
  :deep(.el-form-item__label) {
    font-weight: normal !important;
    color: #666;
  }
}
.section-block {
  margin-bottom: 25px;
  .section-title {
    padding: 8px 15px;
    background-color: #f8fbff;
    color: #409eff;
    font-size: 14px;
    margin-bottom: 15px;
    &.attachment-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 4px 15px;
    }
  }
}
.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;
  }
}
: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;
  }
}
</style>
