<script setup lang="tsx">
import { nextTick } from 'vue';
import { NSwitch } from 'naive-ui';
import {
  fetchAddChannel,
  fetchDelChannel,
  fetchGetChannelList,
  fetchUpdateChannel
} from '@/service/api/government/government-list';
import { fetchGetLoginUserList } from '@/service/api/common';
import { useAuth } from '@/hooks/business/auth';
import { useTable } from '@/components/zt/Table/hooks/useTable';
import { useModalFrom } from '@/components/zt/ModalForm/hooks/useModalForm';

const columns: NaiveUI.TableColumn<Api.government.ChannelVO>[] = [
  {
    key: 'channelNo',
    title: '企业编号',
    align: 'center',
    width: 150
  },
  {
    key: 'channelName',
    title: '企业名称',
    align: 'center'
  },
  {
    key: 'staffCount',
    title: '总员工数',
    align: 'center'
  },
  {
    key: 'normalCount',
    title: '正常员工数',
    align: 'center'
  },
  {
    key: 'status',
    title: '状态',
    align: 'center',
    render: row => {
      return (
        <NSwitch
          uncheckedValue={0}
          checkedValue={1}
          value={row.status}
          onUpdate:value={val => {
            row.status = val;
            fetchUpdateChannel(row);
          }}
        ></NSwitch>
      );
    }
  },
  {
    key: 'createTime',
    title: '创建时间',
    align: 'center'
  }
];

const [registerTable, { refresh, setFieldsValue: setSearchValues, getTableData }] = useTable({
  searchFormConfig: {
    schemas: [
      {
        field: 'channelNos',
        label: '企业名称',
        component: 'ApiSelect',
        componentProps: {
          api: fetchGetLoginUserList,
          labelFeild: 'channelName',
          valueFeild: 'channelNo',
          multiple: true,
          onUpdateValue: () => {
            nextTick(() => {
              handleSearch();
            });
          },
          getOptions: async (options: any) => {
            await setSearchValues({ channelNos: [options[0].channelNo] });
            handleSearch();
          }
        }
      },
      {
        field: 'status',
        label: '状态',
        component: 'NSelect',
        componentProps: {
          options: [
            {
              label: '正常',
              value: 1
            },
            {
              label: '禁用',
              value: 0
            }
          ]
        }
      },
      {
        field: 'userAttrType',
        label: '人员属性',
        component: 'dictSelect',
        componentProps: {
          dictCode: 'user_attr_type',
          immediate: true
        },
        show: useAuth().hasAuth('user:attr:type')
      }
    ],
    inline: false,
    size: 'small',
    labelPlacement: 'left',
    isFull: false
  },
  tableConfig: {
    keyField: 'id',
    title: '企业列表',
    showAddButton: true,
    defaultParamsNotReset: 'channelNos',
    opWdith: 220
  }
});

const [registerModalForm, { openModal, closeModal, getFieldsValue, setFieldsValue, setModalProps }] = useModalFrom({
  modalConfig: {
    title: '标签 ',
    width: 500,
    isShowHeaderText: true,
    height: 200
  },
  formConfig: {
    schemas: [
      {
        label: '',
        field: 'id',
        component: 'NInput',
        show: false
      },
      {
        label: '企业编码',
        field: 'channelNo',
        component: 'NInput',
        show: false
      },
      {
        label: '所属企业',
        field: 'appName',
        component: 'NInput',
        componentProps: {
          readonly: true,
          disabled: true
        }
      },
      {
        field: 'channelName',
        label: '企业名称',
        component: 'NInput',
        required: true
      },
      {
        field: 'status',
        label: '状态',
        component: 'NSwitch',
        required: true,
        componentProps: {
          checkedValue: 1,
          uncheckedValue: 0
        },
        defaultValue: 1
      }
    ],
    gridProps: {
      cols: '1'
    },
    labelWidth: 120
  }
});
async function handleSubmit() {
  const form = await getFieldsValue();
  if (form.id) {
    await fetchUpdateChannel(form);
  } else {
    await fetchAddChannel(form);
  }
  closeModal();
  refresh();
}

function handleSearch() {
  refresh();
}

async function edit(row: Recordable) {
  openModal(row);
  setFieldsValue(row);
}
function handleOpenModal() {
  openModal();
  setModalProps({ title: '新增一级企业' });
}
function addtwo(row: Api.government.ChannelVO) {
  // 获取完整的层级路径名称
  const fullPathName = findParentNames(row);
  const levelDesc = getLevelDescription(row);
  openModal();
  setFieldsValue({ appName: fullPathName, channelNo: row.channelNo });
  setModalProps({ title: `新增${levelDesc}` });
}
function findParentNames(row: Api.government.ChannelVO): string {
  const tableData = getTableData();

  // 如果没有父级ID，说明是顶级节点
  if (!row.fatherId) {
    return row.channelName || '';
  }

  const nodeMap = new Map<string, Api.government.ChannelVO>();
  function buildNodeMap(nodes: Api.government.ChannelVO[]) {
    nodes.forEach((item: Api.government.ChannelVO) => {
      nodeMap.set(item.id, item);
      if (item.children && item.children.length > 0) {
        buildNodeMap(item.children);
      }
    });
  }

  buildNodeMap(tableData);

  function findPath(currentId: string, path: string[] = []): string[] {
    const currentNode = nodeMap.get(currentId);
    if (!currentNode) {
      return path;
    }

    const currentPath = [currentNode.channelName || '', ...path];

    if (!currentNode.fatherId) {
      return currentPath;
    }

    return findPath(currentNode.fatherId, currentPath);
  }

  const fullPath = findPath(row.fatherId, [row.channelName || '']);
  return fullPath.join('>');
}
function getLevelDescription(row: Api.government.ChannelVO): string {
  if (row.level === undefined || row.level < 0) {
    return '未知层级';
  }

  const levelMap: Record<number, string> = {
    0: '一级',
    1: '二级',
    2: '三级',
    3: '四级',
    4: '五级'
  };

  return `${levelMap[row.level] || `${row.level + 1}级`}企业`;
}
async function handleDelete(row: Api.government.ChannelVO) {
  await fetchDelChannel(row.id);
  refresh();
}
</script>

<template>
  <LayoutTable>
    <ZTable
      :columns="columns"
      :api="fetchGetChannelList"
      :immediate="false"
      @register="registerTable"
      @add="handleOpenModal"
    >
      <template #op="{ row }">
        <NButton v-if="row.level < 5" size="small" ghost type="primary" @click="addtwo(row)">
          添加{{ row.level + 1 }}级企业
        </NButton>
        <NButton size="small" ghost type="primary" @click="edit(row)">编辑</NButton>
        <NPopconfirm @positive-click="handleDelete(row)">
          <template #trigger>
            <NButton size="small" type="error" ghost :disabled="Boolean(row.staffCount)">删除</NButton>
          </template>
          确定删除吗？
        </NPopconfirm>
      </template>
    </ZTable>
    <BasicModelForm @register-modal-form="registerModalForm" @submit-form="handleSubmit"></BasicModelForm>
  </LayoutTable>
</template>

<style scoped></style>
