<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="客户名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入客户名称" />
      </el-form-item>
      <el-form-item label="客户类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择客户类型">
          <el-option v-for="item in customerType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="base地址" prop="baseLocation">
        <el-input v-model="formData.baseLocation" maxlength="100" show-word-limit placeholder="请输入base地址" />
      </el-form-item>

      <el-form-item label="介绍人" prop="introducer">
        <el-input v-model="formData.introducer" placeholder="请输入介绍人" />
      </el-form-item>

      <el-form-item label="联系人姓名" prop="contactName">
        <div style="display: flex; width: 100%">
          <el-input
            v-model="formData.contactName"
            :disabled="drawerProps.row.id"
            placeholder="请输入联系人姓名"
            style="width: 100%"
          />
          <el-button type="primary" @click="selectContact" style="margin-left: 10px" v-if="drawerProps.row.id"
            >查看联系人</el-button
          >
        </div>
      </el-form-item>
      <el-form-item label="联系人电话" prop="contactPhone">
        <el-input v-model="formData.contactPhone" :disabled="drawerProps.row.id" placeholder="请输入联系人电话" />
      </el-form-item>
      <el-form-item label="联系人微信号" prop="contactWechat">
        <el-input v-model="formData.contactWechat" :disabled="drawerProps.row.id" placeholder="请输入联系人微信号" />
      </el-form-item>
      <el-form-item label="联系人职务" prop="contactPosition">
        <el-input v-model="formData.contactPosition" :disabled="drawerProps.row.id" placeholder="请输入联系人职务" />
      </el-form-item>
      <el-form-item label="跟进内容" prop="followUpContent">
        <el-input v-model="formData.followUpContent" type="textarea" 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"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item v-if="drawerProps.row.id" label="是否有效" prop="isValid">
        <el-switch v-model="formData.isValid" />
      </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="SyncMaterialConsumption">
import { ref, reactive, computed } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { customerType, isValidType } from "@/utils/dict";
import { addCustomer, updateCustomer } from "@/api/modules/customer";
import ContactSelectModal from "./ContactSelectModal.vue";
const rules = reactive({
  name: [{ required: true, message: "请输入客户名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择客户类型", trigger: "change" }],
  contactName: [{ required: true, message: "请输入联系人姓名", trigger: "blur" }]
});
const formData = ref<any>({
  name: "",
  type: "",
  baseLocation: "",
  introducer: "",
  contactId: "",
  contactName: "",
  contactPhone: "",
  contactWechat: "",
  contactPosition: "",
  followUpContent: "",
  nextRemindTime: "",
  isValid: true
});

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: {}
});

// 从 row 中提取广告主ID列表
const advertiserIdList = computed(() => {
  const advertiserId = drawerProps.value.row?.advertiserId;
  if (!advertiserId) return [];
  // 如果是数组，直接返回
  if (Array.isArray(advertiserId)) return advertiserId;
  // 如果是字符串，转换为数组
  if (typeof advertiserId === "string") return [advertiserId];
  return [];
});
const contactSelectModalRef = ref<InstanceType<typeof ContactSelectModal>>();

const selectContact = () => {
  // 使用管理模式打开，只管理联系人，不选择
  contactSelectModalRef.value?.openManage(drawerProps.value.row.id);
};

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  // 确保 row 对象存在
  if (!drawerProps.value.row) {
    drawerProps.value.row = {};
  }
  formData.value = {
    id: drawerProps.value.row.id || "",
    name: drawerProps.value.row.name || "",
    type: drawerProps.value.row.type || "",
    baseLocation: drawerProps.value.row.baseLocation || "",
    introducer: drawerProps.value.row.introducer || "",
    contactId: drawerProps.value.row?.contactInfo?.id || "",
    contactName: drawerProps.value.row?.contactInfo?.name || "",
    contactPhone: drawerProps.value.row?.contactInfo?.phone || "",
    contactWechat: drawerProps.value.row?.contactInfo?.wechat || "",
    contactPosition: drawerProps.value.row?.contactInfo?.position || "",
    followUpContent: drawerProps.value.row.followUpContent || "",
    nextRemindTime: drawerProps.value.row.nextRemindTime || "",
    isValid: drawerProps.value.row.isValid !== undefined ? drawerProps.value.row.isValid : true
  };

  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;

  try {
    if (formData.value.id) {
      const res = await updateCustomer(formData.value);
      console.log(res);
    } else {
      const res = await addCustomer(formData.value);
      console.log(res);
    }

    ElMessage.success("成功！");

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

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

defineExpose({
  acceptParams
});
</script>
