<template>
  <el-drawer title="编辑拜访日程" :model-value="modelValue" @update:model-value="val => $emit('update:modelValue', val)" size="80%" direction="rtl" destroy-on-close class="routine-drawer">
    <div class="dialog-content-area">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <div class="section-title">基本信息</div>
        <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>
            <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>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <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, watch, computed, toRefs } from 'vue';
import { getRoutine, updateRoutine } 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";

const props = defineProps({
  modelValue: Boolean,
  id: [Number, String]
});

const emit = defineEmits(['update:modelValue', 'success']);
const proxy = getCurrentInstance().proxy;
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({
  id: undefined,
  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;
});

watch(() => props.id, (newVal) => {
  if (newVal) {
    getInfo(newVal);
  }
}, { immediate: true });

function getInfo(id) {
  getRoutine(id).then(response => {
    const data = response.data || {};
    form.value = {
      ...data,
      relevanceType: String(data.relevanceType ?? '0'),
      importantLevel: String(data.importantLevel ?? '')
    };
  });
}

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) {
      updateRoutine(form.value).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        emit('success');
        cancel();
      });
    }
  });
};

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

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">
.routine-drawer {
  :deep(.el-drawer__header) {
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 0;
    padding: 15px 20px;
    .el-drawer__title { font-size: 15px; color: #333; font-weight: normal; }
  }
}
.dialog-content-area { padding: 20px; }
.section-title {
  font-size: 14px;
  color: #409eff;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #ebeef5;
  font-weight: normal;
}
:deep(.el-form-item__label) {
  font-weight: normal;
}
.dialog-footer { text-align: right; padding: 20px; border-top: 1px solid #f0f0f0; }
:deep(*) { font-weight: 400 !important; }
</style>
