<template>
  <page-wrapper>
    <el-card :bordered="false" class="proCard">
      <BasicTable
        :columns="colomns"
        :data-source="showTableData"
        :row-key="(row) => row.code"
        :action-column="actionColumn"
        :expend-row="expendRowKeys"
        :pagination="{ total: total, pageSize: size, hideOnSinglePage: false }"
        :tableSetting="{
          width: 200,
          size: false,
          redo: false,
          fullscreen: false,
          striped: false,
          setting: false,
        }"
        ref="tableRef"
        @checked-row-change="onCheckedRow"
        @order-change="orderByItem"
        @page-num-change="handlePageNumChange"
        @page-size-change="handlePageSizeChange"
      >
        <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"
        :allCodes="allCodes"
        @on-ok="subCompany"
        @on-close="handleUpdateTableCom"
      />
      <!-- 车间 -->
      <WorkshopDrawer_shangfei
        v-if="showDrawer === DrawerType.workshop"
        :workshopTemplateList="workshopTemplateList"
        :detail="detail"
        :allCodes="allCodes"
        @on-close="handleUpdataWorkshopTab"
        @on-ok="subWorkshop"
      />
      <!-- 工位 -->
      <WorkspaceDrawer_shangfei
        v-if="showDrawer === DrawerType.workspace"
        :allCodes="allCodes"
        :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"
        :allCodes="allCodes"
        @on-ok="subCompany"
        @on-close="handleUpdateTableCom" />
      <!-- 车间 -->
      <WorkshopDrawer
        v-if="showDrawer === DrawerType.workshop"
        :workshopTemplateList="workshopTemplateList"
        :detail="detail"
        :allCodes="allCodes"
        @on-close="handleUpdataWorkshopTab"
        @on-ok="subWorkshop" />

      <!-- 工位 -->
      <WorkspaceDrawer
        v-if="showDrawer === DrawerType.workspace"
        :allCodes="allCodes"
        :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 } 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-method';
  import { delCompany, delWorkshop, delWorkspace, sortSceneList } from '@/api/scene/scene';
  import { ComAddDatas, WorkshopAddDatas, WorkspaceAddDatas } from '@/types/scene/type.ts';
  import useScene from './hook/use-scene';
  import useSceneTemplete from './hook/use-sence-templete';
  import { useRouter } from 'vue-router';
  import { storeToRefs } from 'pinia';
  import { cloneDeep } from 'lodash-es';
  import { ElMessageBox } from 'element-plus';
  import { useGlobSetting } from '@/hooks/setting';

  const globSetting = useGlobSetting();
  const disableDepartmentEdit = globSetting.disableDepartmentEdit;

  const router = useRouter();

  const useSceneList = useScene();
  const { tableData } = storeToRefs(useSceneList);
  const { getSceneDetail } = useSceneList;
  const useSceneTempleteDetail = useSceneTemplete();
  const { sceneList, templateList, workshopTemplateList } = useSceneTempleteDetail;
  const expendRowKeys = ref(['']);

  const showDrawer = ref<DrawerType | null>(null);
  const showTableData = computed(() => {
    const temp = cloneDeep(tableData.value);
    return temp.splice((page.value - 1) * size.value, page.value * size.value);
  });

  const page = ref(1);
  const size = ref(10);
  const total = computed(() => tableData.value.length);
  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(() => {
    //添加父级，主要用于排序功能
    //dataSourceWithParent(tableData.value, null);
    //获取tableData数据
    getSceneDetail();
    // getCompanyList().then((res) => {
    //   companyList.value = res;
    // });
  });

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

  const orderByItem = () => {};
  const handlePageNumChange = (pageNum) => {
    page.value = pageNum;
  };
  const handlePageSizeChange = (pageSize) => {
    size.value = pageSize;
  };

  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(tableData.value);
  });

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

  const subWorkspace = () => {
    getSceneDetail();
    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,
        handleConig: handleConfig,
        handleAdd: handleAdd,
        handleEdit: handleEdit,
        handleDelete: handleDelete,
        handleUp: rowUp,
        handleDown: rowDown,
      });
    },
  });

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

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

  const handleAdd = (row) => {
    editedItem.value = { ...row }; // 将当前行的内容拷贝到 editedItem 中，以便编辑
    //得出当前的数据的层级
    level.value = findItemLevel(tableData.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;
    }
  };

  //公司，车间，工位的模板数据
  const editedItem = ref<ComAddDatas | WorkshopAddDatas | WorkspaceAddDatas | null>(null);

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

  // 在这里实现删除行的函数
  const handleDelete = (row: Recordable) => {
    level.value = findItemLevel(tableData.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(() => {
          getSceneDetail();
        });
    }
  };

  const handleEdit = (row) => {
    editedItem.value = { ...row } as ComAddDatas; // 将当前行的内容拷贝到 editedItem 中，以便编辑
    level.value = findItemLevel(tableData.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 = () => {
    getSceneDetail();
    showDrawer.value = null;
  };

  //向上排序
  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(tableData.value, previousRow.parent.code);
        // 进行交换位置
        targetParent.children!.splice(parentIndex - 1, 2, row, previousRow);
      }
    } else {
      const index = tableData.value.findIndex((item) => item.id === row.id);
      if (index > 0) {
        tableData.value.splice(index - 1, 2, row, tableData.value[index - 1]);
      }
    }
    tableData.value = updateSerials(tableData.value);
    sortSceneList(removeParent(tableData.value))
      .then(() => {
        getSceneDetail();
      })
      .catch((...e) => {
        console.error('catch error', ...e);
      });
  };

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

    sortSceneList(removeParent(tableData.value))
      .then(() => {
        getSceneDetail();
      })
      .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>
