<template>
  <el-drawer
    v-model="visible"
    direction="rtl"
    size="80%"
    :close-on-click-modal="false"
    :with-header="false"
    class="opp-drawer"
  >
    <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-body">
        <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 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="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 localCustomerOptions" :key="item.id"
                      :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 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="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="12">
                <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="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="24">
              <el-col :span="12">
                <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-col :span="12">
                <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-row>
            <el-row :gutter="24">
              <el-col :span="12">
                <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="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="24">
              <el-col :span="12">
                <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-col :span="12">
                <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="purchaseContent">
              <el-input v-model="form.purchaseContent" type="textarea" :rows="3" maxlength="500" show-word-limit placeholder="请输入采购内容" />
            </el-form-item>
            <el-form-item label="项目描述" prop="description">
              <el-input v-model="form.description" type="textarea" :rows="3" maxlength="500" show-word-limit placeholder="请输入项目描述" />
            </el-form-item>
            <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>
          </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 min-width="200">
                <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="文件类型" prop="type" width="100" align="center" />
              <el-table-column label="上传时间" prop="uploadTime" width="180" align="center" />
              <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>
    </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 { useDebounceFn } from '@vueuse/core';
import { addOpportunity } from '@/api/saleManage/opportunity/index';
import { listCustomerInfo } from "@/api/customer/customerInfo/index";
import { globalHeaders } from '@/utils/request';
import { Close, Upload, Document } from '@element-plus/icons-vue';

const props = defineProps({
  modelValue: Boolean,
  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 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: 0,
  projectType: '销售商机',
  status: '0'
});

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, customerNo: String(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' }],
  projectLevel: [{ required: true, message: '项目级别不能为空', trigger: 'change' }],
  projectArea: [
    { required: true, message: '项目区域不能为空', trigger: 'blur' },
    { max: 100, message: '项目区域不能超过100个字符', trigger: 'blur' }
  ],
  purchaseMethod: [{ required: true, message: '采购方式不能为空', trigger: 'change' }],
  source: [{ required: true, message: '信息来源不能为空', trigger: 'change' }],
  purchaseContent: [
    { required: true, message: '采购内容不能为空', trigger: 'blur' },
    { max: 500, message: '采购内容不能超过500个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '项目描述不能为空', trigger: 'blur' },
    { max: 500, message: '项目描述不能超过500个字符', trigger: 'blur' }
  ],
  competitor: [
    { max: 500, message: '竞争对手不能超过500个字符', 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,
    companyId: undefined,
    customerNo: undefined,
    customerName: undefined,
    managerId: undefined,
    leaderName: undefined,
    projectName: undefined,
    amount: undefined,
    winRate: undefined,
    setupTime: undefined,
    deadline: undefined,
    marketingActivity: undefined,
    projectLevel: undefined,
    projectArea: undefined,
    purchaseMethod: undefined,
    source: undefined,
    description: undefined,
    competitor: undefined,
    fileNo: '',
    izClue: 0,
    projectType: '销售商机',
    status: '0'
  });
  fileList.value = [];
  if (formRef.value) formRef.value.resetFields();
};

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

const handleLeaderChange = (val) => {
  const user = props.userOptions.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 = { 
      name: res.data.fileName, 
      url: res.data.url, 
      ossId: res.data.ossId,
      type: res.data.fileName.split('.').pop().toUpperCase() || '-',
      uploadTime: proxy.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
    };
    fileList.value.push(file);
    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 = {
        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'
      };
      addOpportunity(data).then(() => {
        proxy.$modal.msgSuccess("新增成功");
        visible.value = false;
        emit('success');
      }).finally(() => { submitting.value = false; });
    }
  });
};
</script>

<style scoped lang="scss">
.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: 600;
      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;
    }
  }
}
:deep(.el-drawer__body) { padding: 0 !important; background-color: #fff; }

.drawer-body {
  padding: 0;
  height: 100%;
  overflow-y: auto;
  // 隐藏滚动条
  &::-webkit-scrollbar { display: none; }
  scrollbar-width: none;
  -ms-overflow-style: none;
}

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

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

.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>
