<template>
  <el-dialog v-model="dialogVisible" :title="isSelectMode ? '选择联系人' : '联系人管理'" width="900px" :destroy-on-close="true">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      row-key="id"
      :pagination="true"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" plain @click="handleAddContact">新增联系人</el-button>
      </template>

      <template #operation="scope">
        <el-button v-if="isSelectMode" type="primary" link @click="handleSelect(scope.row)">选择</el-button>
        <el-button type="primary" link @click="handleEditContact(scope.row)">编辑</el-button>
        <el-button type="primary" link @click="handleInvalidContact(scope.row)">失效</el-button>
        <el-button type="primary" link @click="handleDefaultContact(scope.row)">默认</el-button>
      </template>
    </ProTable>
  </el-dialog>
  <ContactEditModal ref="contactEditModalRef" />
</template>

<script setup lang="tsx" name="ContactSelectModal">
import { ref, reactive } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { ElMessage, ElMessageBox } from "element-plus";
import { getContactList, invalidContact, defaultDisplayContact, ResContactList } from "@/api/modules/contact";
import { isValidType } from "@/utils/dict";
import ContactEditModal from "./ContactEditModal.vue";

const proTable = ref<ProTableInstance>();
const contactEditModalRef = ref<InstanceType<typeof ContactEditModal>>();
const dialogVisible = ref(false);
const initParam = reactive({ customerId: "" as string | number });
const isSelectMode = ref(true);

// 回调函数
let onSelectCallback: ((row: ResContactList) => void) | null = null;

// dataCallback 处理返回数据
const dataCallback = (data: any) => {
  return {
    content: data?.content || [],
    total: Number(data?.total) || 0
  };
};

// 获取联系人列表
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  // 处理时间范围参数，将 createdAt 转换为 startTime 和 endTime
  if (newParams.createdAt && Array.isArray(newParams.createdAt) && newParams.createdAt.length === 2) {
    newParams.startTime = newParams.createdAt[0];
    newParams.endTime = newParams.createdAt[1];
    delete newParams.createdAt;
  }
  return getContactList(newParams);
};

// 表格配置项
const columns = reactive<ColumnProps<ResContactList>[]>([
  { prop: "id", label: "联系人ID", search: { el: "input" }, width: 100 },
  { prop: "customerId", label: "客户ID", search: { el: "input" }, width: 100 },
  { prop: "name", label: "姓名", width: 120, search: { el: "input" } },
  { prop: "phone", label: "电话", width: 140, search: { el: "input" } },
  { prop: "wechat", label: "微信号", width: 140, search: { el: "input" } },
  { prop: "position", label: "职务", width: 120 },
  { prop: "importanceLevel", label: "重要程度", width: 100 },
  { prop: "isValid", label: "是否有效", width: 100, enum: isValidType, search: { el: "select" } },
  { prop: "createdAt", label: "创建时间", width: 160, search: { el: "date-picker", props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" } } },
  { prop: "operation", label: "操作", fixed: "right", width: 280 }
]);

// 选择联系人
const handleSelect = (row: ResContactList) => {
  if (onSelectCallback) {
    onSelectCallback(row);
  }
  dialogVisible.value = false;
};

// 新增联系人
const handleAddContact = () => {
  contactEditModalRef.value?.acceptParams({
    title: "新增联系人",
    isView: false,
    row: { customerId: initParam.customerId },
    api: undefined,
    getTableList: proTable.value?.getTableList
  });
};

// 编辑联系人
const handleEditContact = (row: ResContactList) => {
  contactEditModalRef.value?.acceptParams({
    title: "编辑联系人",
    isView: false,
    row: row,
    api: undefined,
    getTableList: proTable.value?.getTableList
  });
};

// 失效联系人
const handleInvalidContact = async (row: ResContactList) => {
  ElMessageBox.confirm(
    '是否更新失效联系人？',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info',
    }
  )
    .then(async () => {
      await invalidContact(row);
      proTable.value?.getTableList();
      ElMessage({
        type: 'success',
        message: '更新成功',
      });
    })
    .catch(() => {});
};

// 默认显示联系人
const handleDefaultContact = async (row: ResContactList) => {
  ElMessageBox.confirm(
    '是否设置该联系人为默认？',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info',
    }
  )
    .then(async () => {
      await defaultDisplayContact(row);
      proTable.value?.getTableList();
      ElMessage({
        type: 'success',
        message: '设置成功',
      });
    })
    .catch(() => {});
};

// 打开弹窗（选择模式）
const open = (customerId: string | number, callback: (row: ResContactList) => void) => {
  initParam.customerId = customerId;
  isSelectMode.value = true;
  onSelectCallback = callback;
  dialogVisible.value = true;
};

// 打开弹窗（管理模式，不显示选择按钮）
const openManage = (customerId: string | number) => {
  initParam.customerId = customerId;
  isSelectMode.value = false;
  onSelectCallback = null;
  dialogVisible.value = true;
};

defineExpose({
  open,
  openManage
});
</script>
