<template>
  <el-drawer
    v-model="visible"
    title="修改销售线索"
    size="80%"
    class="leads-drawer"
    :with-header="false"
  >
    <div class="drawer-content" v-loading="loading">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="110px" label-position="left">
        <div class="drawer-header">
          <div class="header-title">
            <span class="main-title">编辑销售线索</span>
          </div>
          <el-button link icon="Close" @click="visible = false" class="close-btn"></el-button>
        </div>

        <div class="form-section">
          <div class="section-title"><span>基本信息</span></div>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="归属公司" prop="companyNo">
                <el-select v-model="form.companyNo" placeholder="请选择" filterable style="width: 100%" clearable>
                  <el-option v-for="item in computedCompanyOptions" :key="item.companyCode" :label="item.companyName" :value="String(item.companyCode)" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户名称" prop="customerNo">
                <el-select 
                  v-model="form.customerNo" 
                  placeholder="请输入关键字检索" 
                  filterable 
                  style="width: 100%" 
                  @change="handleCustomerChange"
                >
                  <el-option v-for="item in localCustomerOptions" :key="item.customerNo" :label="item.customerName" :value="String(item.customerNo)" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="项目负责人" prop="leader">
                <el-select v-model="form.leader" placeholder="请选择" filterable style="width: 100%" @change="handleLeaderChange">
                  <el-option v-for="item in computedUserOptions" :key="item.staffId" :label="(item.staffCode ? '(' + item.staffCode + ') ' : '') + item.staffName" :value="String(item.staffId)" />
                </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="30">
            <el-col :span="12">
              <el-form-item label="金额(万)" prop="projectBudget">
                <el-input-number 
                  v-model="form.projectBudget" 
                  :precision="2" 
                  :step="1" 
                  :min="0" 
                  placeholder="请输入金额" 
                  controls-position="right" 
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <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-row>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="立项时间" prop="approvalDate">
                <el-date-picker v-model="form.approvalDate" type="date" placeholder="请选择" value-format="YYYY-MM-DD" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="成单时间" prop="expectedCompletionTime">
                <el-date-picker v-model="form.expectedCompletionTime" type="date" value-format="YYYY-MM-DD" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="营销活动" prop="activityNo">
                <el-select v-model="form.activityNo" 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-col :span="12">
              <el-form-item label="行业" prop="profession">
                <el-select v-model="form.profession" placeholder="请选择" style="width: 100%" clearable filterable>
                  <el-option v-for="item in industryOptions" :key="item.id" :label="item.industryCategoryName" :value="String(item.id)" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="产品支持" prop="productSupport">
                <el-select v-model="form.productSupport" placeholder="请选择" filterable style="width: 100%" clearable @change="handleProductSupportChange">
                  <el-option v-for="item in computedProductSupportOptions" :key="item.staffId" :label="(item.staffCode ? '(' + item.staffCode + ') ' : '') + item.staffName" :value="String(item.staffId)" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section">
          <div class="section-title"><span>项目信息</span></div>
          <el-row :gutter="30">
            <el-col :span="12">
              <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="12">
              <el-form-item label="项目区域" prop="projectArea">
                <el-input v-model="form.projectArea" placeholder="请输入" maxlength="100" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="采购方式" prop="procurementMethod">
                <el-select v-model="form.procurementMethod" 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-col :span="12">
              <el-form-item label="信息来源" prop="infoSource">
                <el-select v-model="form.infoSource" 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-row :gutter="30">
            <el-col :span="24">
              <el-form-item label="采购内容" prop="purchaseContent">
                <el-input v-model="form.purchaseContent" type="textarea" :rows="3" maxlength="500" show-word-limit placeholder="请输入采购内容" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="24">
              <el-form-item label="项目描述" prop="projectDescription">
                <el-input v-model="form.projectDescription" type="textarea" :rows="3" maxlength="500" show-word-limit placeholder="请输入项目描述" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="24">
              <el-form-item label="竞争对手" prop="competitor">
                <el-input v-model="form.competitor" type="textarea" :rows="3" maxlength="500" show-word-limit placeholder="请输入竞争对手" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section">
          <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="at-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)">下载</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, computed, getCurrentInstance } from 'vue';
import { getLeads, updateLeads } from '@/api/saleManage/leads/index';
import { listCustomerInfo } from "@/api/customer/customerInfo/index";
import { listByIds } from '@/api/system/oss/index';
import { globalHeaders } from '@/utils/request';
import { Close, Upload } 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,
  industryOptions: 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 customerLoading = ref(false);
const localCustomerOptions = ref([]);

const form = reactive({});

// 【增强回显】处理远程加载时的回显问题
watch(() => [form.customerNo, form.customerName], ([no, name]) => {
  if (no && name) {
    const exists = localCustomerOptions.value.some(i => String(i.customerNo) === String(no));
    if (!exists) {
      localCustomerOptions.value.unshift({ customerNo: String(no), customerName: name });
    }
  }
}, { immediate: true });

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

const computedUserOptions = computed(() => {
  const options = [...(props.userOptions || [])];
  if (form.leader && form.leaderName) {
    const exists = options.some(i => String(i.staffId) === 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) === String(form.productSupport));
    if (!exists) options.unshift({ staffId: form.productSupport, staffName: form.productSupportName });
  }
  return options;
});

const computedCompanyOptions = computed(() => {
  const options = [...(props.companyOptions || [])];
  if (form.companyNo && form.companyName) {
    const exists = options.some(i => String(i.companyCode) === String(form.companyNo));
    if (!exists) options.unshift({ companyCode: form.companyNo, companyName: form.companyName });
  }
  return options;
});
const rules = reactive({
  companyNo: [{ required: true, message: '必填', trigger: 'change' }],
  customerNo: [{ required: true, message: '必填', trigger: 'change' }],
  leader: [{ required: true, message: '必填', trigger: 'change' }],
  projectName: [
    { required: true, message: '必填', trigger: 'blur' },
    { max: 200, message: '项目名称不能超过200个字符', trigger: 'blur' }
  ],
  winRate: [
    { pattern: /^(100|[1-9]?\d(\.\d+)?)$/, message: '请输入正确的赢单率(0-100)', trigger: 'blur' }
  ],
  projectArea: [
    { max: 100, message: '项目区域不能超过100个字符', trigger: 'blur' }
  ],
  purchaseContent: [
    { max: 500, message: '采购内容不能超过500个字符', trigger: 'blur' }
  ],
  projectDescription: [
    { max: 500, message: '项目描述不能超过500个字符', trigger: 'blur' }
  ],
  competitor: [
    { max: 500, message: '竞争对手不能超过500个字符', trigger: 'blur' }
  ]
});

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;
  getLeads(id).then(res => {
    const data = res.data || res;
    Object.assign(form, data);
    
    // 兼容后端不同字段名映射
    if (!form.companyNo && data.companyId) form.companyNo = data.companyId;
    if (!form.customerNo && data.customerNo) form.customerNo = data.customerNo; 
    if (!form.customerNo && data.customerId) form.customerNo = data.customerId;
    if (!form.leader && data.leaderId) form.leader = data.leaderId;
    if (!form.leader && data.userId) form.leader = data.userId;
    
    // 【关键修复】强制转为字符串，确保与 el-select 的 options 匹配
    if (form.companyNo !== undefined && form.companyNo !== null) form.companyNo = String(form.companyNo);
    if (form.customerNo !== undefined && form.customerNo !== null) form.customerNo = String(form.customerNo);
    if (form.leader !== undefined && form.leader !== null) form.leader = String(form.leader);
    if (form.productSupport !== undefined && form.productSupport !== null) form.productSupport = String(form.productSupport);
    if (form.projectLevel !== undefined && form.projectLevel !== null) form.projectLevel = String(form.projectLevel);
    if (form.procurementMethod !== undefined && form.procurementMethod !== null) form.procurementMethod = String(form.procurementMethod);
    if (form.activityNo !== undefined && form.activityNo !== null) form.activityNo = String(form.activityNo);
    if (form.infoSource !== undefined && form.infoSource !== null) form.infoSource = String(form.infoSource);
    if (form.profession !== undefined && form.profession !== null) form.profession = String(form.profession);

    if (form.fileNo) {
      listByIds(form.fileNo).then(ossRes => {
        fileList.value = ossRes.data.map(i => ({ 
          name: i.originalName, 
          url: i.url, 
          ossId: i.ossId,
          type: i.fileSuffix ? i.fileSuffix.toUpperCase() : (i.originalName.split('.').pop().toUpperCase()),
          uploadTime: i.createTime || ''
        }));
      });
    }
  }).finally(() => { loading.value = false; });
};

const remoteLoadCustomers = (query) => {
  customerLoading.value = true;
  listCustomerInfo({ pageNum: 1, pageSize: 500, isHighSeas: 'all' }).then(res => {
    const list = res.rows || [];
    localCustomerOptions.value = list.map(i => ({ ...i, customerNo: String(i.customerNo) }));
    // 确保当前选中的客户始终在列表中
    if (form.customerNo && form.customerName) {
      const exists = localCustomerOptions.value.some(i => String(i.customerNo) === String(form.customerNo));
      if (!exists) localCustomerOptions.value.unshift({ customerNo: String(form.customerNo), customerName: form.customerName });
    }
  }).finally(() => {
    customerLoading.value = false;
  });
};

const handleCustomerChange = (no) => {
  const customer = localCustomerOptions.value.find(i => String(i.customerNo) === String(no));
  if (customer) { 
    form.customerName = customer.customerName; 
    form.deptNo = String(customer.belongDeptId || ''); 
    // 行业跟随客户变化
    if (customer.industryCategoryId) {
      form.profession = String(customer.industryCategoryId);
    }
  }
};

const handleLeaderChange = (id) => {
  const staff = props.userOptions.find(i => i.staffId === id);
  if (staff) {
    form.leaderName = staff.staffName;
  }
};

const handleProductSupportChange = (id) => {
  const staff = props.userOptions.find(i => i.staffId === id);
  if (staff) {
    form.productSupportName = staff.staffName;
  }
};

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(i => i.ossId).join(',');
  }
};

const handleDownload = (row) => {
  if (row.url) {
    window.open(row.url);
  } else {
    proxy.$modal.msgError("下载地址不存在");
  }
};

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

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

<style scoped lang="scss">
.drawer-content {
  height: calc(100vh - 110px);
  overflow-y: auto;
  padding: 15px 25px;
  // 隐藏滚动条
  &::-webkit-scrollbar { display: none; }
  scrollbar-width: none;
  -ms-overflow-style: none;

  :deep(.el-form-item__label) {
    font-weight: normal;
  }
}
.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  .header-title {
    .main-title {
      font-size: 18px;
      font-weight: normal;
      color: #333;
    }
  }
  .close-btn {
    font-size: 18px;
    color: #999;
  }
}
.form-section {
  margin-bottom: 25px;
  .section-title {
    font-size: 14px;
    font-weight: normal;
    color: #409eff;
    margin-bottom: 15px;
  }
}
.attachment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.drawer-footer {
  padding: 15px 25px;
  border-top: 1px solid #f0f0f0;
  text-align: right;
  .el-button {
    font-weight: normal;
  }
}
.at-table {
  :deep(th.el-table__cell) {
    font-weight: normal;
    color: #333;
  }
}
</style>
