<template>
  <div class="cameraConfigGroup">
    <el-button
      type="primary"
      @click="createGroupDialog = true"
      style="margin: 10px 0;"
      v-permission="{ action: [PERM_ALGO.CONFIG_ADD_GROUP] }"
    >
      <img src="@/assets/images/create.png" style="margin-top: -1px; margin-right: 5px" />新建相机分组
    </el-button>
    <el-table
      :data="cameraGroupList"
      :span-method="objectSpanMethod"
      height="calc(100vh - 300px)"
      style="width: 100%; margin-top: 16px; --el-table-border-color: none"
      v-loading="loading"
      :row-class-name="tableRowClassName"
    >
      <el-table-column prop="id" label="组序号"  width="70"/>
      <el-table-column prop="cameraName" label="相机名称" align="center">
        <template #default="scope">
          <div class="cameraName-text" v-if="scope.row.isMainCamera === IsMainCamera.YES">
            <el-icon><Star color="Gold" /></el-icon>
            {{ scope.row.cameraName }}
          </div>
        </template>  
      </el-table-column>
      <el-table-column prop="cameraCode" label="设备ID"/>
      <el-table-column prop="location" label="地点"/>
      <el-table-column prop="algoName" label="算法">
        <template #default="scope">
          <div class="algoId-text" @click="handleView(scope.row)">
            {{ scope.row.algoName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="120px">
        <template #default="scope">
          <div class="operation">
            <el-tooltip effect="light" content="关闭/开启" placement="bottom">
              <el-switch 
                :model-value="scope.row.status" 
                :inactive-value="CameraGroupStatus.CLOSE"
                :active-value="CameraGroupStatus.OPEN"
                @update:model-value="(val) => handleSwitch(val, scope.row)"/>
            </el-tooltip>
            
            <el-tooltip effect="light" content="删除" placement="bottom">
              <img src="@/views/message/alarmMessages/img/delete.png" 
              @click="handleDelete(scope.row)" 
                v-permission="{ action: [PERM_ALGO.CONFIG_DELETE_GROUP] }"
              />
            </el-tooltip>
          </div>
        </template>
      </el-table-column>

      <template #empty>
        <div class="emptyDiv">
          <img src="@/assets/images/empty.png" class="emptyImg" />
          <span class="emptySpan">暂无数据</span>
        </div>
      </template>
    </el-table>
    <section class="mt-4 flex justify-end">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next"
        :page-sizes="[10, 30, 50]"
        :total="total"
        v-model:page-size="requestParams.pageSize"
        v-model:current-page="requestParams.pageNumber"
        @change="queryCameraGroupPage"
      />
    </section>
    <!-- </el-card> -->

    <!--删除弹窗 -->
    <el-dialog v-model="deleteDialog" width="424px" top="20%" class="deleteDialog">
      <template #header="">
        <div class="deleteDialogHeader">
          <img src="@/assets/images/deleteTip.png" class="deleteTip" />
          <span class="titleSpan">请确认删除该相机分组吗？</span>
        </div>
      </template>
      <span style="margin-left: 37px">删除之后，该组多相机检测将失效！</span>
      <div class="dialogBottom">
        <el-button class="dialogBtn" @click="deleteDialog = false">取消</el-button>
        <el-button class="dialogBtn" type="primary" @click="confirmDelete">确定</el-button>
      </div>
    </el-dialog>

    <!-- 新增相机分组弹窗 -->
    <el-dialog v-model="createGroupDialog" width="70%" top="15%" left="25%" class="deleteDialog" title="设置相机组" @close="handleCancle">
    <SettingCamera ref="settingCameraRef"/>
      <div class="dialogBottom">
        <el-button class="dialogBtn" @click="handleCancle">取消</el-button>
        <el-button class="dialogBtn" type="primary" @click="handleCreateGroup">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Star } from '@element-plus/icons-vue';
import useCameraGroupQuery from './hooks/useCameraGroupQuery';
import { CameraGroupTableItem, CameraGroupStatus, IsMainCamera } from '@/types/camera/camera-preview';
import { deleteDetectionGroup, updateGroupStatus, saveDetectionGroup } from '@/api/camera/camera-preview-group';
import SettingCamera from './components/SettingCamera.vue'
import { PERM_ALGO } from '@/types/permission/constants';

const router = useRouter();
const { requestParams, total, queryCameraGroupPage, cameraGroupList, loading } = useCameraGroupQuery();
const createGroupDialog = ref(false);
const deleteDialog = ref(false);
const cameraDetectionGroupId = ref();

const tableRowClassName = ({
  row,
}: {
  row: CameraGroupTableItem
}) => {
  // 根据分组ID计算颜色索引（使用模运算实现颜色循环）
  const groupColors = ['normal', 'active'];
  const groupId = row.cameraDetectionGroupId;
  return groupColors[groupId % 3];
}

const objectSpanMethod = ({
  row,
  rowIndex,
  columnIndex,
}) => {
  // 合并组序列和操作列
  if (columnIndex === 0 || columnIndex === 5) {
    const list = cameraGroupList.value;
    const groupId = row.cameraDetectionGroupId;
    const firstIndex = list.findIndex(item => item.cameraDetectionGroupId === groupId);
    
    if (rowIndex !== firstIndex) {
      return { rowspan: 0, colspan: 0 };
    }
    
    let rowCount = 0;
    for (let i = firstIndex; i < list.length; i++) {
      if (list[i].cameraDetectionGroupId === groupId) rowCount++;
      else break;
    }
    
    return {
      rowspan: rowCount,
      colspan: 1
    };
  }
};

const handleDelete = (row: CameraGroupTableItem) => {
  if (row.status === CameraGroupStatus.OPEN) {
    ElMessage({
      message: '开启状态的分组不可删除',
      type: 'warning',
      plain: true,
    });
  } else {
    deleteDialog.value = true;
    cameraDetectionGroupId.value = row.cameraDetectionGroupId;
  }
}

const handleSwitch = (newStatus: number, row: CameraGroupTableItem) => {
  const data = {
    cameraDetectionGroupId: row.cameraDetectionGroupId,
    status: newStatus,
  }
  updateGroupStatus(data).then(res => {
    ElMessage.success('操作成功')
    queryCameraGroupPage();
  })
}

const confirmDelete = () => {
  deleteDetectionGroup([Number(cameraDetectionGroupId.value)]).then(() => {
    ElMessage({
      message: '删除成功',
      type: 'success',
      plain: true,
    });
    deleteDialog.value = false;
    queryCameraGroupPage();
  })
  
}

const settingCameraRef = ref<InstanceType<typeof SettingCamera>>();
const handleCreateGroup = () => {
  const { valid, data } = settingCameraRef.value?.isValidate();
 
  if(valid) {
    // 执行提交逻辑
    const saveData = data.map(item => {
      return {
        cameraId: Number(item.code),
        algoId: Number(item.algoCode),
        isMainCamera: item.isMainCamera,
      }
    })
    
    saveDetectionGroup(saveData).then(() => {
      ElMessage({
        message: '相机组添加成功',
        type:'success',
        plain: true,
      });
      createGroupDialog.value = false;
      settingCameraRef.value?.clearForm();
      queryCameraGroupPage();
    })
  }
}

const handleCancle = () => {
  createGroupDialog.value = false
  settingCameraRef.value?.clearForm();
}

const handleView = (row: CameraGroupTableItem) => {
  router.push({
    path: '/algorithm/camera-group',
    query: {
      groupId: row.cameraDetectionGroupId,
      cameraId: row.cameraId
    }
  })
}

onMounted(() => {
  queryCameraGroupPage();
})
</script>

<style lang="scss" scoped>
  .emptyDiv {
    margin-top: 78px;
    margin: auto;
    width: 396px;
    .emptyImg {
      height: 257px;
    }
    .emptySpan {
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 18px;
      color: rgba(0, 0, 0, 0.45);
      text-align: left;
      font-style: normal;
    }
  }

  .algoId-text {
    cursor: pointer;
    color: #409eff;
  }

    .deleteDialog {
    .deleteDialogHeader {
      display: flex;
      .deleteTip {
        height: 24px;
        width: 24px;
      }
      
      .titleSpan {
        height: 24px;
        font-size: 16px;
        color: rgba(0, 0, 0, 0.88);
        line-height: 24px;
        text-align: center;
        margin-left: 12px;
      }
    }
    .dialogBottom {
      display: flex;
      justify-content: flex-end;
      margin-top: 12px;
    }
  }

  .operation {
    display: flex;
    align-items: center;

    img {
      margin-left: 20px;
    }
    
  }

 .el-table {
    :deep(.normal) {
      --el-table-tr-bg-color: #fff;
      &:hover {
        --el-table-tr-bg-color: #fff;
      }
    }
    :deep(.active) {
      --el-table-tr-bg-color: #fafafa;
      &:hover {
        --el-table-tr-bg-color: #fafafa;
      }
    }
  }

</style>
