<template>
  <div class="camera-page">
    <ConditionQuery />
    <div class="camera-list">
      <BasicTable
        :columns="columns"
        :data-source="cameraItems"
        :row-key="(row) => row.code"
        :action-column="actionColumn"
        :pagination="{ total: total, pageSize: size, hideOnSinglePage: !cameraItems.length }"
        :loading="loading"
        :tableSetting="{
          size: false,
          redo: false,
          fullscreen: false,
          striped: false,
          setting: false,
        }"
        :striped="true"
        ref="tableRef"
        @order-change="orderByItem"
        @page-num-change="handlePageNumChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #tableTitle>
          <el-button type="primary" :icon="Plus" @click="showAddPopover = true">添加</el-button>
          <el-badge :value="totalRow" :hidden="totalRow < 1" class="item">
            <el-button color="#1890FF" @click="showSharedPopover = true" plain>共享相机</el-button>
          </el-badge>
        </template>
        <template #empty>
          <div class="empty-content flex flex-col items-center">
            <img :src="emptyImg" class="empty-img" />
            <span class="empty-text">目前无内容，请先添加相机</span>
          </div>
        </template>
      </BasicTable>
    </div>
    <AddCamera class="add-popover" v-model="showAddPopover" />
    <EditCamera class="add-popover" v-model="showEditPopover" :edit-data="editCameraData" />
    <EditSRSCamera class="add-popover" v-model="showEditSRSPopover" :edit-data="editCameraData!" />
    <EditNVRCamera
      class="add-popover"
      v-model="showEditNVRPopover"
      :edit-data="editCameraData! as any as CameraNVRItem"
    />
    <ShareCamera class="add-popover" v-model="addSharedPopover" :share-data="shareCameraData" />
    <EditSharedCamera
      class="add-popover"
      v-model="showSharedPopover"
      @update-unadd="updateUnaddAmount"
    />
  </div>
</template>

<script setup lang="ts">
  import { h, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
  import { BasicTable, TableActionIcons } from '@/components/Table';
  import { BasicColumn } from '@/components/Table';
  import { columns } from './overviewColumns';
  import ConditionQuery from './components/ConditionQuery.vue';
  import AddCamera from './components/CameraAddPopover.vue';
  import ShareCamera from './components/CameraSharePopover.vue';
  import EditCamera from './components/CameraEditPopover.vue';
  import EditSRSCamera from './components/CameraEditSRSPopover.vue';
  import EditNVRCamera from './components/CameraEditNVRPopover.vue';
  import EditSharedCamera from './components/CameraSharedEdit.vue';
  import emptyImg from '@/assets/images/table/table-empty.png';
  import { Plus } from '@element-plus/icons-vue';
  import shareIcon from '@/assets/images/table/table-share.png';
  import previewIcon from '@/assets/images/table/table-preview.png';
  import editIcon from '@/assets/images/table/table-edit.png';
  import deleteIcon from '@/assets/images/table/table-delete.png';
  import useCameraOverview from './stores/useCameraOverview';
  import { storeToRefs } from 'pinia';
  import { CameraIPItem, CameraNVRItem, CameraShowItem } from './type';
  import { deleteCameraItem } from '@/api/camera/camera-overview';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import useCameraShare from './stores/useCameraShare';
  import router from '@/router';
  import { AddType } from './constant';

  const useShare = useCameraShare();
  const { totalRow, queryToTenantId, isAddState, conditionSearch } = useShare;

  onMounted(() => {
    isAddState.value = false;
    console.log('isAddState', isAddState.value);
    queryToTenantId.value = -10;
    conditionSearch();
  });

  const cameraOverview = useCameraOverview();
  const { cameraItems, loading, total, page, size } = storeToRefs(cameraOverview);
  const { getCameraItems, openInterval, closeInterval, reset } = cameraOverview;

  // 添加弹窗相关
  const showAddPopover = ref(false);

  const showSharedPopover = ref(false);
  const addSharedPopover = ref(false);

  const showEditPopover = ref(false);
  const showEditSRSPopover = ref(false);
  const showEditNVRPopover = ref(false);
  const editCameraData = ref<CameraIPItem | null>();
  const shareCameraData = ref<CameraShowItem | null>();

  const updateUnaddAmount = () => {
    isAddState.value = false;
    console.log('isAddState', isAddState.value);
    queryToTenantId.value = -10;
    conditionSearch();
  };

  //操作列
  const actionColumn: BasicColumn = reactive({
    width: 200,
    title: '操作',
    prop: 'action',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableActionIcons as any, {
        space: 20,
        color: '#629bf9',
        style: 'img',
        size: 16,
        actionIcons: [
          {
            label: '分享',
            icon: shareIcon,
            onClick: handleShare.bind(null, record.row),
          },
          {
            label: '预览',
            icon: previewIcon,
            onClick: handlePreview.bind(null, record.row),
          },
          {
            label: '编辑',
            icon: editIcon,
            onClick: handleEdit.bind(null, record.row),
          },
          {
            label: '删除',
            icon: deleteIcon,
            onClick: handleDelete.bind(null, record.row),
          },
        ],
      });
    },
  });

  // 列排序操作
  const orderByItem = () => {};

  const handlePageNumChange = (pageNum) => {
    page.value = pageNum;
    getCameraItems();
  };

  const handlePageSizeChange = (pageSize) => {
    size.value = pageSize;
    getCameraItems();
  };

  const handleShare = (row) => {
    addSharedPopover.value = true;
    shareCameraData.value = row;
  };

  const handlePreview = (_row) => {
    router.push(`/cameras/preview?cameraId=${_row.id}`);
  };

  const handleDelete = (row) => {
    ElMessageBox.confirm(`您想删除相机${row.code}`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
    })
      .then(() => {
        deleteCameraItem({ cameraId: row.id }).then(() => {
          ElMessage.success('删除成功');

          getCameraItems();
        });
      })
      .catch(() => {});
  };

  const handleEdit = (row) => {
    if (row.sourceType === AddType.srs) {
      showEditSRSPopover.value = true;
    } else if (row.sourceType === AddType.ip) {
      showEditPopover.value = true;
    } else {
      showEditNVRPopover.value = true;
    }
    editCameraData.value = row;
  };

  onMounted(() => {
    getCameraItems();
    openInterval();
  });

  onBeforeUnmount(() => {
    closeInterval();
    reset();
  });
</script>

<style scoped>
  .camera-page {
    position: relative;
    height: calc(100vh - 64px - 12px);
    background-color: #ffffff;
  }

  .camera-list {
    padding: 0 21px;
  }

  .empty-content {
    margin: auto;
    padding: 125px 0;
  }

  .empty-img {
    width: 396px;
  }

  .empty-text {
    font-size: 22px;
    color: #8e8e8e;
    line-height: 30px;
    text-align: center;
  }

  .add-tip {
    position: absolute;
    left: 187px;
    top: 64px;
    font-size: 16px;
    color: red;
  }
  .add-popover {
    position: absolute;
    width: calc(100% - 21px);
    height: 622px;
    top: 0;
    bottom: 0;
    margin: auto;
    z-index: 99;
  }

  .item {
    margin: 0px 40px 0px 15px;
  }
</style>
