<template>
  <el-drawer
    title="编辑项目商机"
    v-model="visible"
    direction="rtl"
    size="85%"
    :close-on-click-modal="false"
    class="opp-drawer"
  >
    <template #default>
      <div class="drawer-body" v-loading="loading">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="110px" class="opp-form" label-position="left">
          <!-- 基本信息 -->
          <div class="section-block">
            <div class="section-title">基本信息</div>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="归属公司" prop="companyId">
                  <el-select v-model="form.companyId" 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="12">
                <el-form-item label="客户名称" prop="customerNo">
                  <el-select 
                    v-model="form.customerNo" 
                    placeholder="请输入关键字搜索客户" 
                    style="width: 100%" 
                    clearable 
                    filterable 
                    @change="handleCustomerChange"
                  >
                    <el-option v-for="item in computedCustomerOptions" :key="item.id || item.customerNo"
                      :label="item.customerName" :value="String(item.id || item.customerNo)" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="项目负责人" prop="managerId">
                  <el-select v-model="form.managerId" 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="12">
                <el-form-item label="项目名称" prop="projectName">
                  <el-input v-model="form.projectName" placeholder="请输入" maxlength="200" show-word-limit />
                </el-form-item>
              </el-col>
            </el-row>
            <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="winRate">
                  <el-input v-model="form.winRate" placeholder="请输入" type="number" maxlength="6">
                    <template #append>%</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="立项时间" prop="setupTime">
                  <el-date-picker v-model="form.setupTime" 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="deadline">
                  <el-date-picker v-model="form.deadline" type="date" value-format="YYYY-MM-DD" placeholder="请选择" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="营销活动" prop="marketingActivity">
                  <el-select v-model="form.marketingActivity" placeholder="请选择" style="width: 100%" clearable filterable>
                    <el-option v-for="item in marketingActivityOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </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="projectLevel">
                  <el-select v-model="form.projectLevel" placeholder="请选择" style="width: 100%" clearable filterable>
                    <el-option v-for="item in projectLevelOptions" :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="projectArea">
                  <el-input v-model="form.projectArea" placeholder="请输入" maxlength="100" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="采购方式" prop="purchaseMethod">
                  <el-select v-model="form.purchaseMethod" placeholder="请选择" style="width: 100%" clearable filterable>
                    <el-option v-for="item in procurementMethodOptions" :key="item.value"
                      :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="商机来源" prop="source">
                  <el-select v-model="form.source" placeholder="请选择" style="width: 100%" clearable filterable>
                    <el-option v-for="item in infoSourceOptions" :key="item.value"
                      :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="项目描述" prop="description">
              <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入项目描述" maxlength="500" show-word-limit />
            </el-form-item>
            <el-form-item label="竞争对手" prop="competitor">
              <el-input v-model="form.competitor" 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 stripe class="file-table">
              <el-table-column label="文件名称" prop="name" show-overflow-tooltip>
                <template #default="scope">
                  <el-link type="primary" :underline="false" @click="downloadFile(scope.row)" class="file-link">
                    <el-icon style="margin-right: 4px;"><Document /></el-icon>
                    {{ scope.row.name }}
                  </el-link>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" align="center">
                 <template #default="scope">
                   <el-button link type="primary" @click="downloadFile(scope.row)">下载</el-button>
                   <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 { useDebounceFn } from '@vueuse/core';
import { getOpportunity, updateOpportunity } from '@/api/saleManage/opportunity/index';
import { listCustomerInfo } from "@/api/customer/customerInfo/index";
import { listByIds } from '@/api/system/oss/index';
import { globalHeaders } from '@/utils/request';
import { Close, Upload, Document } from '@element-plus/icons-vue';

const props = defineProps({
  modelValue: Boolean,
  id: [String, Number],
  companyOptions: Array,
  customerOptions: Array,
  userOptions: Array,
  projectLevelOptions: Array,
  procurementMethodOptions: Array,
  infoSourceOptions: Array,
  marketingActivityOptions: Array
});

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

const visible = ref(false);
const loading = ref(false);
const submitting = ref(false);
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 customerLoading = ref(false);
const localCustomerOptions = ref([]);

const remoteLoadCustomers = useDebounceFn((query) => {
  customerLoading.value = true;
  listCustomerInfo({ pageNum: 1, pageSize: 500, isHighSeas: 'all' }).then(res => {
    const list = res.rows || [];
    localCustomerOptions.value = list.map(i => ({ ...i, id: String(i.id || i.customerNo) }));
  }).finally(() => {
    customerLoading.value = false;
  });
}, 300);

const rules = reactive({
  companyId: [{ required: true, message: '归属公司不能为空', trigger: 'change' }],
  customerNo: [{ required: true, message: '客户名称不能为空', trigger: 'change' }],
  managerId: [{ required: true, message: '项目负责人不能为空', trigger: 'change' }],
  projectName: [
    { required: true, message: '项目名称不能为空', trigger: 'blur' },
    { max: 200, message: '项目名称不能超过200个字符', trigger: 'blur' }
  ],
  amount: [
    { required: true, message: '金额不能为空', trigger: 'blur' }
  ],
  winRate: [
    { required: true, message: '赢单率不能为空', trigger: 'blur' },
    { pattern: /^(100|[1-9]?\d(\.\d+)?)$/, message: '请输入正确的赢单率(0-100)', trigger: 'blur' }
  ],
  setupTime: [{ required: true, message: '立项时间不能为空', trigger: 'change' }],
  projectArea: [
    { max: 100, message: '项目区域不能超过100个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '项目描述不能为空', trigger: 'blur' },
    { max: 500, message: '项目描述不能超过500个字符', trigger: 'blur' }
  ],
  competitor: [
    { max: 500, message: '竞争对手不能超过500个字符', trigger: 'blur' }
  ]
});

// 【增强回显】通过计算属性确保当前项在选项列表中，防止分页或数据不全导致回显显示为 ID
const computedCustomerOptions = computed(() => {
  const options = [...localCustomerOptions.value];
  if (form.customerNo && form.customerName) {
    const exists = options.some(i => String(i.id || i.customerNo) === String(form.customerNo));
    if (!exists) options.unshift({ id: form.customerNo, customerNo: form.customerNo, customerName: form.customerName });
  }
  return options;
});

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

const computedCompanyOptions = computed(() => {
  const options = [...(props.companyOptions || [])];
  if (form.companyId && form.companyName) {
    const exists = options.some(i => String(i.companyCode || i.id) === String(form.companyId));
    if (!exists) options.unshift({ companyCode: form.companyId, companyName: form.companyName });
  }
  return options;
});

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

const loadDetail = (id) => {
  loading.value = true;
  getOpportunity(id).then(res => {
    const data = res.data || res;
    Object.assign(form, data);
    
    // 映射与强制转字符串以适配下拉回显
    form.companyId = data.companyNo ? String(data.companyNo) : '';
    form.customerNo = data.customerNo ? String(data.customerNo) : '';
    form.managerId = data.leader ? String(data.leader) : '';
    form.amount = data.projectBudget;
    form.setupTime = data.approvalDate;
    form.deadline = data.expectedCompletionTime;
    form.marketingActivity = data.activityNo ? String(data.activityNo) : '';
    form.projectLevel = data.projectLevel ? String(data.projectLevel) : '';
    form.purchaseMethod = data.procurementMethod ? String(data.procurementMethod) : '';
    form.source = data.infoSource ? String(data.infoSource) : '';
    form.description = data.projectDescription;

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

const handleCustomerChange = (val) => {
  const customer = computedCustomerOptions.value.find(c => String(c.id || c.customerNo) === val);
  if (customer) {
    form.customerName = customer.customerName;
    form.profession = customer.industryCategoryId;
  }
};

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

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

const downloadFile = (row) => {
  if (row.url) {
    proxy.$modal.msgInfo("正在启动下载...");
    if (proxy.$download && proxy.$download.resource) {
      proxy.$download.resource(row.url);
    } else {
      window.open(row.url, '_blank');
    }
  }
};

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;
      const data = {
        id: form.id,
        projectName: form.projectName,
        projectBudget: Number(form.amount),
        winRate: Number(form.winRate),
        approvalDate: form.setupTime,
        expectedCompletionTime: form.deadline,
        companyNo: form.companyId,
        leader: form.managerId,
        leaderName: form.leaderName,
        activityNo: form.marketingActivity,
        procurementMethod: form.purchaseMethod,
        infoSource: form.source,
        projectDescription: form.description,
        competitor: form.competitor,
        customerNo: form.customerNo,
        customerName: form.customerName,
        fileNo: form.fileNo,
        projectLevel: form.projectLevel,
        projectArea: form.projectArea,
        profession: form.profession,
        izClue: form.izClue || 0,
        projectType: form.projectType || '销售商机',
        status: form.status || '0'
      };
      updateOpportunity(data).then(() => {
        proxy.$modal.msgSuccess("修改成功");
        visible.value = false;
        emit('success');
      }).finally(() => { submitting.value = false; });
    }
  });
};
</script>

<style scoped lang="scss">
.opp-drawer {
  :deep(.el-drawer__header) {
    margin: 0;
    padding: 0 20px;
    height: 48px;
    line-height: 48px;
    border-bottom: 1px solid #f0f0f0;
    span {
      font-size: 16px;
      font-weight: normal;
      color: #333;
    }
  }
  :deep(.el-drawer__body) { padding: 0 !important; background-color: #fff; }
}

.drawer-body {
  padding: 0;
  height: 100%;
  overflow-y: auto;
}

.opp-form {
  padding: 15px 24px;
  :deep(.el-form-item__label) {
    font-weight: normal !important;
    color: #666;
  }
}

.section-block {
  margin-bottom: 24px;
  .section-title {
    padding: 8px 15px;
    background-color: #f8fbff;
    color: #409eff;
    font-size: 14px;
    margin-bottom: 15px;
    border-bottom: none;
    &.attachment-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 4px;
      padding-bottom: 4px;
    }
  }
}

.file-table {
  :deep(th.el-table__cell) {
    background-color: #f8fafc !important;
    color: #475569;
    font-weight: 500;
  }
  .file-link {
    font-weight: normal;
    font-size: 13px;
  }
}

.drawer-footer {
  padding: 12px 24px;
  border-top: 1px solid #f0f2f5;
  text-align: right;
  background-color: #fff;
  .el-button { font-weight: normal !important; padding: 8px 20px; }
}
</style>
