import type {
  LoadingConfig,
  AdaptiveConfig,
  PaginationProps
} from "@pureadmin/table";
import { ref, reactive, watch } from "vue";
import { delObjectProperty } from "@pureadmin/utils";
import { clone, delay } from "@pureadmin/utils";

import Attend from "@/model/attend.js";
import AttendItem from "@/model/attendItem.js";

export function useColumns(projects) {
  const loading = ref(true);
  const editMap = ref({});
  const dataList = ref([]);
  const dataFilter = ref([]);
  const options = ref([]);

  const confirmOptions = ref([
    { value: 0, label: '缺岗' },
    { value: 1, label: '到岗' }
  ]);

  const projectMap = reactive<Record<string | number, string>>({});

  const getProjectName = (projId) => {
    for (const p of projects.value) {
      if (Number(p.id) == Number(projId)) {
        return p.name;
      }
    }
    return ''
  }

  const getLocName = (projId, locId) => {
    for (const p of projects.value) {
      if (Number(p.id) == Number(projId)) {
        for (const loc of p.locations) {
          if (Number(loc.id) == Number(locId)) {
            return loc.name;
          }
        }
      }
    }
    return ''
  }

  // 监听 projectList 变化，动态更新映射（异步获取后会触发）
  watch(
    projects,
    (newList) => {
      // 清空旧映射
      Object.keys(projectMap).forEach(key => delete projectMap[key]);
      // 构建新映射
      newList.forEach(project => {
        projectMap[project.id] = project.name;
      });
    },
    { immediate: true } // 初始时执行一次（即使 projectList 初始为空）
  );

  const columns: TableColumnList = [
    {
      label: "时间",
      prop: "tm",
      cellRenderer: ({ row, index }) => (
        <p>{ new Date(row.tm).toLocaleString() }</p>
      )
    },
    {
      label: "项目名称",
      prop: "projId",
      // cellRenderer: ({ row, index }) => {
      //   // 处理未加载/未匹配的情况
      //   if (!Object.keys(projectMap).length) {
      //     return <p>加载中...</p>; // 未加载完成时显示
      //   }
      //   const projectName = projectMap[row.projId] || `未知项目(${row.projId})`;
      //   return <p>{ projectName }</p>;
      // }
      cellRenderer: ({ row, index }) => (
        <p>{ getProjectName(row.projId) }</p>
      )
    },
    {
      label: "区域名称",
      prop: "locId",
      cellRenderer: ({ row, index }) => (
        <p>{ getLocName(row.projId, row.locId) }</p>
      )
    },
    {
      label: "人员ID",
      prop: "id",
      cellRenderer: ({ row, index }) => (
        <p>{row.id}</p>
      )
    },
    {
      label: "人员名称",
      prop: "name",
      cellRenderer: ({ row, index }) => (
        <p>{row.name}</p>
      )
    },
    {
      label: "职位",
      prop: "job",
      cellRenderer: ({ row, index }) => (
        <p>{row.job}</p>
      )
    },
    {
      label: "电话",
      prop: "phone",
      cellRenderer: ({ row, index }) => (
        <p>{row.phone}</p>
      )
    },
    {
      label: "标签ID",
      prop: "tagId",
      cellRenderer: ({ row, index }) => (
        <p>{row.tagId}</p>
      )
    },
    {
      label: "在线",
      prop: "isOnline",
      cellRenderer: ({ row, index }) => (
        <el-tag type={row.rssi == 0 ? 'danger' : 'primary'}>
          {row.rssi == 0 ? '离线' : '在线'}
        </el-tag>
      )
    },
    {
      label: "到岗",
      prop: "confirm",
      cellRenderer: ({ row, index }) => (
        <>
          {editMap.value[index]?.editable ? (
            <el-select v-model={row.confirm} clearable placeholder="请选择爱好">
              {confirmOptions.value.map(item => {
                return (
                  <el-option
                    key={item.value}
                    label={item.label}
                    value={item.value}
                  />
                );
              })}
            </el-select>
          ) : (
            <el-tag type={row.confirm == 0 ? 'danger' : 'primary'}>
              {row.confirm == 0 ? '缺岗' : '到岗'}
            </el-tag>
          )}
        </>
      )
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    },
  ];

  /** 分页配置 */
  const pagination = reactive<PaginationProps>({
    pageSize: 20,
    currentPage: 1,
    pageSizes: [20, 40, 60],
    total: 0,
    align: "right",
    background: true,
    size: "default"
  });

  /** 加载动画配置 */
  const loadingConfig = reactive<LoadingConfig>({
    text: "正在加载第一页...",
    viewBox: "-10, -10, 50, 50",
    spinner: `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `
    // svg: "",
    // background: rgba()
  });

  /** 撑满内容区自适应高度相关配置 */
  const adaptiveConfig: AdaptiveConfig = {
    /** 表格距离页面底部的偏移量，默认值为 `96` */
    offsetBottom: 110
    /** 是否固定表头，默认值为 `true`（如果不想固定表头，fixHeader设置为false并且表格要设置table-layout="auto"） */
    // fixHeader: true
    /** 页面 `resize` 时的防抖时间，默认值为 `60` ms */
    // timeout: 60
    /** 表头的 `z-index`，默认值为 `100` */
    // zIndex: 100
  };

  function onSizeChange(val) {
    console.log("onSizeChange", val);
  }

  function onCurrentChange(val) {
    loadingConfig.text = `正在加载第${val}页...`;
    loading.value = true;
    delay(600).then(() => {
      loading.value = false;
    });
  }

  function onEdit(row, index) {
    editMap.value[index] = Object.assign({ ...row, editable: true });
  }

  function onSave(index) {
    editMap.value[index].editable = false;
  }

  function onCancel(index) {
    editMap.value[index].editable = false;
    dataFilter.value[index] = delObjectProperty(editMap.value[index], "editable");
  }

  function onDel(row) {
    let index = dataFilter.value.indexOf(row);
    if (index !== -1) dataFilter.value.splice(index, 1);

    index = dataList.value.indexOf(row);
    if (index !== -1) dataList.value.splice(index, 1);

    if (row.parent) {
      const attend = row.parent;
      index = attend.items.indexOf(row);
      if (index !== -1) attend.items.splice(index, 1);
    } else {
      console.log('no parent', row)
    }
    
  }

  return {
    loading,
    editMap,
    columns,
    dataList,
    dataFilter,
    options,
    pagination,
    loadingConfig,
    adaptiveConfig,

    getProjectName,
    getLocName,

    onDel,
    onEdit,
    onSave,
    onCancel,
    onSizeChange,
    onCurrentChange
  };
}
