<template>
  <el-dialog v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="drawerProps.title">
    <el-form
      ref="ruleFormRef"
      label-width="120px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="formData"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="选择联系人">
        <el-button type="primary" @click="selectContact">选择联系人</el-button>
        <span v-if="formData.contactName" style="margin-left: 10px; color: #606266;">
          已选择: {{ formData.contactName }}
        </span>
      </el-form-item>
      <el-form-item label="跟进内容" prop="content">
        <el-input v-model="formData.content" type="textarea" :rows="4" placeholder="请输入跟进内容" />
      </el-form-item>
      <el-form-item label="下次提醒时间" prop="nextRemindTime">
        <el-date-picker
          v-model="formData.nextRemindTime"
          type="datetime"
          placeholder="选择下次提醒时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
  <ContactSelectModal ref="contactSelectModalRef" />
</template>

<script setup lang="ts" name="FollowUpModal">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { addFollowUp } from "@/api/modules/follow";
import ContactSelectModal from "./ContactSelectModal.vue";

const rules = reactive({
  content: [{ required: true, message: "请输入跟进内容", trigger: "blur" }],
  contactId: [{ required: true, message: "请选择联系人", trigger: "change" }],
  nextRemindTime: [
    { required: true, message: "请选择下次提醒时间", trigger: "change" },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value) {
          const selectedTime = new Date(value).getTime();
          const currentTime = new Date().getTime();
          if (selectedTime <= currentTime) {
            callback(new Error("下次提醒时间必须大于当前时间"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ]
});

const formData = ref<any>({
  content: "",
  nextRemindTime: "",
  customerId: "",
  contactId: "",
  contactName: ""
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: {
    [key: string]: any;
  };
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

const contactSelectModalRef = ref<InstanceType<typeof ContactSelectModal>>();

// 选择联系人
const selectContact = () => {
  contactSelectModalRef.value?.open(formData.value.customerId, (row: any) => {
    formData.value.contactId = row.id || "";
    formData.value.contactName = row.name || "";
  });
};

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  // 确保 row 对象存在
  if (!drawerProps.value.row) {
    drawerProps.value.row = {};
  }
  formData.value = {
    content: drawerProps.value.row.content || "",
    nextRemindTime: drawerProps.value.row.nextRemindTime || "",
    customerId: drawerProps.value.row.customerId || "",
    contactId: drawerProps.value.row.contactId || "",
    contactName: drawerProps.value.row.contactName || ""
  };

  drawerVisible.value = true;
};

// 提交数据
const ruleFormRef = ref<FormInstance>();
const handleSubmit = async () => {
  // 表单验证
  if (!ruleFormRef.value) return;
  const valid = await ruleFormRef.value.validate().catch(() => false);
  if (!valid) return;

  // 构建提交数据
  const submitData = {
    customerId: formData.value.customerId,
    contactId: formData.value.contactId,
    content: formData.value.content,
    nextRemindTime: formData.value.nextRemindTime
  };

  try {
    const res = await addFollowUp(submitData);
    console.log(res);

    ElMessage.success("新增成功！");

    // 刷新表格数据
    drawerProps.value.getTableList?.();

    // 关闭抽屉
    drawerVisible.value = false;
  } catch (error) {
    console.error("新增失败：", error);
  }
};

defineExpose({
  acceptParams
});
</script>
