<template>
  <el-drawer
    v-model="visible"
    title="新增销售线索"
    size="80%"
    class="leads-drawer"
    :with-header="false"
  >
    <div class="drawer-content">
      <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>
            <span class="sub-title">(3个月以上出结果或金额不明确的项目信息，计入：销售线索)</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 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.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="请输入" />
              </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">
                   <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-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="请输入" />
              </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="200" 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="200" 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="200" 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 class="drawer-footer">
      <el-button type="primary" @click="submitForm" :loading="submitting">保存</el-button>
      <el-button @click="visible = false">取消</el-button>
    </div>
  </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: ''
});

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' }],
  projectBudget: [{ required: true, message: '金额不能为空', trigger: 'blur' }],
  winRate: [{ required: true, message: '赢单率不能为空', trigger: 'blur' }],
  expectedCompletionTime: [{ required: true, message: '成单时间不能为空', trigger: 'change' }],
  projectLevel: [{ required: true, message: '项目级别不能为空', trigger: 'change' }],
  projectArea: [{ required: true, message: '项目区域不能为空', trigger: 'blur' }],
  procurementMethod: [{ required: true, message: '采购方式不能为空', trigger: 'change' }],
  infoSource: [{ required: true, message: '信息来源不能为空', trigger: 'change' }],
  purchaseContent: [{ required: true, message: '采购内容不能为空', trigger: 'blur' }],
  projectDescription: [{ required: true, message: '项目描述不能为空', 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
  });
  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 {
  padding: 15px 25px;
  :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;
    }
    .sub-title {
      font-size: 12px;
      color: #999;
      margin-left: 10px;
    }
  }
  .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 {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  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>
