<template>
  <div class="safety-platform-container">
    <div class="safety-platform-container__header">
      <div class="breadcrumb-title">治安重点部位</div>
    </div>
    <div class="safety-platform-container__main">
      <div class="search-table-container">
        <header class="disaster-precaution__header">
          <el-button
            v-if="securityPositionManagePermission"
            class="search-table-container--button"
            type="primary"
            :icon="Plus"
            @click="handleAddSecurityPosition"
          >
            新建治安重点部位
          </el-button>
          <BasicSearch
            :searchConfig="SECURITY_POSITION_LIST_SEARCH_CONFIG"
            :searchData="searchData"
            @update:search-data="handleSearch"
          >
            <template #securityPosition>
              <el-input
                v-model="searchKeyword"
                :placeholder="`请输入${curSearchTypeLabel}进行搜索`"
                clearable
                @input="handleSearch"
                @keyup.enter="handleSearch"
                style="width: 380px"
              >
                <template #prefix>
                  <el-icon color="#1777ff"><Search /></el-icon>
                </template>
                <template #prepend>
                  <el-select
                    v-model="searchSelectedType"
                    placeholder="选择搜索项"
                    @change="handleSelectedTypeChange"
                    style="width: 100px"
                  >
                    <el-option
                      v-for="item in securityPositionQueryOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </template>
              </el-input>
            </template>
          </BasicSearch>
        </header>
        <BasicTable ref="basicTableRef" :tableData="tableData" :tableConfig="tableConfig">
          <template #cameraName="scope">
            <div class="camera-name-container">
              <div v-for="item in scope.row.children" :key="item.id">
                {{ item.name }}
              </div>
            </div>
          </template>
          <template #action="scope">
            <div class="action-container--div">
              <ActionButton text="上移" @click="handleUpOne(scope.row.id, scope.row.orderNum)" />
              <ActionButton text="下移" @click="handleDownOne(scope.row.id, scope.row.orderNum)" />
              <ActionButton
                text="编辑"
                v-if="securityPositionManagePermission"
                @click="handleEditSecurityPosition(scope.row)"
              />
              <ActionButton
                v-if="securityPositionManagePermission"
                text="删除"
                :popconfirm="{
                  title: '是否删除该治安重点部位？',
                }"
                @confirm="handleDeleteSecurityPosition(scope.row.id)"
              />
            </div>
          </template>
        </BasicTable>
      </div>
    </div>
    <UpdatePositionMonitorCamera
      v-if="updatePositionMonitorCameraVisible"
      @confirm="handleConfirmPositionMonitorCamera"
      @close="handleClosePositionMonitorCamera"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive, computed } from 'vue';
  import { ElMessage } from 'element-plus';
  import { Plus, Search } from '@element-plus/icons-vue';
  import { storeToRefs } from 'pinia';
  import BasicSearch from '@/components/BasicSearch.vue';
  import BasicTable from '@/components/BasicTable.vue';
  import ActionButton from '@/components/ActionButton.vue';
  import UpdatePositionMonitorCamera from '@/components/position-monitor-camera-edit/UpdatePositionMonitorCamera.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { useUserInfoHook } from '@/hooks/useUserInfoHook';
  import { usePositionMonitorCameraEdit } from '@/store/modules/usePositionMonitorCameraEdit';
  import { SECURITY_CONFIDENTIALITY_PERMISSIONS } from '../constant';
  import { FIELDTYPE, FIELD_CONTENT, POSITION_TYPE, securityPositionQueryOptions } from './constant';
  import {
    SECURITY_POSITION_LIST_TABLE_MAX_HEIGHT_DEFAULT,
    SECURITY_POSITION_LIST_TABLE_MAX_HEIGHT_PERMISSION,
    SECURITY_POSITION_LIST_TABLE_OPTIONS,
    SECURITY_POSITION_LIST_TABLE_COLUMNS,
    SECURITY_POSITION_LIST_SEARCH_CONFIG,
  } from './config';
  import {
    GetPositionListParams,
    PositionMonitorCameraListRes,
    getSecurityPositionList,
    AddOrUpdatePositionInfoParams,
    addOrUpdatePositionInfo,
    updateCameraGroupOrder,
  } from '@/api/security-confidentiality-position';
  import { deleteCameraGroupApi } from '@/api/nine-square-grid';

  const { tableConfig } = useTableConfig(SECURITY_POSITION_LIST_TABLE_COLUMNS, SECURITY_POSITION_LIST_TABLE_OPTIONS);

  const { permissions } = useUserInfoHook();
  const securityPositionManagePermission = ref<boolean>(false);

  const positionMonitorCameraEdit = usePositionMonitorCameraEdit();
  const {
    titleOfUpdatePositionMonitorCamera,
    dataOfPosition,
    idOfPosition,
    nameOfPosition,
    selectedCameraIdsOfPosition,
  } = storeToRefs(positionMonitorCameraEdit);
  const { initDataOfPosition } = positionMonitorCameraEdit;

  const searchData = reactive<GetPositionListParams>({
    groupName: '',
    cameraName: '',
  });

  const searchSelectedType = ref(FIELDTYPE.POSITION_NAME);
  const searchKeyword = ref('');
  const curSearchTypeLabel = computed(() => {
    const option = securityPositionQueryOptions.find((item) => item.value === searchSelectedType.value);
    return option ? option.label : FIELD_CONTENT[searchSelectedType.value];
  });

  const tableData = ref<PositionMonitorCameraListRes[]>([]);

  const updatePositionMonitorCameraVisible = ref(false);

  const handleAddSecurityPosition = () => {
    titleOfUpdatePositionMonitorCamera.value = '编辑重点监控部位';
    dataOfPosition.value = undefined;
    updatePositionMonitorCameraVisible.value = true;
  };

  const handleSearch = () => {
    console.log('查询治安重点部位');
    if (searchSelectedType.value === FIELDTYPE.POSITION_NAME) searchData.groupName = searchKeyword.value;
    else searchData.cameraName = searchKeyword.value;
    getTableData();
  };

  const handleSelectedTypeChange = () => {
    searchKeyword.value = '';
  };

  const handleUpOne = (id: number, orderNum: number) => {
    console.log('上移治安重点部位', id);
    updateCameraGroupOrder({
      id: id,
      orderNum: orderNum - 1,
    }).then((res) => {
      console.log('上移治安重点部位', res);
      getTableData();
    });
  };

  const handleDownOne = (id: number, orderNum: number) => {
    console.log('下移治安重点部位', id);
    updateCameraGroupOrder({
      id: id,
      orderNum: orderNum + 1,
    }).then((res) => {
      console.log('下移治安重点部位', res);
      getTableData();
    });
  };

  const handleEditSecurityPosition = (row: PositionMonitorCameraListRes) => {
    console.log('编辑治安重点部位', row);
    titleOfUpdatePositionMonitorCamera.value = '编辑重点监控部位';
    dataOfPosition.value = row;
    initDataOfPosition();
    updatePositionMonitorCameraVisible.value = true;
  };

  const handleDeleteSecurityPosition = (id: number) => {
    console.log('删除治安重点部位', id);
    deleteCameraGroupApi(id).then((res) => {
      console.log('删除治安重点部位', res);
      getTableData();
    });
  };

  const handleConfirmPositionMonitorCamera = () => {
    const params: AddOrUpdatePositionInfoParams = {
      id: idOfPosition.value ?? undefined,
      groupName: nameOfPosition.value,
      type: POSITION_TYPE.SECURITY_POSITION,
      cameraIdList: selectedCameraIdsOfPosition.value.map((item) => item.id),
    };
    addOrUpdatePositionInfo(params).then(() => {
      ElMessage.success(idOfPosition.value ? '治安重点部位编辑成功' : '治安重点部位新建成功');
      getTableData();
    });
    updatePositionMonitorCameraVisible.value = false;
  };

  const handleClosePositionMonitorCamera = () => {
    ElMessage.info('取消操作');
    updatePositionMonitorCameraVisible.value = false;
  };

  const getTableData = () => {
    tableConfig.loading = true;
    getSecurityPositionList(searchData).then((res) => {
      console.log('获取治安重点部位列表', res);
      tableData.value = res;
    });
    tableConfig.loading = false;
  };

  onMounted(() => {
    securityPositionManagePermission.value = Boolean(
      permissions.find(
        (item: { code: string }) => item.code === SECURITY_CONFIDENTIALITY_PERMISSIONS.SECURITY_POSITION_MANAGEMENT,
      ),
    );
    tableConfig.maxHeight = securityPositionManagePermission.value
      ? SECURITY_POSITION_LIST_TABLE_MAX_HEIGHT_PERMISSION
      : SECURITY_POSITION_LIST_TABLE_MAX_HEIGHT_DEFAULT;
  });
  getTableData();
</script>

<style scoped lang="scss">
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;
</style>
