<template>
  <el-drawer
    v-model="visible"
    title="新增销售线索"
    size="80%"
    class="leads-drawer"
    :with-header="false"
  >
    <template #default>
      <div class="drawer-container">
        <div class="drawer-header-custom">
          <div class="header-title">
            <span class="main-title">销售线索</span>
            <span class="sub-title">(3个月以上出结果或金额不明确的项目信息，计入：销售线索)</span>
          </div>
          <el-icon class="close-btn" @click="visible = false"><Close /></el-icon>
        </div>
        <div class="drawer-content">
          <el-form :model="form" :rules="rules" ref="formRef" label-width="110px" label-position="left">

        <!-- 基本信息 -->
        <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 companyOptions"
                    :key="item.companyCode"
                    :label="item.companyName"
                    :value="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="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 userOptions"
                    :key="item.staffId"
                    :label="(item.staffCode ? '(' + item.staffCode + ') ' : '') + item.staffName"
                    :value="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" placeholder="请选择" 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="productSupport">
                <el-select v-model="form.productSupport" placeholder="请选择" filterable style="width: 100%" clearable @change="handleProductSupportChange">
                  <el-option
                    v-for="item in userOptions"
                    :key="item.staffId"
                    :label="(item.staffCode ? '(' + item.staffCode + ') ' : '') + item.staffName"
                    :value="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" 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-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="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>
  </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, getCurrentInstance } from 'vue';
import { addLeads } from '@/api/saleManage/leads/index';
import { listCustomerInfo } from "@/api/customer/customerInfo/index";
import { globalHeaders } from '@/utils/request';
import { Close, Upload } from '@element-plus/icons-vue';

const props = defineProps({
  modelValue: Boolean,
  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 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({
  izClue: 1,
  status: '1',
  fileNo: '',
  productSupport: undefined,
  productSupportName: undefined
});

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' }
  ],
  projectBudget: [{ required: true, message: '金额不能为空', trigger: 'blur' }],
  winRate: [
    { required: true, message: '赢单率不能为空', trigger: 'blur' },
    { pattern: /^(100|[1-9]?\d(\.\d+)?)$/, message: '请输入正确的赢单率(0-100)', trigger: 'blur' }
  ],
  expectedCompletionTime: [{ required: true, message: '成单时间不能为空', trigger: 'change' }],
  projectLevel: [{ required: true, message: '项目级别不能为空', trigger: 'change' }],
  projectArea: [
    { required: true, message: '项目区域不能为空', trigger: 'blur' },
    { max: 100, message: '项目区域不能超过100个字符', trigger: 'blur' }
  ],
  procurementMethod: [{ required: true, message: '采购方式不能为空', trigger: 'change' }],
  infoSource: [{ required: true, message: '信息来源不能为空', trigger: 'change' }],
  purchaseContent: [
    { required: true, message: '采购内容不能为空', trigger: 'blur' },
    { max: 500, message: '采购内容不能超过500个字符', trigger: 'blur' }
  ],
  projectDescription: [
    { required: true, message: '项目描述不能为空', trigger: 'blur' },
    { max: 500, message: '项目描述不能超过500个字符', trigger: 'blur' }
  ],
  competitor: [
    { max: 500, message: '竞争对手不能超过500个字符', trigger: 'blur' }
  ]
});

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) }));
  }).finally(() => {
    customerLoading.value = false;
  });
};

watch(() => props.modelValue, (val) => { 
  visible.value = val; 
  if (val) {
    reset();
    remoteLoadCustomers(''); // 默认加载前20条
  }
});
watch(() => visible.value, (val) => { emit('update:modelValue', val); });

const reset = () => {
  Object.assign(form, {
    id: undefined,
    izClue: 1,
    companyNo: undefined,
    customerNo: undefined,
    customerName: undefined,
    leader: undefined,
    leaderName: undefined,
    projectName: undefined,
    projectBudget: undefined,
    winRate: undefined,
    approvalDate: undefined,
    expectedCompletionTime: undefined,
    projectLevel: undefined,
    projectArea: undefined,
    procurementMethod: undefined,
    infoSource: undefined,
    purchaseContent: undefined,
    projectDescription: undefined,
    competitor: undefined,
    status: '1',
    fileNo: '',
    activityNo: undefined,
    profession: undefined,
    productSupport: undefined,
    productSupportName: undefined
  });
  fileList.value = [];
  if (formRef.value) formRef.value.resetFields();
};

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 || '');
    // 行业跟随客户变化 (对应客户信息的 industry_category_id)
    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 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;
      addLeads(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-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;
    }
    .sub-title {
      font-size: 12px;
      color: #999;
      margin-left: 8px;
    }
  }
  .close-btn {
    cursor: pointer;
    font-size: 18px;
    color: #909399;
    transition: color 0.3s;
    &:hover {
      color: #409eff;
    }
  }
}
.form-section {
  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-top: 4px;
      padding-bottom: 4px;
    }
  }
}
.attachment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.drawer-footer {
  padding: 15px 25px;
  border-top: 1px solid #f0f0f0;
  background: #fff;
  text-align: right;
  .el-button {
    font-weight: normal;
  }
}
.at-table {
  :deep(th.el-table__cell) {
    font-weight: normal;
    color: #333;
  }
}
</style>
