<template>
  <page-wrapper>
    <el-card :bordered="false" class="proCard">
      <!-- row-key 属性，用于设置树形表格的行键，默认为id，这里设置为code，保证唯一性 不能为空字符串 -->
      <BasicTable
        :columns="colomns"
        :data-source="comTreeData"
        :row-key="(row) => row.uniqueCode"
        :action-column="actionColumn"
        :expend-row="expendRowKeys"
        :tableSetting="{
          width: 200,
          size: false,
          redo: false,
          fullscreen: false,
          striped: false,
          setting: false,
        }"
        ref="tableRef"
        @checked-row-change="onCheckedRow"
        @order-change="orderByItem"
      >
        <template #tableTitle>
          <div>
            <el-button type="primary" @click="companyAdd" style="margin-right: 40px">
              <template #icon>
                <el-icon>
                  <Plus />
                </el-icon>
              </template>
              添加公司
            </el-button>
          </div>
        </template>
        <template #empty>
          <div class="empty-content flex flex-col items-center">
            <img src="@/assets/icons/no-content.png" class="empty-img" />
            <span class="empty-text">目前无内容，请先添加公司</span>
          </div>
        </template>
      </BasicTable>
    </el-card>

    <div v-if="disableDepartmentEdit">
      <!-- 上飞定制的抽屉表单 -->
      <!-- 公司 -->
      <CompanyDrawer_shangfei
        v-if="showDrawer === DrawerType.company"
        :comEdit="comEdit"
        :sceneList="sceneList"
        :templateList="templateList"
        :detail="detail"
        @on-ok="subCompany"
        @on-close="handleUpdateTableCom"
      />
      <!-- 车间 -->
      <WorkshopDrawer_shangfei
        v-if="showDrawer === DrawerType.workshop"
        :workshopTemplateList="workshopTemplateList"
        :detail="detail"
        @on-close="handleUpdataWorkshopTab"
        @on-ok="subWorkshop"
      />
      <!-- 工位 -->
      <WorkspaceDrawer_shangfei
        v-if="showDrawer === DrawerType.workspace"
        :detail="detail"
        @on-close="handleUpdataWorkspaceTab"
        @on-ok="subWorkspace"
      />
    </div>
    <div v-else>
      <!-- 其他项目的抽屉表单 -->
      <!-- 公司 -->
      <CompanyDrawer
        v-if="showDrawer === DrawerType.company"
        :comEdit="comEdit"
        :sceneList="sceneList"
        :templateList="templateList"
        :detail="detail"
        @on-ok="subCompany"
        @on-close="handleUpdateTableCom" />
      <!-- 车间 -->
      <WorkshopDrawer
        v-if="showDrawer === DrawerType.workshop"
        :workshopTemplateList="workshopTemplateList"
        :detail="detail"
        @on-close="handleUpdataWorkshopTab"
        @on-ok="subWorkshop" />

      <!-- 工位 -->
      <WorkspaceDrawer
        v-if="showDrawer === DrawerType.workspace"
        :detail="detail"
        @on-close="handleUpdataWorkspaceTab"
        @on-ok="subWorkspace"
    /></div>

    <!-- 用于渝北项目政府租户绑定企业 -->
    <SceneDialog v-if="dialogVisible" @close-dialog="closeDialog" />
  </page-wrapper>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive, h, computed, Ref } from 'vue';
  import { Plus } from '@element-plus/icons-vue';
  import { BasicTable, BasicColumn } from '@/components/Table';
  import ActionColomn from './components/ActionColomns.vue';
  import CompanyDrawer from './components/CompanyDrawer.vue';
  import CompanyDrawer_shangfei from './components/CompanyDrawer-shangfei.vue';
  import WorkshopDrawer from './components/WorkshopDrawer.vue';
  import WorkshopDrawer_shangfei from './components/WorkshopDrawer-shangfei.vue';
  import WorkspaceDrawer from './components/WorkspaceDrawer.vue';
  import WorkspaceDrawer_shangfei from './components/WorkspaceDrawer-shangfei.vue';
  import { DATA_LEVEL, DrawerType, ENABLED } from '@/types/scene/constant.ts';
  import SceneDialog from './components/SceneDialog.vue';
  import {
    colomns,
    // updateSerials,
    // findItemLevel,
    // removeParent,
    // flattenCodes,
    // getParent,
  } from './hook/use-table-method';
  // import {
  //   delCompany,
  //   delWorkshop,
  //   delWorkspace,
  //   updateComShopSpaceTreeSort,
  // } from '@/api/scene/scene';
  import {
    // ComAddDatas,
    // WorkshopAddDatas,
    // WorkspaceAddDatas,
    UseComType,
    UseWorkshopType,
    UseWorkspaceType,
  } from '@/types/scene/type.ts';
  import useComTree from './store/use-com-tree';
  import useSceneTemplete from './hook/use-sence-templete';
  import { storeToRefs } from 'pinia';
  // import { ElMessageBox } from 'element-plus';
  import { useGlobSetting } from '@/hooks/setting';

  // 此处获取了全局变量，关系到用不用sf定制的组件
  const globSetting = useGlobSetting();
  const disableDepartmentEdit = globSetting.disableDepartmentEdit;

  // 公司车间工位数据
  const comTree = useComTree();
  const { comTreeData } = storeToRefs(comTree);

  const { getComTreeDetail } = comTree;
  const useSceneTempleteDetail = useSceneTemplete();
  const { sceneList, templateList, workshopTemplateList } = useSceneTempleteDetail;
  const expendRowKeys = ref(['']);

  const showDrawer = ref<DrawerType | null>(null);

  const dialogVisible = ref<boolean>(false);

  const closeDialog = () => {
    dialogVisible.value = false;
  };

  // 改变el-drawer公司的状态
  const handleUpdateTableCom = () => {
    showDrawer.value = null;
  };

  // 改变el-drawer车间的状态
  const handleUpdataWorkshopTab = () => {
    showDrawer.value = null;
  };

  // 改变el-drawer工位的状态
  const handleUpdataWorkspaceTab = () => {
    showDrawer.value = null;
  };

  // 判断是否为公司编辑
  const comEdit = ref<boolean>(false);

  // const level = ref<number>();

  onMounted(() => {
    //获取公司树数据
    getComTreeDetail();
  });

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  const orderByItem = (rowKeys) => {
    console.log(rowKeys);
  };

  /**
   * 新建公司时的表单初始化
   * @modifications
   *  - 2025-01-09: Yunfeng
   *  - V4-平台权限重构
   */
  const companyAdd = () => {
    showDrawer.value = DrawerType.company;
    detail.value = {
      seniorScene: '顶级场景',
      selectItems: [{ tag: '', template: '' }],
      addEnable: ENABLED.TRUE,
      name: '',
      code: '',
    };
    comEdit.value = false;
  };

  // 用于新增场景
  // const selectItems = ref([{ tag: '', template: '' }] as { tag: string; template: string }[]);
  // const allCodes = computed(() => {
  //   return flattenCodes(comTreeData.value);
  // });

  //新增车间
  const subWorkshop = () => {
    getComTreeDetail();
    showDrawer.value = null;
  };

  const subWorkspace = () => {
    getComTreeDetail();
    showDrawer.value = null;
  };

  //操作列
  const actionColumn: BasicColumn = reactive({
    width: 360,
    label: '操作',
    prop: 'booking',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(ActionColomn, {
        // rowUpDisable:
        // rowDownDisable:
        subItem: record.row,
        handleRelate: handleRelate,
        // handleConfig: handleConfig,
        handleAdd: handleAdd,
        handleEdit: handleEdit,
        handleDelete: handleDelete,
        handleUp: rowUp,
        handleDown: rowDown,
      });
    },
  });

  //绑定
  const handleRelate = (row) => {
    console.log(row);
    dialogVisible.value = true;
  };

  //公司，车间，工位的模板数据
  // const editedItem: Ref<(ComAddDatas & WorkshopAddDatas & WorkspaceAddDatas) | undefined> = ref();
  const editedItem: Ref<
    (UseComType<undefined> & UseWorkshopType<undefined> & UseWorkspaceType) | undefined
  > = ref();

  //点击所有添加和编辑时显示的数据内容
  const detail = ref({});

  // 点击添加时
  const handleAdd = (row) => {
    console.log(row);
  };

  // 点击编辑时
  const handleEdit = (row) => {
    editedItem.value = { ...row }; // 将当前行的内容拷贝到 editedItem 中，以便编辑
    console.log(row);
  };

  // 点击删除时
  const handleDelete = (row) => {
    console.log(row);
  };

  // 点击上移时
  const rowUp = (row) => {
    console.log(row);
  };

  // 点击下移时
  const rowDown = (row) => {
    console.log(row);
  };

  //页面设置函数 Deprecated in V4
  // const handleConfig = (row) => {
  //   router.push({
  //     path: '/page-config/config',
  //     query: { companyId: row.id },
  //   });
  // };

  // TODO 处理添加
  // const handleAdd = (row) => {
  //   editedItem.value = { ...row }; // 将当前行的内容拷贝到 editedItem 中，以便编辑
  //   //得出当前的数据的层级
  //   level.value = findItemLevel(comTreeData.value, row.id, row.name);
  //   if ((expendRowKeys.value[0] = row.name)) {
  //     expendRowKeys.value[0] = '';
  //   }
  //   expendRowKeys.value[0] = row.name;
  //   if (level.value === DATA_LEVEL.company) {
  //     showDrawer.value = DrawerType.workshop;
  //     detail.value = {
  //       id: editedItem.value?.id,
  //       seniorScene: editedItem.value?.name,
  //       tagList: row?.labelList,
  //       addEnable: ENABLED.TRUE,
  //       name: '',
  //       code: '',
  //       tagWorkshop: null,
  //       templateWorkshop: null,
  //     };
  //   } else if (level.value === DATA_LEVEL.workshop) {
  //     detail.value = {
  //       id: editedItem.value?.id,
  //       seniorScene: editedItem.value?.name,
  //       addEnable: ENABLED.TRUE,
  //       name: '',
  //       code: '',
  //       principal: '',
  //     };
  //     if (disableDepartmentEdit) detail.value['workshopCode'] = editedItem.value?.code;
  //     showDrawer.value = DrawerType.workspace;
  //   }
  // };

  // TODO 在这里实现删除行的函数
  // const handleDelete = (row: Recordable) => {
  //   level.value = findItemLevel(comTreeData.value, row.id, row.name);
  //   if (row.children?.length > 0) {
  //     ElMessageBox.confirm('存在下级场景，无法删除该场景', '无法删除该条信息', {
  //       confirmButtonText: '确认',
  //       cancelButtonText: '取消',
  //       type: 'error',
  //     })
  //       .then(() => {
  //         console.log('存在子集');
  //       })
  //       .catch(() => {
  //         console.log('取消删除物件');
  //       });
  //   } else {
  //     ElMessageBox.confirm('确认要删除该场景吗', {
  //       confirmButtonText: '确认',
  //       cancelButtonText: '取消',
  //       type: 'warning',
  //     })
  //       .then(() => {
  //         //删除接口的调用
  //         if (level.value === DATA_LEVEL.company) {
  //           return delCompany(row.id);
  //         } else if (level.value === DATA_LEVEL.workshop) {
  //           return delWorkshop(row.id);
  //         } else {
  //           return delWorkspace(row.id);
  //         }
  //       })
  //       .catch(() => {
  //         console.log('取消删除物件');
  //       })
  //       .finally(() => {
  //         getComTreeDetail();
  //       });
  //   }
  // };

  /**
   * TODO
   * 处理公司/车间/工位编辑表单数据的初始化
   * @modifications
   *  - 2025-01-09: Yunfeng
   *  - V4-平台权限重构
   */
  // const handleEdit = (row) => {
  //   editedItem.value = { ...row }; // 将当前行的内容拷贝到 editedItem 中，以便编辑
  //   level.value = findItemLevel(comTreeData.value, row.id, row.name);
  //   if (level.value === DATA_LEVEL.company) {
  //     showDrawer.value = DrawerType.company;
  //     comEdit.value = true;
  //     //复原公司选择的场景集合
  //     if (row.labelList && Array.isArray(row.labelList)) {
  //       selectItems.value = row.labelList.map((item, index) => ({
  //         tag: item.id,
  //         template: row.moduleList[index]?.id,
  //       }));
  //     }
  //     detail.value = {
  //       id: editedItem.value?.id,
  //       name: editedItem.value!.name,
  //       code: editedItem.value!.code,
  //       seniorScene: '顶级场景',
  //       addEnable: editedItem.value!.status,
  //       selectItems: selectItems.value,
  //       remark: editedItem.value?.remark,
  //       longitude: editedItem.value?.longitude!,
  //       latitude: editedItem.value?.latitude!,
  //       regionCode: editedItem.value?.regionCode,
  //       thumbnail: editedItem.value?.thumbnail,
  //     };
  //   } else if (level.value === DATA_LEVEL.workshop && 'companyId' in editedItem.value!) {
  //     showDrawer.value = DrawerType.workshop;
  //     detail.value = {
  //       id: editedItem.value.id,
  //       name: editedItem.value.name,
  //       code: editedItem.value.code,
  //       seniorScene: editedItem.value.parent?.name || '',
  //       tagWorkshop: editedItem.value.sceneLabelId,
  //       templateWorkshop: editedItem.value.workshopModule?.id,
  //       addEnable: editedItem.value.status,
  //       tagList: editedItem.value.parent?.labelList || [],
  //       companyId: editedItem.value.companyId,
  //     };
  //   } else if (level.value === DATA_LEVEL.workspace && 'workshopId' in editedItem.value!) {
  //     detail.value = {
  //       id: editedItem.value.id,
  //       name: editedItem.value.name,
  //       code: editedItem.value.code,
  //       seniorScene: editedItem.value.parent?.name || '',
  //       principal: editedItem.value.principal,
  //       addEnable: editedItem.value.status,
  //     };

  //     showDrawer.value = DrawerType.workspace;
  //   }
  // };

  //编辑时的提交按钮功能

  //编辑公司的提交按钮
  const subCompany = () => {
    getComTreeDetail();
    showDrawer.value = null;
  };

  // TODO 向上排序
  // const rowUp = (row) => {
  //   if (row.parent) {
  //     const parentIndex = row.parent.children!.findIndex((item) => item.id === row.id);
  //     if (parentIndex > 0) {
  //       const previousRow = row.parent.children![parentIndex - 1];
  //       const targetParent = getParent(comTreeData.value, previousRow.parent.code);
  //       // 进行交换位置
  //       targetParent.children!.splice(parentIndex - 1, 2, row, previousRow);
  //     }
  //   } else {
  //     const index = comTreeData.value.findIndex((item) => item.id === row.id);
  //     if (index > 0) {
  //       comTreeData.value.splice(index - 1, 2, row, comTreeData.value[index - 1]);
  //     }
  //   }
  //   comTreeData.value = updateSerials(comTreeData.value);
  //   updateComShopSpaceTreeSort(removeParent(comTreeData.value))
  //     .then(() => {
  //       getComTreeDetail();
  //     })
  //     .catch((...e) => {
  //       console.error('catch error', ...e);
  //     });
  // };

  // TODO 向下排序
  // const rowDown = (row) => {
  //   if (row.parent) {
  //     const parentIndex = row.parent.children!.findIndex((item) => item.id === row.id);
  //     if (parentIndex < row.parent.children?.length - 1) {
  //       const behindRow = row.parent.children![parentIndex + 1];
  //       const targetParent = getParent(comTreeData.value, behindRow.parent.code);
  //       // 进行交换位置
  //       targetParent.children!.splice(parentIndex, 2, behindRow, row);
  //     }
  //   } else {
  //     const index = comTreeData.value.findIndex((item) => item.id === row.id);
  //     if (index < comTreeData.value.length - 1) {
  //       comTreeData.value.splice(index, 2, comTreeData.value[index + 1], row);
  //     }
  //   }
  //   comTreeData.value = updateSerials(comTreeData.value);

  //   updateComShopSpaceTreeSort(removeParent(comTreeData.value))
  //     .then(() => {
  //       getComTreeDetail();
  //     })
  //     .catch((...e) => {
  //       console.error('catch error', ...e);
  //     });
  // };
</script>

<style scoped>
  .proCard {
    position: relative;
    height: calc(100vh - 64px - 12px);
  }

  .tag-select {
    margin-right: 10px;
    margin-bottom: 10px;
    border-radius: 4px;
    border: 1px solid rgba(0, 0, 0, 0.15);
  }

  .relate-select {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }

  .select-title {
    width: 100px;
    margin-right: 20px;
  }
</style>
