<template>
  <div>
    <QueryForm :algos-info="algosInfo" @on-search="handleQueryTableData" @on-reset="handleResetTableData" />
    <div v-if="showActionBar" class="action-bar">
      <span class="num-text">已选{{ chooseNum }}项</span>
      <el-button :class="isAlgoAdd ? 'btn-active' : 'btn-normal'" @click="handleAlgosAdd" v-if="hasAddPermission()"
        >算法添加</el-button
      >
      <el-button
        :class="isParamsSet ? 'btn-active' : 'btn-normal'"
        @click="handleParamsSet"
        v-if="hasParamSetPermission()"
        >参数设置</el-button
      >
      <el-button :class="isAlgoOpen ? 'btn-active' : 'btn-normal'" @click="handleAlgosOpen">算法开启</el-button>
      <el-button :class="isAlgoClose ? 'btn-active' : 'btn-normal'" @click="handleAlgosClose">算法关闭</el-button>
      <el-button
        :class="isAlgoDelete ? 'btn-active' : 'btn-normal'"
        @click="handleAlgosDel"
        v-if="hasDeletePermission()"
        >算法删除</el-button
      >
      <span class="close-btn" @click="handleSelectNone"></span>
    </div>
    <SingleCameraTable
      ref="singleCameraTableRef"
      class="table-bar"
      :table-data="tableData"
      @on-filter="handleFilterTable"
      @on-reset="handleResetTable"
      @on-refresh="getTableData"
      @update:selection="handlePop"
    />
    <Pagination
      v-model:page="tableQueryParams.pageNumber"
      v-model:size="tableQueryParams.pageSize"
      :total="total"
      @update:page="handlePageChange"
      @update:size="handleSizeChange"
      style="margin-bottom: 0"
    />
    <BatchOperationDialog
      v-if="batchOperationVisible"
      :type="batchOperationType"
      :camera-ids="chooseId"
      :all-algo-list="algosInfo"
      @on-confirm="handleConfirmBatchOperation"
      @on-close="handleCloseBatchOperation"
    />
    <el-dialog
      v-model="isBatchParamSetVisible"
      width="1022"
      align-center
      :close-on-click-modal="false"
      @close="handleCancel"
    >
      <template #header>
        <div class="batch-param-set-header">
          <div class="algo-title">{{ selectedAlgoDetail?.name }}</div>
          <div class="set-tips">
            <el-icon :size="15"><InfoFilled /></el-icon>
            <div class="tip"
              >当前显示默认参数值，请选择具体参数进行修改，提交后新参数值将对所选全部相机生效，覆盖原有参数值</div
            >
          </div>
        </div>
      </template>
      <AlgoParamsSetting
        v-if="selectedAlgoDetail"
        :algo-detail="selectedAlgoDetail"
        @on-submit="handleSubmit"
        @on-cancel="handleCancel"
      />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, ref } from 'vue';
  import { ElButton, ElIcon, ElMessage, ElDialog } from 'element-plus';
  import { InfoFilled } from '@element-plus/icons-vue';
  import {
    QueryCameraPageByAlgoParams,
    QueryCameraPageByAlgoRes,
    getCameraListByAlgo,
    QueryAlgoInfoRes,
    getAlgosInfo,
    addAlgosByBatch,
    deleteAlgosByBatch,
    updateAlgosStatusByBatch,
    updateAlgosByBatch,
  } from '@/api/camera/camera-config';
  import QueryForm from './QueryForm.vue';
  import SingleCameraTable from './SingleCameraTable.vue';
  import Pagination from '@/components/Pagination/Pagination.vue';
  import BatchOperationDialog from './BatchOperationDialog.vue';
  import AlgoParamsSetting from '@/modules/algo/algo-params-edit/index.vue';
  import { CameraAlgoItemInCard } from '@/modules/algo/algo-params-edit/types';
  import { createAlgoSubmitParams, algoDetailToJSON } from '@/modules/algo/algo-params-edit/utils';
  import { useUserStore } from '@/store/modules/user';
  import { PERM_ALGO } from '@/types/permission/constants';

  const userStore = useUserStore();

  // 权限设置
  const hasAddPermission = () => {
    return userStore.checkPermission(PERM_ALGO.CONFIG_ADD);
  };
  const hasDeletePermission = () => {
    return userStore.checkPermission(PERM_ALGO.CONFIG_DELETE);
  };
  const hasParamSetPermission = () => {
    return userStore.checkPermission(PERM_ALGO.CONFIG_PARAM);
  };

  const tableQueryParams = ref<QueryCameraPageByAlgoParams>({
    pageNumber: 1,
    pageSize: 10,
    queryParam: {},
  });

  const algosInfo = ref<QueryAlgoInfoRes[]>([]);
  const singleCameraTableRef = ref<typeof SingleCameraTable>();
  const tableData = ref<QueryCameraPageByAlgoRes[]>([]);
  const total = ref(0);
  // 多选相机 批量操作
  const showActionBar = ref(false);
  const chooseNum = ref(0);
  const chooseRow = ref<QueryCameraPageByAlgoRes[]>([]); // 被选中的数据行
  const chooseId = ref<number[]>([]);
  // 按钮点击激活状态
  const isAlgoAdd = ref(false);
  const isParamsSet = ref(false);
  const isAlgoClose = ref(false);
  const isAlgoOpen = ref(false);
  const isAlgoDelete = ref(false);
  const batchOperationType = ref('');
  const batchOperationVisible = ref(false);
  // 批量参数设置
  const isBatchParamSetVisible = ref(false);
  const selectedAlgoDetail = ref<CameraAlgoItemInCard>(); // 批量参数设置组件的参数

  // 查询
  const handleQueryTableData = (queryParams) => {
    tableQueryParams.value.queryParam.cameraName = queryParams.queryParam.cameraName;
    tableQueryParams.value.queryParam.cameraCode = queryParams.queryParam.cameraCode;
    tableQueryParams.value.queryParam.workspaceIdList = queryParams.queryParam.workspaceIdList;
    tableQueryParams.value.queryParam.algoId = queryParams.queryParam.algoId;
    tableQueryParams.value.pageNumber = 1;
    tableQueryParams.value.pageSize = 10;
    getTableData();
  };
  // 重置 (清空查询条件, 不清空筛选条件)
  const handleResetTableData = () => {
    Reflect.deleteProperty(tableQueryParams.value.queryParam, 'cameraName');
    Reflect.deleteProperty(tableQueryParams.value.queryParam, 'cameraCode');
    Reflect.deleteProperty(tableQueryParams.value.queryParam, 'workspaceIdList');
    Reflect.deleteProperty(tableQueryParams.value.queryParam, 'algoId');
    tableQueryParams.value.pageNumber = 1;
    tableQueryParams.value.pageSize = 10;
    getTableData();
  };

  // 筛选
  const handleFilterTable = (type: string, opened: boolean, closed: boolean) => {
    // 为了在筛选时 保留 查询条件，将筛选处理放在此处
    if (type === 'algo') {
      if (opened && !closed) {
        tableQueryParams.value.queryParam.isAlgoDisabled = false;
      } else if (!opened && closed) {
        tableQueryParams.value.queryParam.isAlgoDisabled = true;
      } else {
        Reflect.deleteProperty(tableQueryParams.value.queryParam, 'isAlgoDisabled');
      }
    }
    if (type === 'render') {
      if (opened && !closed) {
        tableQueryParams.value.queryParam.isRenderDisabled = false;
      } else if (!opened && closed) {
        tableQueryParams.value.queryParam.isRenderDisabled = true;
      } else {
        Reflect.deleteProperty(tableQueryParams.value.queryParam, 'isRenderDisabled');
      }
    }
    tableQueryParams.value.pageNumber = 1;
    tableQueryParams.value.pageSize = 10;
    getTableData();
  };
  // 清空筛选 (不清空查询条件)
  const handleResetTable = (type: string) => {
    if (type === 'algo') {
      Reflect.deleteProperty(tableQueryParams.value.queryParam, 'isAlgoDisabled');
    }
    if (type === 'render') {
      Reflect.deleteProperty(tableQueryParams.value.queryParam, 'isRenderDisabled');
    }
    tableQueryParams.value.pageNumber = 1;
    tableQueryParams.value.pageSize = 10;
    getTableData();
  };

  // 多选
  const handlePop = (selection) => {
    chooseRow.value = selection;
    chooseId.value = [];
    selection.forEach((item) => {
      if (chooseId.value.indexOf(item.cameraId) === -1) chooseId.value.push(item.cameraId);
    });
    chooseNum.value = selection.length;
    showActionBar.value = chooseNum.value > 0 ? true : false;
  };
  // 取消多选
  const handleSelectNone = () => {
    chooseId.value = [];
    chooseNum.value = 0;
    singleCameraTableRef.value?.clearAll();
    showActionBar.value = false;
    handleResetBtnStatus();
  };
  // 重置按钮点击状态
  function handleResetBtnStatus() {
    isAlgoAdd.value = false;
    isParamsSet.value = false;
    isAlgoClose.value = false;
    isAlgoOpen.value = false;
    isAlgoDelete.value = false;
  }

  // 批量操作
  const handleAlgosAdd = () => {
    isAlgoAdd.value = true;
    batchOperationType.value = 'add';
    batchOperationVisible.value = true;
  };
  const handleParamsSet = () => {
    isParamsSet.value = true;
    batchOperationType.value = 'set';
    batchOperationVisible.value = true;
  };
  const handleAlgosOpen = () => {
    isAlgoOpen.value = true;
    batchOperationType.value = 'open';
    batchOperationVisible.value = true;
  };
  const handleAlgosClose = () => {
    isAlgoClose.value = true;
    batchOperationType.value = 'close';
    batchOperationVisible.value = true;
  };
  const handleAlgosDel = () => {
    isAlgoDelete.value = true;
    batchOperationType.value = 'delete';
    batchOperationVisible.value = true;
  };
  // 批量操作弹窗
  const handleConfirmBatchOperation = (algoIds) => {
    if (batchOperationType.value === 'add') {
      addAlgosByBatch({ cameraIdList: chooseId.value, algoIdList: algoIds }).then(() => {
        ElMessage({ type: 'success', message: '算法添加成功' });
        handleCloseBatchOperation();
        getTableData();
      });
    }
    if (batchOperationType.value === 'set') {
      isBatchParamSetVisible.value = true;
      const algoDetail = algosInfo.value.find((item) => item.id === algoIds[0]);
      selectedAlgoDetail.value = algoDetailToJSON(algoDetail);
    }
    if (batchOperationType.value === 'open') {
      updateAlgosStatusByBatch({ cameraIdList: chooseId.value, algoIdList: algoIds, isEnabled: true }).then(() => {
        ElMessage({ type: 'success', message: '算法开启成功' });
        handleCloseBatchOperation();
        getTableData();
      });
    }
    if (batchOperationType.value === 'close') {
      updateAlgosStatusByBatch({ cameraIdList: chooseId.value, algoIdList: algoIds, isEnabled: false }).then(() => {
        ElMessage({ type: 'success', message: '算法关闭成功' });
        handleCloseBatchOperation();
        getTableData();
      });
    }
    if (batchOperationType.value === 'delete') {
      deleteAlgosByBatch({ cameraIdList: chooseId.value, algoIdList: algoIds }).then(() => {
        ElMessage({ type: 'success', message: '算法删除成功' });
        handleCloseBatchOperation();
        getTableData();
      });
    }
  };
  const handleCloseBatchOperation = () => {
    batchOperationType.value = '';
    batchOperationVisible.value = false;
    handleResetBtnStatus();
  };

  // 批量参数设置提交
  const handleSubmit = (param) => {
    const newParam = createAlgoSubmitParams(param, selectedAlgoDetail.value);
    updateAlgosByBatch({
      cameraIdList: chooseId.value,
      ...newParam,
    }).then(() => {
      ElMessage({ type: 'success', message: '参数设置成功' });
      isBatchParamSetVisible.value = false;
    });
  };
  const handleCancel = () => {
    isBatchParamSetVisible.value = false;
  };

  // 换页，重新获取表格
  const handlePageChange = (val) => {
    tableQueryParams.value.pageNumber = val;
    getTableData();
  };
  const handleSizeChange = (val) => {
    tableQueryParams.value.pageSize = val;
    getTableData();
  };

  const getTableData = async () => {
    await getCameraListByAlgo(tableQueryParams.value).then((res) => {
      tableData.value = res.records;
      total.value = res.totalRow;
    });
  };

  onMounted(() => {
    getTableData();
    getAlgosInfo().then((res) => {
      algosInfo.value = res;
    });
  });
</script>

<style lang="scss" scoped>
  .action-bar {
    display: flex;
    align-items: center;
    position: absolute;
    min-width: calc(100vw - 266px);
    height: 50px;
    border-radius: 4px 4px 0px 0px;
    background-color: #ddefff;
    z-index: 10;

    .num-text {
      margin: 0 34px 0 25px;
      color: rgba(0, 0, 0, 0.85);
      font-weight: 500;
    }

    .btn-normal {
      color: #1890ff;
      background: transparent;
      border: 1px solid #1890ff;
      border-radius: 2px;
    }

    .btn-active,
    .btn-normal:hover {
      color: #ffffff;
      background-color: #1890ff;
    }

    .close-btn {
      margin-left: auto;
      margin-right: 20px;
    }

    .close-btn:before {
      content: '\2716';
      color: #000;
      cursor: pointer;
    }
  }

  .table-bar {
    position: relative;
  }

  .batch-param-set-header {
    width: 100%;
    height: 80px;
    border-bottom: 1px solid #e4e7ec;
    position: relative;

    .algo-title {
      font-size: 20px;
      font-weight: 600;
      color: #000000;
    }

    .set-tips {
      display: flex;
      align-items: center;
      margin-top: 10px;
      color: #66abeb;

      .tip {
        margin-left: 2px;
      }
    }
  }

  :deep(.el-dialog__header) {
    padding-right: 0px;
  }
</style>
