<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      row-key="advertiserId"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" plain @click="handleAddCustomer"> 新增客户 </el-button>
      </template>

      <template #operation="scope">
        <el-button type="primary" link @click="handleEditCustomer(scope.row)">编辑</el-button>
        <el-button type="primary" link @click="handleInvalidContact(scope.row)">失效</el-button>
        <el-button type="primary" link @click="handleDisable(scope.row)">是否默认</el-button>
      </template>
    </ProTable>
    <ContactModal ref="contactModalRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, onMounted } 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, ResContactList } from "@/api/modules/contact";
import { isValidType } from "@/utils/dict";
import ContactModal from "./components/contactModal.vue";

// ProTable 实例
const proTable = ref<ProTableInstance>();
const contactModalRef = ref<InstanceType<typeof ContactModal>>();

// 搜索时间范围
const searchTime = ref<[string, string]>(["", ""]);

// 如果表格需要初始化请求参数，直接定义传给 ProTable
const initParam = reactive({});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 content && total 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    content: data?.content || [],
    total: Number(data?.total) || 0
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
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: 230 }
]);

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

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

    })
};

// 设置默认联系人
const handleDisable = async (row: ResContactList) => {
  console.log(row);
};

// 新增联系人
const handleAddCustomer = async () => {
  contactModalRef.value?.acceptParams({
    title: "新增联系人",
    isView: false,
    row: {},
    api: undefined,
    getTableList: proTable.value?.getTableList
  });
};
onMounted(() => {});
</script>
