<!--
 * @Author: Light
 * @Date: 2022-11-18 11:53:43
 * @LastEditors: Light
 * @LastEditTime: 2022-11-28 16:45:50
 * @Description: 告诉大家这是什么
-->
<template>
  <div class="infrastructureApplication" v-show="showFlag">
    <div class="top">
      <a-list size="small" bordered :data-source="dataList.toBeApplied">
        <template #renderItem="{ item }">
          <a-list-item>
            <div class="name">
              <a-tooltip>
                <template #title>{{ item.channelName }}</template>
                {{ item.channelName }}
              </a-tooltip>
            </div>
            <a-popconfirm
              :title="'是否移出' + item.channelName + '?'"
              ok-text="是"
              cancel-text="否"
              @confirm="delWillApplyCamera(item.id)"
            >
              <a-button type="link" danger style="padding: 0">移出</a-button>
            </a-popconfirm>
          </a-list-item>
        </template>
        <template #header>
          <div class="title">待申请列表</div>
        </template>
        <template #footer>
          <a-button type="primary" @click="showApply">一键申请</a-button>
        </template>
      </a-list>
    </div>
    <div class="bottom">
      <a-list size="small" bordered :data-source="dataList.requested">
        <template #renderItem="{ item }">
          <a-list-item>
            <div class="name">
              <a-tooltip>
                <template #title>{{ item.cameraInfo.channelName }}</template>
                {{ item.cameraInfo.channelName }}
              </a-tooltip>
            </div>
            <a-tag
              color="cyan"
              style="margin-right: 0; cursor: pointer"
              @click="selectItem(item)"
            >
              {{
                item.approveStatus == '通过'
                  ? '预览'
                  : item.backToFirst == 'true'
                  ? '被驳回'
                  : item.approveStatus
              }}
            </a-tag>
            <a-popconfirm
              v-if="item.approveStatus == '通过'"
              :title="'是否撤销' + item.cameraInfo.channelName + '?'"
              ok-text="是"
              cancel-text="否"
              @confirm="deleteApply(item)"
            >
              <a-button type="link" danger style="padding: 0">撤销</a-button>
            </a-popconfirm>
            <a-button
              v-else
              type="link"
              danger
              @click="deleteApply(item)"
              style="padding: 0"
            >
              撤销
            </a-button>
          </a-list-item>
        </template>
        <template #header>
          <div class="title">
            已申请列表
            <a-button type="link" @click="goToApply">详情</a-button>
          </div>
        </template>
      </a-list>
    </div>
  </div>
  <a-modal
    v-if="!dataList.selectItem.cameraInfo"
    :width="800"
    v-model:visible="visible"
    title="撤销申请"
    @ok="handleOk"
    @cancel="clear"
  >
    <p>本次申请的视频监控包含以下{{ showArr.length }}个，是否撤销申请？</p>
    <a-table
      :columns="columns"
      :data-source="showArr"
      :pagination="{
        pageSize: 5,
      }"
    >
      <template #bodyCell="{ column, text }">
        <template v-if="column.dataIndex === 'name'">
          <a>{{ text }}</a>
        </template>
      </template>
    </a-table>
  </a-modal>
  <a-modal
    v-else
    v-model:visible="showVisible"
    :title="dataList.selectItem.cameraInfo.channelName"
    :footer="null"
    :width="845"
    destroyOnClose
    @cancel="clear"
  >
    <div
      style="
        width: 800px;
        height: 600px;
        display: flex;
        justify-content: center;
      "
    >
      <h5-player
        videoId="preview"
        unStopable="true"
        :video-url="videoUrl"
      ></h5-player>
    </div>
  </a-modal>
  <a-modal
    :width="800"
    v-model:visible="visibleApply"
    title="视频监控申请"
    @ok="apply"
    @cancel="clear"
  >
    <p>本次申请的视频监控包含以下{{ showArrApply.length }}个，是否提交申请？</p>
    <a-table
      :columns="columns"
      :data-source="showArrApply"
      :pagination="{
        pageSize: 5,
      }"
    >
      <template #bodyCell="{ column, text }">
        <template v-if="column.dataIndex === 'name'">
          <a>{{ text }}</a>
        </template>
      </template>
    </a-table>
  </a-modal>
</template>
<script setup>
  import {
    willApplyCameraSelect,
    willApplyCameraBatchInsert,
    willApplyCameraBatchDelete,
    getApplyCameraListXha,
    delApplyCamera,
  } from '@/api/home'
  import { getUserInfo, getRole } from '@/api/user'
  import { endProcess } from '@/api/personalCenter.js'
  import { onBeforeUnmount, reactive, ref } from 'vue'
  import { message } from 'ant-design-vue'
  import mybus from '@/myplugins/mybus'
  import { useRouter } from 'vue-router'
  import H5Player from '@/views/home/components/H5Player.vue'
  import { getCameraLiveStream } from '@/api/file'
  const dataList = reactive({ toBeApplied: [], requested: [], selectItem: {} })
  const showVisible = ref(false)
  // 待办
  const addWacFlag = ref(true)
  const delWacFlag = ref(true)
  const delApply = ref(true)
  const visible = ref(false)
  const visibleApply = ref(false)
  const instanceId = ref('')
  const showArr = ref([])
  const showArrApply = ref([])
  const columns = [
    {
      title: '名称',
      dataIndex: 'channelName',
      key: 'channelName',
    },
    {
      title: '地址',
      dataIndex: 'managementUnitName',
      key: 'managementUnitName',
    },
    {
      title: '类型',
      dataIndex: 'cameraPointTypeName',
      key: 'cameraPointTypeName',
      ellipsis: true,
    },
  ]
  const router = useRouter()
  const showFlag = ref(false)
  getUserInfo().then((res) => {
    if (res.data.data.superAdmin == '1') {
      showFlag.value = true
    } else {
      res.data.data.roleIdList.map((val) => {
        getRole(val).then((role) => {
          if (role.data.data.name === '视频管理员') {
            showFlag.value = true
          }
        })
      })
    }
  })
  const showApply = () => {
    if (dataList.toBeApplied.length === 0) {
      message.warning('待申请列表为空!')
      return
    }
    if (dataList.toBeApplied.length + dataList.requested.length > 10) {
      message.warning('最多只能申请10个视频监控!')
      return
    }
    visibleApply.value = true
    showArrApply.value = dataList.toBeApplied
  }
  const delWillApplyCamera = (id) => {
    console.log('撤销===>', id)
    if (delWacFlag.value) {
      delWacFlag.value = false
      willApplyCameraBatchDelete([id]).then((res) => {
        if (res.data.code == 0) {
          message.success('移出成功')
          init()
        } else {
          message.warning('移出失败')
          init()
        }
      })
    }
  }
  const apply = () => {
    let obj = {
      arr: [
        {
          checked: true,
          delFlag: 0,
          id: '1593084734789996545',
          idtCameraChannel: '790582098133127168',
          loading: false,
          note1: '',
          resourceId: '1522550195055828996',
          resourceName: '视频监控列表',
          type: '基础设施',
        },
      ],
      deptName: '西海岸新区工业和信息化局',
      deptId: '732560225344761856',
    }
    dataList.toBeApplied.map((val) => {
      val.type = '基础设施'
      val.delFlag = 0
      val.resourceId = val.channelId
      val.resourceName = val.channelName
      // obj.arr.push(val)
    })
    obj.arr[0].note1 = JSON.stringify(dataList.toBeApplied)
    if (obj.arr.length > 0) {
      console.log('一键申请===================>', obj)
      localStorage.setItem('applyList', JSON.stringify([obj]))
      router.push({
        path: '/apply',
      })
    }
  }
  // 撤销已申请
  const deleteApply = (item) => {
    console.log('撤销========>', item)
    if (delApply.value) {
      delApply.value = false
      switch (item.approveStatus) {
        case '审核中':
          visible.value = true
          instanceId.value = item.instanceId
          showArr.value = []
          dataList.requested.map((val) => {
            if (val.instanceId == item.instanceId) {
              showArr.value.push(val.cameraInfo)
            }
          })
          break
        case '通过':
          delApplyCamera([item.id]).then((res) => {
            if (res.data.code == 0) {
              message.success('撤销成功')
              initApply()
            } else {
              message.warning('撤销失败')
              initApply()
            }
          })
          break
      }
    }
  }
  const goToApply = () => {
    router.push({
      path: '/personalCenter',
      query: {
        type: 'apply',
      },
    })
  }
  const selectItem = (item) => {
    if (item.approveStatus == '通过') {
      dataList.selectItem = item
      getVideoUrl(item.cameraInfo)
    } else {
      dataList.selectItem = {}
      message.info('请耐心等待审核通过')
      showVisible.value = false
    }
  }
  const handleOk = () => {
    console.log('id', instanceId.value)
    endProcess({ instanceId: instanceId.value }).then((res) => {
      if (res.data.code == 0) {
        message.success('撤销成功')
        initApply()
      } else {
        message.warning('撤销失败')
        initApply()
      }
      visible.value = false
    })
  }
  const clear = () => {
    console.log('清空')
    instanceId.value = ''
    showArr.value = []
    showArrApply.value = []
    visible.value = false
    visibleApply.value = false
    delApply.value = true
    dataList.selectItem = {}
    showVisible.value = false
    showVisible.value = false
  }
  const init = () => {
    willApplyCameraSelect().then((res) => {
      if (res.data.code == 0) {
        dataList.toBeApplied = res.data.data
        delWacFlag.value = true
        addWacFlag.value = true
      } else {
        message.warning('查询失败')
        dataList.toBeApplied = []
      }
    })
  }
  const initApply = () => {
    getApplyCameraListXha().then((res) => {
      if (res.data.code == 0) {
        res.data.data.map((val) => {
          val.cameraInfo = JSON.parse(val.cameraInfo)
        })
        dataList.requested = res.data.data
        delApply.value = true
      } else {
        message.warning('查询失败')
        dataList.requested = []
      }
    })
  }
  init()
  initApply()
  const videoUrl = ref('')
  //获取视频控件所需播放地址
  const getVideoUrl = (data) => {
    let param = data
    getCameraLiveStream(param).then((res) => {
      //console.log('555555rrrrr',res)
      if (res.data.data) {
        videoUrl.value = res.data.data.url
        showVisible.value = true
      } else {
        message.warning('申请内容已失效，请撤销后重新进行申请！')
      }
    })
  }
  mybus.on('selectCamera', (obj) => {
    // 判断最多10条 + dataList.requested.length
    if (dataList.toBeApplied.length >= 10) {
      message.warning('最多只能申请10个视频监控！')
      return
    }
    // 判断是否已操作
    let addFlag = true
    dataList.toBeApplied.map((val) => {
      if (addFlag && val.channelId == obj.channelId) {
        addFlag = false
      }
    })
    dataList.requested.map((val) => {
      if (addFlag && val.cameraInfo.channelId == obj.channelId) {
        addFlag = false
      }
    })
    if (addWacFlag.value) {
      if (addFlag) {
        addWacFlag.value = false
        willApplyCameraBatchInsert([obj]).then((res) => {
          if (res.data.code == 0) {
            message.success('移入成功')
          } else {
            message.warning('移入失败')
          }
          init()
        })
      } else {
        message.warning('已申请该视频监控！')
      }
    }
  })
  onBeforeUnmount(() => {
    mybus.off('selectCamera')
  })
</script>
<style lang="less" scoped>
  .infrastructureApplication {
    background: #fff;
    position: absolute;
    top: 50%;
    right: 0.16rem;
    margin-top: -3.9rem;
    .bottom {
      margin-top: 20px;
    }
    .title {
      font-size: 16px;
      font-weight: 600;
    }
    .name {
      width: 1.3rem;
      overflow: hidden;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
      word-break: break-all;
    }
    .top .name {
      width: 1.8rem;
    }
    :deep(.ant-list-footer) {
      display: flex;
      justify-content: flex-end;
    }
    :deep(.ant-list-items) {
      width: 2.5rem;
      height: 3rem;
      overflow-y: scroll;
    }
    :deep(.ant-list-item) {
      padding: 5px 5px 5px 10px;
    }
    :deep(.ant-spin-nested-loading) {
      width: 2.5rem;
      height: 3rem;
    }

    .waterMark {
      position: absolute;
      z-index: 99999999;
      color: #0058e1;
      font-size: 22px;
      font-weight: bold;
      opacity: 0.4;
      transform: rotate(-25deg);
      width: 470px;
    }

    // 左上
    .waterMark-left-top {
      left: 50px;
      top: 100px;
      text-align: left;
    }

    // 右上
    .waterMark-right-top {
      right: 50px;
      top: 100px;
      text-align: right;
    }

    // 左下
    .waterMark-left-bottom {
      left: 50px;
      bottom: 100px;
      text-align: left;
    }

    // 右下
    .waterMark-right-bottom {
      right: 50px;
      bottom: 100px;
      text-align: right;
    }
  }
</style>
