<!-- eslint-disable vue/v-on-event-hyphenation -->
<template>
  <page-wrapper>
    <el-card :bordered="false" class="proCard" style="position: relative">
      <BasicTable
        :columns="colomns"
        :data-source="tableData"
        :row-key="(row) => row.name"
        :action-column="actionColumn"
        :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"
        style="height: 800px"
      >
        <template #tableTitle>
          <el-button type="primary" @click="companyAdd">
            <template #icon>
              <el-icon>
                <Plus />
              </el-icon>
            </template>
            添加
          </el-button>
        </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>

    <!-- 添加的抽屉内容 -->

    <!-- 公司 -->

    <CompanyDrawer
      ref="companyDrawerChild"
      :table-com="tableCom"
      :companyAddTitle="companyAddTitle"
      :comEdit="comEdit"
      :sceneList="sceneList"
      :templateList="templateList"
      :selectItems="selectItems"
      :addEnable="addEnable"
      :allCodes="allCodes"
      :editedItem="editedItem"
      @upload-company-data="addNewTypeCom"
      @edit-company-data="editedSubCom"
      @update-tab-com="handleUpdateTableCom"
    />

    <!-- 车间 -->

    <WorkshopDrawer
      ref="workshopDrawerChild"
      :table-workshop="tableWorkshop"
      :add-title="addTitle"
      :tag-list="tagList"
      :workshopTemplateList="workshopTemplateList"
      :add-enable="addEnable"
      :editWork="workshopEdit"
      :editedItem="editedItem"
      :allCodes="allCodes"
      @update-tab-com="handleUpdataWorkshopTab"
      @upload-work-data="addNewWorkshop"
      @edit-work-data="editedSubWorkshop"
    />

    <!-- 工位 -->

    <WorkspaceDrawer
      ref="workspaceDrawerChild"
      :tableWorkspace="tableWorkspace"
      :add-title="addTitle"
      :add-enable="addEnable"
      :editWork="workspaceEdit"
      :allCodes="allCodes"
      :editedItem="editedItem"
      @update-tab-com="handleUpdataWorkspaceTab"
      @upload-work-data="addNewWorkspace"
      @edit-work-data="editedSubWorkspace"
    />
  </page-wrapper>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive, h, watch, computed } from 'vue';
  import { Plus } from '@element-plus/icons-vue';
  import { BasicTable, BasicColumn } from '@/components/Table';
  import { ElMessageBox } from 'element-plus';
  import ActionColomn from './actionColomns.vue';
  import CompanyDrawer from './CompanyDrawer.vue';
  import WorkshopDrawer from './WorkshopDrawer.vue';
  import WorkspaceDrawer from './WorkspaceDrawer.vue';
  import { DATA_LEVEL, ENABLED } from './constant';
  import {
    colomns,
    dataSourceWithParent,
    updateSerials,
    findItemLevel,
    removeParent,
    flattenCodes,
  } from './use-method';
  import {
    ComAddDatas,
    delCompany,
    WorkshopAddDatas,
    delWorkshop,
    WorkspaceAddDatas,
    delWorkspace,
    LabelModuleListType,
    sortSceneList,
  } from '@/api/scene/sceneOperate';
  import useScene from './use-scene';
  import useSceneTemplete from './use-sence-templete';

  const useSceneList = useScene();
  const { tableData, getSceneDetail } = useSceneList;
  const useSceneTempleteDetail = useSceneTemplete();
  const { sceneList, templateList, workshopTemplateList } = useSceneTempleteDetail;

  // 新增类型的参数值
  const addEnable = ref(ENABLED.TRUE); //启动按钮的值

  //表格中的规则

  interface RuleForm {
    name: string; //名称
    seniorScene: string; //上级场景
    code: string; //代码
    sceneCode: string; //场景代码
    tagCom?: string[]; //公司场景标签 可选多个
    templateCom?: string[]; //公司场景模板 可选多个
    tagWorkshop?: number; //场景标签  车间
    templateWorkshop?: number; //车间模板
    principal?: string; //负责人
  }
  const ruleForm = reactive<RuleForm>({
    name: '',
    seniorScene: '',
    code: '',
    sceneCode: '',
    tagCom: [],
    templateCom: [],
    tagWorkshop: undefined,
    templateWorkshop: undefined,
    principal: '',
  });

  //添加组件的添加功能
  const tableWorkshop = ref(false); //车间的drawer开关
  const tableWorkspace = ref(false); //工位的drawer开关
  const tableCom = ref(false); //公司的drawer开关

  //改变el-drawer公司的状态
  const handleUpdateTableCom = (val: boolean) => {
    tableCom.value = val;
  };

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

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

  //公司el-drawer的标题
  const companyAddTitle = ref('');
  //是否公司编辑
  const comEdit = ref<boolean>(false);

  const addTitle = ref('');

  const level = ref<number>();

  onMounted(() => {
    //添加父级，主要用于排序功能
    dataSourceWithParent(tableData.value, null);
    //获取tableData数据
    getSceneDetail();
  });
  watch(
    () => tableData.value,
    () => {
      dataSourceWithParent(tableData.value, null);
    },
  );

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

  const orderByItem = () => {};
  const handlePageNumChange = () => {};
  const handlePageSizeChange = () => {};

  const companyDrawerChild = ref();
  const workshopDrawerChild = ref();
  const workspaceDrawerChild = ref();

  const companyAdd = () => {
    tableCom.value = true;
    if (companyDrawerChild.value) {
      companyDrawerChild.value.resetDrawCom(); // 这里假设resetDraw是子组件中用于重置的方法
    }
    addEnable.value = ENABLED.TRUE;
    // ruleForm.seniorScene = '顶级场景';
    companyAddTitle.value = '添加公司';
    comEdit.value = false;
  };

  //用于新增场景
  const selectItems = ref([{ tag: '', template: '' }] as { tag: string; template: string }[]);

  const allCodes = computed(() => {
    return flattenCodes(tableData.value);
  });

  //添加公司场景的提交按钮
  const addNewTypeCom = () => {
    getSceneDetail();
    tableCom.value = false;
  };

  //判断是否是车间的编辑
  const workshopEdit = ref<boolean>(true);
  //判断是否工位的编辑
  const workspaceEdit = ref<boolean>(true);

  //新增车间
  const addNewWorkshop = () => {
    getSceneDetail();
    tableWorkshop.value = false;
  };

  const addNewWorkspace = () => {
    getSceneDetail();
    tableWorkspace.value = false;
  };

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

  //页面设置函数
  const handleConfig = (row) => {
    console.log(row);
  };

  const handleAdd = (row) => {
    editedItem.value = { ...row }; // 将当前行的内容拷贝到 editedItem 中，以便编辑
    workshopEdit.value = false;
    workspaceEdit.value = false;
    //得出当前的数据的层级
    level.value = findItemLevel(tableData.value, row.id, row.name);

    if (level.value === DATA_LEVEL.first) {
      addTitle.value = '添加车间';
      tableWorkshop.value = true;
      workshopDrawerChild.value.receiveSeniorScene(row.name);
      workshopDrawerChild.value.resetDraw();
      tagList.value = row?.labelList;
    } else if (level.value === DATA_LEVEL.second) {
      console.log('22');
      addTitle.value = '添加工位';
      tableWorkspace.value = true;
      workspaceDrawerChild.value.receiveSeniorScene(row.name);
      workspaceDrawerChild.value.resetDraw();
    } else {
      return;
    }
  };

  //添加车间中的场景标签
  const tagList = ref<LabelModuleListType[]>([]);

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

  // 在这里实现删除行的函数
  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.first) {
            return delCompany(row.id);
          } else if (level.value === DATA_LEVEL.second) {
            return delWorkshop(row.id);
          } else {
            return delWorkspace(row.id);
          }
        })
        .catch(() => {
          console.log('取消删除物件');
        })
        .finally(() => {
          getSceneDetail();
        });
    }
  };

  const handleEdit = (row) => {
    editedItem.value = { ...row }; // 将当前行的内容拷贝到 editedItem 中，以便编辑
    workshopEdit.value = true;
    workspaceEdit.value = true;
    level.value = findItemLevel(tableData.value, row.id, row.name);
    if (level.value === DATA_LEVEL.first) {
      tableCom.value = true;
      companyAddTitle.value = '编辑公司';
      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,
        }));
      }

      companyDrawerChild.value.receiveDataFromParent(editedItem.value, selectItems.value);
    } else if (level.value === DATA_LEVEL.second) {
      addTitle.value = '编辑车间';
      tableWorkshop.value = true;
      ruleForm.name = editedItem.value.name!;
      //使用ts 类型守卫
      ruleForm.seniorScene = editedItem.value.parent.name;
      ruleForm.code = editedItem.value.code!;
      addEnable.value = editedItem.value.status!;
      tagList.value = editedItem.value.parent?.labelList;
      ruleForm.tagWorkshop = editedItem.value.sceneLabelId;
      ruleForm.templateWorkshop = editedItem.value.workshopModule.id;
      // console.log('ruleForm.seniorScene', ruleForm.seniorScene);

      workshopDrawerChild.value.receiveDataFromParent(ruleForm, addEnable.value);
    } else if (level.value === DATA_LEVEL.third) {
      addTitle.value = '编辑工位';
      // addName.value = '工位名称';
      // addCodeName.value = '工位代码';
      tableWorkspace.value = true;
      ruleForm.name = editedItem.value.name!;
      ruleForm.seniorScene = editedItem.value.parent.name;
      ruleForm.code = editedItem.value.code!;
      addEnable.value = editedItem.value.status!;
      ruleForm.principal = (editedItem.value as WorkspaceAddDatas).principal!;
      workspaceDrawerChild.value.receiveDataFromParent(ruleForm, addEnable.value);
    }
  };

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

  //编辑公司的提交按钮
  const editedSubCom = () => {
    getSceneDetail();
    tableCom.value = false;
  };

  //编辑车间的提交按钮
  const editedSubWorkshop = () => {
    getSceneDetail();
    tableWorkshop.value = false;
  };

  //编辑工位的提交按钮
  const editedSubWorkspace = () => {
    getSceneDetail();
    tableWorkspace.value = false;
  };

  //向上排序
  const rowUp = (row) => {
    if (row.parent) {
      const parentIndex = row.parent.children!.indexOf(row);
      if (parentIndex > 0) {
        const previousRow = row.parent.children![parentIndex - 1];
        // 进行交换位置
        row.parent.children!.splice(parentIndex - 1, 2, row, previousRow);
      }
    } else {
      const index = tableData.value.indexOf(row);
      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!.indexOf(row);
      if (parentIndex < row.parent.children?.length - 1) {
        const behindRow = row.parent.children![parentIndex + 1];
        // 进行交换位置
        row.parent.children!.splice(parentIndex, 2, behindRow, row);
      }
    } else {
      const index = tableData.value.indexOf(row);
      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>
  .tag-select {
    margin-right: 10px;
    margin-bottom: 10px;
    border-radius: 4px;
    border: 1px solid rgba(0, 0, 0, 0.15);
  }
</style>
