<template>
  <el-drawer title="新增拜访日程" :model-value="modelValue" @update:model-value="val => $emit('update:modelValue', val)" size="80%" direction="rtl" destroy-on-close class="custom-drawer" :with-header="false">
    <div class="drawer-header">
      <span class="header-title">新增拜访日程</span>
      <el-icon class="close-icon" @click="cancel"><Close /></el-icon>
    </div>
    <div class="drawer-body-custom">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="right" class="standard-form">
        <div class="section-group">
          <div class="section-title-bar">基本信息</div>
          <div class="section-content">
            <el-form-item label="关联计划" prop="planNo">
              <el-select v-model="form.planNo" placeholder="请选择" style="width: 100%" clearable filterable>
                <el-option v-for="item in planOptions" :key="item.id" :label="item.planNo + (item.customerName ? ' - ' + item.customerName : '')" :value="item.planNo" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="关联类型" prop="relevanceType">
              <el-radio-group v-model="form.relevanceType" @change="handleTypeChange">
                <el-radio value="0">客户</el-radio>
                <el-radio value="1">项目商机</el-radio>
                <el-radio value="2">年度入围</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item :label="typeLabel" prop="objectName">
              <el-select v-model="form.objectName" placeholder="请选择" style="width: 100%" clearable filterable @change="handleObjectChange">
                <el-option v-for="item in currentOptions" :key="item.id || item.customerNo" :label="item.projectName || item.customerName" :value="item.projectName || item.customerName" />
              </el-select>
            </el-form-item>

            <el-form-item label="拜访人" prop="callPeopleNo">
              <el-select v-model="form.callPeopleNo" placeholder="请选择" style="width: 100%" clearable filterable @change="handleStaffChange">
                <el-option v-for="item in staffOptions" :key="item.staffId" :label="(item.staffCode ? '(' + item.staffCode + ') ' : '') + item.staffName" :value="item.staffId" />
              </el-select>
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="拜访日期" prop="callDate">
                  <el-date-picker v-model="form.callDate" type="date" placeholder="请选择" style="width: 100%" value-format="YYYY-MM-DD" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="重要级别" prop="importantLevel">
                  <el-select v-model="form.importantLevel" placeholder="请选择" style="width: 100%">
                    <el-option v-for="dict in importanceOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="随访人" prop="followPeopleName">
              <el-select v-model="form.followPeopleName" placeholder="请选择" style="width: 100%" clearable filterable multiple collapse-tags>
                <el-option v-for="item in staffOptions" :key="item.staffId" :label="(item.staffCode ? '(' + item.staffCode + ') ' : '') + item.staffName" :value="item.staffName" />
              </el-select>
            </el-form-item>

            <el-form-item label="拜访目的" prop="purposeVisit">
              <el-input type="textarea" :rows="4" v-model="form.purposeVisit" placeholder="请输入内容" maxlength="200" show-word-limit />
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
    <template #footer>
      <div class="drawer-footer-standard">
        <el-button type="primary" @click="submitForm">确 认</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, computed, toRefs } from 'vue';
import { addRoutine } from "@/api/visit/routine";
import { listPlan } from "@/api/visit/plan";
import { listCustomerInfo } from "@/api/customer/customerInfo/index";
import { listComStaff } from "@/api/system/comStaff/index";
import { listOpportunity } from "@/api/saleManage/opportunity";
import { listProjectSelection } from "@/api/saleManage/projectSelection";
import { useUserStore } from "@/store/modules/user";

const props = defineProps({
  modelValue: Boolean
});

const emit = defineEmits(['update:modelValue', 'success']);
const proxy = getCurrentInstance().proxy;
const userStore = useUserStore();
const { importance_level: importanceOptions } = toRefs(reactive(proxy.useDict("importance_level")));

const formRef = ref(null);
const planOptions = ref([]);
const customerOptions = ref([]);
const opportunityOptions = ref([]);
const annualOptions = ref([]);
const staffOptions = ref([]);

const form = ref({
  planNo: undefined,
  relevanceType: '0',
  customerNo: undefined,
  customerName: undefined,
  objectNo: undefined,
  objectName: undefined,
  callPeopleNo: undefined,
  callPeopleName: undefined,
  callDate: undefined,
  importantLevel: undefined,
  followPeopleName: undefined,
  purposeVisit: undefined,
  platformCode: 'crm'
});

const rules = reactive({
  objectName: [{ required: true, message: "关联对象不能为空", trigger: "change" }],
  callDate: [{ required: true, message: "拜访日期不能为空", trigger: "change" }],
  importantLevel: [{ required: true, message: "重要级别不能为空", trigger: "change" }],
  purposeVisit: [
    { required: true, message: "拜访目的不能为空", trigger: "blur" },
    { max: 200, message: "不能超过200个字符", trigger: "blur" }
  ]
});

const typeLabel = computed(() => {
  if (form.value.relevanceType === '1') return '项目商机';
  if (form.value.relevanceType === '2') return '年度入围';
  return '客户';
});

const currentOptions = computed(() => {
  if (form.value.relevanceType === '1') return opportunityOptions.value;
  if (form.value.relevanceType === '2') return annualOptions.value;
  return customerOptions.value;
});

const handleTypeChange = () => {
  form.value.objectNo = undefined;
  form.value.objectName = undefined;
  form.value.customerNo = undefined;
  form.value.customerName = undefined;
};

const handleObjectChange = (val) => {
  const item = currentOptions.value.find(i => (i.projectName || i.customerName) === val);
  if (item) {
    form.value.objectNo = item.id || item.customerNo || item.opportunityNo;
    form.value.objectName = item.projectName || item.customerName;
    
    // 如果是商机或年度入围，同步其客户信息
    if (form.value.relevanceType !== '0') {
      form.value.customerName = item.customerName;
      form.value.customerNo = item.customerNo;
    } else {
      form.value.customerName = item.customerName;
      form.value.customerNo = item.customerNo;
    }
  }
};

const handleStaffChange = (val) => {
  const staff = staffOptions.value.find(item => item.staffId === val);
  if (staff) {
    form.value.callPeopleName = staff.staffName;
  }
};

const submitForm = () => {
  formRef.value.validate(valid => {
    if (valid) {
      if (!form.value.callPeopleName) {
        form.value.callPeopleName = userStore.nickname || userStore.name;
      }
      addRoutine(form.value).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        emit('success');
        cancel();
      });
    }
  });
};

const cancel = () => {
  emit('update:modelValue', false);
  reset();
};

const reset = () => {
  const currentUserName = userStore.nickname || userStore.name;
  const defaultStaff = staffOptions.value.find(item => item.staffName === currentUserName);
  
  form.value = {
    planNo: undefined,
    relevanceType: '0',
    customerNo: undefined,
    customerName: undefined,
    objectNo: undefined,
    objectName: undefined,
    callPeopleNo: defaultStaff ? defaultStaff.staffId : undefined,
    callPeopleName: defaultStaff ? defaultStaff.staffName : currentUserName,
    callDate: undefined,
    importantLevel: undefined,
    followPeopleName: undefined,
    purposeVisit: undefined,
    platformCode: 'crm'
  };
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

onMounted(() => {
  listPlan({ pageSize: 1000 }).then(res => { planOptions.value = res.rows || []; });
  listCustomerInfo({ pageNum: 1, pageSize: 500, isHighSeas: 'all' }).then(res => { customerOptions.value = res.rows || []; });
  listOpportunity({ pageSize: 1000 }).then(res => { opportunityOptions.value = res.rows || []; });
  listProjectSelection({ pageSize: 1000 }).then(res => { annualOptions.value = res.rows || []; });
  listComStaff({ pageSize: 1000 }).then(res => { staffOptions.value = res.rows || res.data || []; });
});
</script>

<style scoped lang="scss">
.custom-drawer {
  :deep(.el-drawer__body) { padding: 0; overflow: hidden; }
}

.drawer-header {
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
  border-bottom: 1px solid #f2f2f2;
  background-color: #fff;
  .header-title { font-size: 14px; color: #333; }
  .close-icon { cursor: pointer; font-size: 18px; color: #999; &:hover { color: #409eff; } }
}

.drawer-body-custom {
  height: calc(100vh - 48px - 60px); /* 减去 header 和 footer 高度 */
  overflow-y: auto;
  padding: 15px;
  background-color: #fff;
}

.section-group {
  margin-bottom: 20px;
  .section-title-bar {
    background-color: #f8faff;
    color: #409eff;
    padding: 6px 12px;
    font-size: 14px;
    margin-bottom: 15px;
    font-weight: normal;
  }
  .section-content {
    padding: 0 12px;
  }
}

.standard-form {
  :deep(.el-form-item) {
    margin-bottom: 18px;
    .el-form-item__label { font-weight: 400 !important; color: #666; }
  }
}

.drawer-footer-standard {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 0 20px;
  border-top: 1px solid #f2f2f2;
  background-color: #fff;
  .el-button {
    padding: 8px 24px;
    &--primary { background-color: #409eff; border-color: #409eff; }
  }
}

/* 隐藏滚动条 */
.drawer-body-custom {
  &::-webkit-scrollbar { width: 0 !important; height: 0 !important; display: none !important; }
  -ms-overflow-style: none !important;
  scrollbar-width: none !important;
}

:deep(*) { font-weight: 400 !important; }
</style>
