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

      <template #operation="scope">
        <el-button type="primary" link @click.stop="handleEditCustomer(scope.row)">编辑</el-button>
        <el-button type="primary" link @click.stop="handleInvalidCustomer(scope.row)">失效</el-button>
        <el-button type="primary" link @click.stop="handleAddFollowUpForRow(scope.row)">跟进</el-button>
        <el-button type="primary" link @click.stop="handleCancelCustomerFollow(scope.row)">取消跟进</el-button>
      </template>
    </ProTable>

    <!-- 跟进列表 -->
    <div v-if="selectedCustomerId" class="follow-up-section">
      <el-divider />
      <div class="section-header">
        <h3>跟进记录 - {{ selectedCustomerName }}</h3>
        <el-button type="primary" plain @click="handleAddFollowUp">新增跟进</el-button>
      </div>
      <div class="follow-up-table">
        <ProTable
          ref="followUpProTable"
          :columns="followUpColumns"
          :request-api="getFollowUpTableList"
          :init-param="followUpInitParam"
          :data-callback="dataCallback"
          row-key="id"
          :pagination="true"
        >
          <template #isRemind="scope">
            <el-switch
              v-model="scope.row.isRemind"
              @change="(val: string | number | boolean) => handleRemindChange(scope.row, val as boolean)"
            />
          </template>
          <template #operation="scope">
            <el-button
              type="primary"
              link
              :disabled="!isCancelable(scope.row.nextRemindTime)"
              @click.stop="handleCancelFollowUp(scope.row)"
            >
              取消跟进
            </el-button>
          </template>
        </ProTable>
      </div>
    </div>

    <CustomerModal ref="customerModalRef" />
    <FollowUpModal ref="followUpModalRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, onMounted } from "vue";
import type { ResCustomerList } from "@/api/modules/customer";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { ElMessage, ElMessageBox } from "element-plus";
import { getCustomerList, updateCustomer, invalidCustomer, getCustomerDetail, cancelCustomer } from "@/api/modules/customer";
import { getFollowUpList, addFollowUp, updateFollowUpEnable, updateFollowUpCancel, ResFollowUpList } from "@/api/modules/follow";
import { isValidType, customerType } from "@/utils/dict";
import CustomerModal from "./components/customerModal.vue";
import FollowUpModal from "./components/FollowUpModal.vue";

// ProTable 实例
const proTable = ref<ProTableInstance>();
const followUpProTable = ref<ProTableInstance>();
const customerModalRef = ref<InstanceType<typeof CustomerModal>>();
const followUpModalRef = ref<InstanceType<typeof FollowUpModal>>();

// 选中的客户
const selectedCustomerId = ref<string | number>("");
const selectedCustomerName = ref<string>("");
const selectedContactId = ref<string | number>("");

// 跟进列表初始化参数
const followUpInitParam = reactive({ customerId: "" as string | number, contactId: "" as string | number });

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

// 排序参数
const sortParam = reactive({
  orderBy: "",
  asc: true
});

// 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));
  // 添加排序参数
  if (sortParam.orderBy) {
    newParams.orderBy = sortParam.orderBy;
    newParams.asc = sortParam.asc;
  }
  return getCustomerList(newParams);
};

// 排序变化处理
const handleSortChange = ({ prop, order }: { prop: string; order: string | null }) => {
  if (prop && order) {
    sortParam.orderBy = prop;
    sortParam.asc = order === "ascending";
  } else {
    sortParam.orderBy = "";
    sortParam.asc = true;
  }
  // 刷新表格数据
  proTable.value?.getTableList();
};

// 获取跟进列表
const getFollowUpTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  return getFollowUpList(newParams);
};

// 客户表格配置项
const columns = reactive<ColumnProps<ResCustomerList>[]>([
  {
    prop: "name",
    label: "客户信息",
    search: { el: "input" },
    width: 280,
    fixed: true,
    sortable: "custom",
    render: (scope: any) => {
      return (
        <div class="customer-info">
          <div class="customer-name">{scope.row.name}</div>
          <div class="customer-id">ID: {scope.row.id}</div>
        </div>
      );
    }
  },
  { prop: "contactName", label: "联系人名称", width: 160, search: { el: "input" } },
  { prop: "type", label: "客户类型", width: 160, enum: customerType, search: { el: "select" }, sortable: "custom" },
  { prop: "baseLocation", label: "base地", width: 160, search: { el: "input" }, sortable: "custom" },
  { prop: "introducer", label: "介绍人", width: 160, search: { el: "input" }, sortable: "custom" },
  { prop: "createdAt", label: "创建时间", width: 200 },
  { prop: "latestFollowTime", label: "最后跟进时间", width: 200, sortable: "custom" },
  { prop: "nextRemindTime", label: "下次提醒时间", width: 200, sortable: "custom" },
  { prop: "isValid", label: "是否有效", width: 160, enum: isValidType, search: { el: "select" } },

  // { prop: "name", label: "客户名称", width: 160, search: { el: "input" }, isShow: false, sortable: "custom" },
  { prop: "operation", label: "操作", fixed: "right", width: 320 }
]);

// 跟进列表表格配置项
const followUpColumns = reactive<ColumnProps<ResFollowUpList>[]>([
  { prop: "id", label: "跟进ID", width: 100 },
  { prop: "content", label: "跟进内容", minWidth: 200 },
  { prop: "isRemind", label: "是否提醒", width: 100 },
  { prop: "nextRemindTime", label: "下次提醒时间", width: 180 },
  { prop: "contactInfo.name", label: "联系人", width: 120 },
  { prop: "createdAt", label: "创建时间", width: 180 },
  { prop: "operation", label: "操作", fixed: "right", width: 120 }
]);

// 提醒状态变更
const handleRemindChange = async (row: ResFollowUpList, val: boolean) => {
  try {
    await updateFollowUpEnable({ id: row.id });
    ElMessage.success("更新成功");
  } catch (error) {
    // 失败时恢复原值
    row.isRemind = !val;
    console.error("更新失败：", error);
  }
};

// 判断是否可以取消跟进（下次提醒时间大于当前时间）
const isCancelable = (nextRemindTime: string) => {
  if (!nextRemindTime) return false;
  const remindTime = new Date(nextRemindTime).getTime();
  const currentTime = new Date().getTime();
  return remindTime > currentTime;
};

// 取消跟进
const handleCancelFollowUp = async (row: ResFollowUpList) => {
  // 再次校验时间
  if (!isCancelable(row.nextRemindTime)) {
    ElMessage.warning("该跟进已过期，无法取消");
    return;
  }

  ElMessageBox.confirm(
    '是否取消该跟进？',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await updateFollowUpCancel({ id: row.id });
      followUpProTable.value?.getTableList();
      ElMessage.success("取消成功");
    })
    .catch(() => {});
};

// 点击行显示跟进列表
const handleRowClick = (row: ResCustomerList) => {
  selectedCustomerId.value = row.id;
  selectedCustomerName.value = row.name;
  selectedContactId.value = (row as any).contactId || "";
  followUpInitParam.customerId = row.id;
  followUpInitParam.contactId = (row as any).contactId || "";
};

// 为指定客户新增跟进
const handleAddFollowUpForRow = (row: ResCustomerList) => {
  // 设置当前选中的客户信息
  selectedCustomerId.value = row.id;
  selectedCustomerName.value = row.name;
  selectedContactId.value = (row as any).contactId || "";
  followUpInitParam.customerId = row.id;
  followUpInitParam.contactId = (row as any).contactId || "";
  // 打开新增跟进弹窗
  followUpModalRef.value?.acceptParams({
    title: "新增跟进",
    isView: false,
    row: { customerId: row.id, contactId: (row as any).contactId || "" },
    api: undefined,
    getTableList: followUpProTable.value?.getTableList
  });
};

// 取消客户最新跟进提醒
const handleCancelCustomerFollow = async (row: ResCustomerList) => {
  ElMessageBox.confirm(
    '是否取消该客户的最新跟进提醒？',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await cancelCustomer({ id: row.id });
      proTable.value?.getTableList();
      ElMessage.success("取消成功");
    })
    .catch(() => {});
};

// 编辑客户
const handleEditCustomer = async (row: ResCustomerList) => {
  console.log(row);
  const res = await getCustomerDetail({ id: row.id });
  console.log("---", res);
  customerModalRef.value?.acceptParams({
    title: "新增客户",
    isView: false,
    row: res.data,
    api: undefined,
    getTableList: proTable.value?.getTableList
  });
};

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

    })
};

// 新增客户
const handleAddCustomer = async () => {
  customerModalRef.value?.acceptParams({
    title: "新增客户",
    isView: false,
    row: {},
    api: undefined,
    getTableList: proTable.value?.getTableList
  });
};

// 新增跟进
const handleAddFollowUp = () => {
  followUpModalRef.value?.acceptParams({
    title: "新增跟进",
    isView: false,
    row: { customerId: selectedCustomerId.value, contactId: selectedContactId.value },
    api: undefined,
    getTableList: followUpProTable.value?.getTableList
  });
};

onMounted(() => { });
</script>

<style scoped lang="scss">
.table-box-customer {
  height: 100%;
}
.customer-table {
  :deep(.table-main) {
    flex: none;
  }
}
.follow-up-section {
  margin-top: 20px;
  .section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 15px;
    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
    }
  }
  .follow-up-table {
    width: 100%;
  }
}
.customer-info {
  .customer-name {
    margin-bottom: 4px;
    font-size: 14px;
    font-weight: 500;
    color: #303133;
  }
  .customer-id {
    font-size: 12px;
    color: #909399;
  }
}
</style>
