import dayjs from "dayjs";
import { message } from "@/utils/message";
import { ElMessageBox, Sort } from "element-plus";
import { computed, onMounted, reactive, ref, toRaw, unref } from "vue";
import { CommonUtils } from "@/utils/common";
import { PaginationProps } from "@pureadmin/table";
import { getUserListApi, UserDTO } from "@/api/system/user";
import { useUserStoreHook } from "@/store/modules/user";
import {
  CollaborationOptionResponse,
  CollaborationRecordListCommand,
  CollaborationRecordPageResponse,
  deleteCollaborationRecordApi,
  getCollaborationOptionsApi,
  getCollaborationRecordListApi
} from "@/api/collaboration/record";

const statusTypeMap = {
  NONE: "info",
  SETTLED: "success",
  UNSETTLED: "danger",
  PARTIAL: "warning"
};

function getUserDisplayName(user: UserDTO) {
  return user.nickname || user.username || "";
}

export function useCollaborationRecordHook() {
  const userStore = useUserStoreHook();
  const isAdmin = computed(() => userStore.roles?.includes("admin"));

  const defaultSort: Sort = {
    prop: "deadline",
    order: "descending"
  };

  const pagination: PaginationProps = {
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  };

  const searchFormParams = reactive<CollaborationRecordListCommand>({
    brand: "",
    goods: "",
    creatorId: undefined,
    cooperationPlatform: undefined
  });

  const deadlineRange = computed<[string, string] | null>({
    get: () => getRange(searchFormParams.beginTime, searchFormParams.endTime),
    set: v => fillRange(v, "beginTime", "endTime")
  });

  const purchaseRange = computed<[string, string] | null>({
    get: () =>
      getRange(
        searchFormParams.purchaseBeginTime,
        searchFormParams.purchaseEndTime
      ),
    set: v => fillRange(v, "purchaseBeginTime", "purchaseEndTime")
  });

  const dataList = ref<CollaborationRecordPageResponse[]>([]);
  const optionMap = ref<Record<string, string[]>>({});
  const creatorOptions = ref<UserDTO[]>([]);
  const pageLoading = ref(true);
  const multipleSelection = ref<number[]>([]);
  const sortState = ref<Sort>(defaultSort);

  const columns: TableColumnList = [
    { type: "selection", align: "left" },
    { label: "品牌", prop: "brand", minWidth: 120 },
    { label: "物品", prop: "goods", minWidth: 120 },
    {
      label: "创建者",
      prop: "creatorName",
      minWidth: 110,
      hide: !isAdmin.value
    },
    { label: "合作平台", prop: "cooperationPlatform", minWidth: 110 },
    { label: "留存方式", prop: "retainedMethod", minWidth: 100 },
    { label: "购入方式", prop: "purchaseMethod", minWidth: 100 },
    {
      label: "预完成日期",
      prop: "deadline",
      minWidth: 130,
      sortable: "custom",
      formatter: ({ deadline }) => formatDate(deadline)
    },
    {
      label: "任务进度",
      minWidth: 130,
      cellRenderer: ({ row }) => `${row.completedTasksNum}/${row.tasksNum}`
    },
    {
      label: "拍单费用",
      minWidth: 110,
      cellRenderer: ({ row, props }) =>
        renderStatus(row.purchaseSettlementStatus, props.size)
    },
    {
      label: "快递费用",
      minWidth: 110,
      cellRenderer: ({ row, props }) =>
        renderStatus(row.deliverySettlementStatus, props.size)
    },
    {
      label: "稿费",
      minWidth: 110,
      cellRenderer: ({ row, props }) =>
        renderStatus(row.remunerationSettlementStatus, props.size)
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 160,
      sortable: "custom",
      formatter: ({ createTime }) => formatDateTime(createTime)
    },
    { label: "操作", fixed: "right", width: 140, slot: "operation" }
  ];

  function getRange(start?: string, end?: string) {
    if (!start || !end) return null;
    return [start, end] as [string, string];
  }

  function fillRange(v, startKey: string, endKey: string) {
    searchFormParams[startKey] = v?.length === 2 ? v[0] : undefined;
    searchFormParams[endKey] = v?.length === 2 ? v[1] : undefined;
  }

  function formatDate(value?: string) {
    return value ? dayjs(value).format("YYYY-MM-DD") : "";
  }

  function formatDateTime(value?: string) {
    return value ? dayjs(value).format("YYYY-MM-DD HH:mm:ss") : "";
  }

  function renderStatus(status, size) {
    if (!status) return "";
    const type = statusTypeMap[status.status] || "info";
    return (
      <el-tag size={size} type={type} effect="plain">
        {status.label}
      </el-tag>
    );
  }

  function onSortChanged(sort: Sort) {
    sortState.value = sort;
    pagination.currentPage = 1;
    getRecordList();
  }

  async function onSearch(tableRef) {
    pagination.currentPage = 1;
    const shouldResetSort = !isDefaultSort(sortState.value);
    sortState.value = defaultSort;

    if (shouldResetSort && sortByDefault(tableRef)) return;
    await getRecordList();
  }

  function isDefaultSort(sort: Sort) {
    return sort.prop === defaultSort.prop && sort.order === defaultSort.order;
  }

  function sortByDefault(tableRef) {
    const tableInstance = getTableInstance(tableRef);
    if (!tableInstance?.sort) return false;
    tableInstance.sort(defaultSort.prop, defaultSort.order);
    return true;
  }

  function getTableInstance(tableRef) {
    return unref(tableRef)?.getTableRef?.();
  }

  function resetForm(formEl, tableRef) {
    if (!formEl) return;
    formEl.resetFields();
    fillRange(null, "beginTime", "endTime");
    fillRange(null, "purchaseBeginTime", "purchaseEndTime");
    onSearch(tableRef);
  }

  async function getRecordList() {
    pageLoading.value = true;
    CommonUtils.fillSortParams(searchFormParams, sortState.value);
    CommonUtils.fillPaginationParams(searchFormParams, pagination);
    const { data } = await getCollaborationRecordListApi(
      toRaw(searchFormParams)
    ).finally(() => {
      pageLoading.value = false;
    });
    dataList.value = data.rows;
    pagination.total = data.total;
  }

  async function getOptions() {
    const { data } = await getCollaborationOptionsApi();
    optionMap.value = data.reduce(
      (result, item: CollaborationOptionResponse) => {
        result[item.type] = item.values;
        return result;
      },
      {}
    );
  }

  async function getCreatorOptions() {
    if (!isAdmin.value) return;
    const { data } = await getUserListApi({ pageNum: 1, pageSize: 1000 });
    creatorOptions.value = data.rows;
  }

  async function handleDelete(row: CollaborationRecordPageResponse) {
    await deleteCollaborationRecordApi([row.recordId]);
    message(`您删除了编号为${row.recordId}的合作记录`, { type: "success" });
    getRecordList();
  }

  async function handleBulkDelete(tableRef) {
    if (multipleSelection.value.length === 0) {
      message("请选择需要删除的数据", { type: "warning" });
      return;
    }
    confirmBulkDelete(tableRef);
  }

  function confirmBulkDelete(tableRef) {
    ElMessageBox.confirm(
      `确认删除编号为[ ${multipleSelection.value} ]的合作记录吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }
    )
      .then(deleteSelectedRecords)
      .catch(() => {
        message("取消删除", { type: "info" });
        getTableInstance(tableRef)?.clearSelection?.();
      });
  }

  async function deleteSelectedRecords() {
    await deleteCollaborationRecordApi(multipleSelection.value);
    message(`您删除了编号为[ ${multipleSelection.value} ]的合作记录`, {
      type: "success"
    });
    getRecordList();
  }

  onMounted(() => {
    getOptions();
    getCreatorOptions();
    getRecordList();
  });

  return {
    searchFormParams,
    pageLoading,
    columns,
    dataList,
    pagination,
    defaultSort,
    deadlineRange,
    purchaseRange,
    optionMap,
    creatorOptions,
    isAdmin,
    getUserDisplayName,
    multipleSelection,
    onSearch,
    onSortChanged,
    getRecordList,
    resetForm,
    handleDelete,
    handleBulkDelete
  };
}
