<template>

  <div id="alarmreminder">
    <!-- 音频文件 | S -->
    <!-- <audio ref="audioE" id="aWrap" controls>
      <source ref="sourceE" id="audio" :src="`http://192.168.1.120:9995/play/23`" type="audio/mpeg">
      </source>
    </audio> -->

    <div style="border: 1px solid red; position: fixed; top: -1000px" v-html="htmlStr"></div>
    <!-- 音频文件 | E -->

    <!-- 替换文件上传 -->
    <NModal v-model:show="updateFileModal">
      <NCard title="替换/上传文件" style="width: 600px" closable @close="() => {
        updateFileModal = false
      }">
        <NForm label-align="left">
          <NForm-item label="选择音频" path="file" required>
            <NUpload :headers="{
              'token': localStg.get('token') as string
            }" :data="{
              'id': audioId,
            }" :max="1" :action="'/v1/upload/' + audioId" @before-upload="beforeUpload" name="audioFile"
              @finish="handleFinish">
              <NButton>上传</NButton>
            </NUpload>
          </NForm-item>
        </NForm>
        <template #footer>
          <div style="display: flex; justify-content: end;">
            <NSpace>
              <NButton @click="updateFileModal = false">取消</NButton>
              <NButton type="primary" @click="updateFileModal = false">确定</NButton>
            </NSpace>
          </div>
        </template>
      </NCard>
    </NModal>

    <!-- ===================== 提醒相关功能 | S -->
    <NRow :gutter="20">
      <NCol span="8">
        <NCard title="报警弹窗及语音提醒">
          <template #action>
            <div>
              <!-- 标题 -->
              <NSpace justify="space-between" class="sum-title">
                <span>选择开启提醒的算法</span>
                <span>共 <i class="sum-style">{{  modifyForm.ids.length || 0 }} </i> 个算法开启提醒</span>
              </NSpace>

              <!-- ========================================== 算法下拉 | S -->
              <n-select style="margin-bottom: 10px;" v-model:value="modifyForm.ids" label-field="algorithmName"
                value-field="id" placeholder="算法" @update-value="(val) => {
                  modifyForm.ids = val
                  onSubmit();
                }" filterable multiple tag :options="algorithmsList" />
              <!-- ========================================== 算法下拉 | E -->

              <div class="_t" style="padding-top: 10px;">提醒方式</div>

              <NSpace justify="space-between" style="margin: 5px 0;">
                <span>系统报警语音</span>
                <NSwitch @update:value="val => {
                  modifyForm.isVoice = val;
                  onSubmit();
                }" v-model:value="modifyForm.isVoice" :round="modifyForm.isVoice">
                </NSwitch>
              </NSpace>

              <NSpace justify="space-between" style="margin: 5px 0;">
                <span>系统报警弹窗</span>
                <NSwitch @update:value="val => {
                  modifyForm.isRemind = val;
                  onSubmit();
                }" v-model:value="modifyForm.isRemind" :round="modifyForm.isRemind">
                </NSwitch>
              </NSpace>

              <div v-if="modifyForm.isRemind" class="_t">显示方式</div>
              <div v-if="modifyForm.isRemind" class="flex-wrap">
                <div>
                  <!-- 最外层区分左右 -->
                  <div @click="() => { modifyForm.reminderType = 1; onSubmit(); }"
                    :class="[modifyForm.reminderType !== 1 ? 'left-warp' : 'left-warp sel-left-warp']">
                    <!-- 外层盒子 -->
                    <div>
                      <!-- 弹窗盒子 -->
                      <div class="right-tip-wrap">
                        <div class="right-tip"></div>
                        <div class="right-tip"></div>
                        <div class="right-tip"></div>
                        <div class="right-tip"></div>
                      </div>
                    </div>
                  </div>
                  <br />
                  <span>右侧小窗</span>
                </div>
                <!-- 右侧盒子 -->
                <div>
                  <div @click="() => { modifyForm.reminderType = 2; onSubmit(); }"
                    :class="[modifyForm.reminderType !== 2 ? 'right-warp' : 'right-warp sel-right-warp']">
                    <div></div>
                  </div>
                  <br />
                  <span class="right-tip_title">居中大窗</span>
                </div>
              </div>
            </div>
          </template>
        </NCard>
      </NCol>
      <NCol span="16">
        <NCard title="提醒语音管理">
          <template #action>
            <NDataTable :ellipsis="true" striped bottom-bordered :row-key="row => row.id" :columns="tableColumn"
              :data="tableData" :bordered="true" />

            <div style="display: flex; justify-content: end">
              <!-- <NPagination key="alarmReminder________iiuiiiiiiiiiiiiiiiiiiiii" v-model:page="page"
                v-model:page-size="pageSize"
                style="margin-top: 20px"
                :display-order="['quick-jumper', 'pages', 'size-picker']"
                :page-count="100"
                show-quick-jumper
                show-size-picker
                :page-sizes="pageSizes" /> -->

              <NPagination
              :item-count="total"
              v-model:page="page" v-model:page-size="pageSize" style="margin-top: 20px"
                :display-order="['quick-jumper', 'pages', 'size-picker']" :page-count="100" show-quick-jumper
                show-size-picker :page-sizes="pageSizes" />
            </div>
          </template>
        </NCard>
      </NCol>
      <!-- <NButton @click="onSubmit">提交</NButton> -->
    </NRow>
  </div>

</template>


<script lang="tsx" setup>
import { h, nextTick, onMounted, onUpdated, reactive, ref, watch } from 'vue';
import type { TreeOverrideNodeClickBehavior, UploadFileInfo } from 'naive-ui';
import { NButton, NImage, NSpace, NTag, useMessage, useNotification, NDropdown, NRow, NCol, NEllipsis } from 'naive-ui';
import JSMpeg from '@cycjimmy/jsmpeg-player';
import html2canvas from 'html2canvas';
import { Add28Filled as AddIcon, Delete16Regular as DelICon, CalendarEdit24Regular as EditIcon } from '@vicons/fluent';
import { localStg } from '@/utils/storage';
// api_algorithmsPopUpsConfig 弹窗配置
// api_algorithmsList 算法列
// api_getKeyOfAnaly
// api_getKeyOfVideoSource
// api_getKeyTaskInfo
// api_algorithmsPopUpsDel api_algorithmsPopUpsFind

import { api_permissionTreeList, api_delRoleInfo, api_modifyRoleInfo, getAudioFile, api_algorithmsPopUpsConfig, api_videoTest, api_algorithmsList, api_algorithmsPopUpsPage, api_algorithmsPopUpsFind, api_algorithmsPopUpsDel } from '@/api/index.ts'


const updateFileModal = ref(false);
const message = useMessage();
const tableData = ref([]);
const selTipType = ref('0');
const notification = useNotification();
let algorithmsList = reactive([]);
const apiUrl = import.meta.env.VITE_SERVICE_URL;


// const page = ref(1);
// const pageSize = ref(10);


// ========================================== 分页 | S
const pageSizes = [
  {
    label: '10 每页',
    value: 10
  },
  {
    label: '20 每页',
    value: 20
  },
  {
    label: '30 每页',
    value: 30
  },
  {
    label: '40 每页',
    value: 40
  }
];


const page = ref(1);
const pageSize = ref(10);

// @on-update:page="next"
// @on-update:page-size="prev"

const next = (val: number) => {
  page.value = val;
}

const prev = (val: number) => {
  pageSize.value = val;
}


// ========================================== 分页 | E

// 音频试听
const sourceE = ref(null);
const audioE = ref(null);

const htmlStr = ref('')

const playAudio = async () => {
  /**
   *  1. 接口形式并非准确的资源形式形式
   *  2. 模板的形式， 特殊处理
   *  3. 动态js网络链接不上
   */


  htmlStr.value = `<audio ref="audioE"  id="aWrap" controls>
         <source  id="audio" src="${apiUrl}/v1/play/${audioId.value}" type="audio/mpeg"></source>
    </audio>`;

  nextTick(() => {
    let a = document.getElementById('aWrap');
    a?.play();
  });
};

// 临时测试播放
const videoTest = async () => {
  return await api_videoTest().then(res => {
    // console.log("================== videoTest", res);

    // ============================= 二进制转化程 video-mp4

    nextTick(() => {
      console.log("================== videoTest |||| ", res);
      // 创建Blob对象
      var blob = new Blob([res.data.data], { type: 'video/mp4' });
      console.log("============== blob", blob)

      // 创建Blob URL
      var blobUrl = URL.createObjectURL(blob);
      console.log("============== blobUrl", blobUrl)

      // 设置video标签的src属性
      var source = document.getElementById('videoSource');
      source.src = blobUrl;
    })
  });
};

// 权限树
const permissionTree = ref([]);

const getPermissionTreeList = async () => {
  return await api_permissionTreeList().then(res => {
    if (res.data.code === 200) {
      return permissionTree.value = res.data.data;
      // return message.success()
    }
    return message.error(res.data.msg);
  })
}

// 算法信息
const getAlgorithmsList = async () => {
  await api_algorithmsList().then(res => {
    if (res.data.code === 200) {
      console.log("================ |||||||||||||||||||||| ================ api_algorithmsList", res.data.data);
      let ids = [];
      let type = true;

      algorithmsList = res.data.data.map(item => {
        // 那些选中
        // if (item.isRemind && item.isVoice) {
        //   ids.push(item?.id);
        //   type && ['isRemind', 'isVoice', 'reminderType'].forEach(key => {
        //     type = false;
        //     modifyForm[key] = item[key];
        //   });
        // }

        if (item.isChecked) {
          ids.push(item?.id);
          type && ['isRemind', 'isVoice', 'reminderType'].forEach(key => {
            type = false;
            modifyForm[key] = item[key];
          });
        }

        // 选项列表
        return {
          algorithmName: item.algorithmName,
          id: item.id
        }
      });
      // 修改表单
      modifyForm.ids = ids;
      return;
    }
    return message.warning(res.data.msg);
  });
};

// 删除视频
const delAudio = async (id: string) => {
  return await api_algorithmsPopUpsDel(id).then(res => {
    console.log("================== delAudio", res);
    if (res?.data.code === 200) {
      getAlgorithmsPopUpsPage()
      // return message.success(res?.data.msg);
    }
    return message.warning(res?.data.msg);
  })
};

// 语音提醒
const total = ref(0);
const getAlgorithmsPopUpsPage = async () => {
  let param = { pageNum: page.value, pageSize: pageSize.value };
  return api_algorithmsPopUpsPage(param).then(res => {
    console.log("================== tableData", res);
    if (res?.data.code === 200) {
      tableData.value = res?.data.data.records;
      total.value = res?.data.data.total;
    }
  })
}

watch(page, () => {
  getAlgorithmsPopUpsPage();
});

watch(pageSize, () => {
  getAlgorithmsPopUpsPage();
});

// 修改弹窗配置
const onSubmit = () => {
  return modifyPopUpList();
}


let modifyForm = reactive({
  // 开启弹窗
  isRemind: true,
  // 开启语音
  isVoice: true,
  // 弹窗类型 报警弹窗类型(1,右侧，2，居中)
  reminderType: 1,
  // 算法ID
  ids: []
});

// 弹窗配置回显数据
const getAlgorithmsPopUpsFind = async () => {
  return await api_algorithmsPopUpsFind().then(res => {
    console.log("================== api_algorithmsPopUpsFind", res);
    if (res?.data.code === 200) {
      return res?.data.data;
    }
  })
}


const modifyPopUpList = async () => {
  console.log('============ modifyForm', modifyForm)
  return await api_algorithmsPopUpsConfig(modifyForm).then(res => {
    if (res.data.code === 200) {
      return message.success(res.data.msg);
    }
    return message.warning(res.data.msg);
  })
}

// ======================= IMG 上传 | S
const beforeUpload = (data: { file: UploadFileInfo; fileList: UploadFileInfo[] }): boolean => {
  console.log("=============== 上传文件", data.file.file.size)

  if ((data.file.file.size / 1024 / 1024).toFixed(0) > 5) {
    message.error('音频大小不能超过5M!');
    return false;
  }

  if (data.file.file?.type !== 'audio/mpeg') {
    message.error('只能上传MP3格式的文件!');
    return false;
  }
  return true;
};

const fileList = ref<UploadFileInfo[]>([]);

const handleFinish = ({ file, event }: { file: UploadFileInfo; event?: ProgressEvent }) => {
  const res = event?.target && event?.target?.response && JSON.parse(event?.target?.response);
  if (res.code === 200) {
    getAlgorithmsPopUpsPage();
    message.success('音频上传成功!');
  }
  return file;
};
// ======================= IMG 上传 | E
const audioId = ref('');

const tableColumn = [
  {
    title: '算法ID',
    align: 'center',
    key: 'id',
  },
  {
    title: '算法名称',
    align: 'center',
    key: 'algorithmName',
  },
  {
    title: '算法等级',
    key: 'grade',
    align: 'center',
    render: (row: any) => {
      return row.grade === 0 ? (
        <NTag bordered={false} type="error">一级</NTag>
      ) : row.grade === 1 ? (
        <NTag bordered={false} type="warning">二级</NTag>
      ) : row.grade === 2 ? (
        <NTag bordered={false} type="info">三级</NTag>
      ) : row.grade === 3 ? (
        <NTag bordered={false} type="success">四级</NTag>
      ) : (
        <NTag bordered={false} >五级</NTag>
      );
    }
  },
  {
    title: '报警语音',
    align: 'center',
    key: 'audioName',
    render: (row: any) => {
      return row.audioName || '无'
    }
  },
  {
    title: '操作',
    key: 'actions',
    align: 'center',
    render(row: any) {
      return (
        <div>
          <n-button
            onClick={() => {
              audioId.value = row.id;
              playAudio();
            }}
            quaternary
            type="info"
          >
            试听
          </n-button>

          <n-button
            onClick={() => {
              audioId.value = row.id;
              updateFileModal.value = true
            }}
            quaternary
            type="info"
          >
            替换/上传
          </n-button>

          <n-button
            onClick={() => {
              delAudio(row.id)
            }}
            quaternary
            type="error"
          >
            删除
          </n-button>
        </div>
      );
    }
  }
];

const handleSelect = () => { };

const options = [
  {
    label: '暂停提醒',
    value: '1'
  },
  {
    label: '继续提醒',
    value: '2'
  }
];


onMounted(() => {
  // 配置回显
  getAlgorithmsList();
  // 语音提醒列表
  getAlgorithmsPopUpsPage();
  // socket 弹窗
  // globalPopUpsFunc()
  // 权限树
  getPermissionTreeList();
});

</script>

<style lang="scss" scoped>
.sum-title {
  line-height: 40px;
  font-size: 15px;
  margin: 15px 0;
}

.right-tip_title {
  position: relative;
  top: 7px;
}

._t {
  font-size: 15px;
  margin: 15px 0;
}

.sum-style {
  font-size: 19px;
  color: rgb(24, 114, 240);
}

#alarmreminder {

  .flex-wrap {
    display: flex;

    &>div {
      flex: 1;
      height: 200px;
      text-align: center;

      &>div {
        margin-top: 10px;
        box-shadow: 0 0 10px rgba(0, 0, 0, .1);
        height: 120px;
        width: 210px;
        background: #fff;
        display: inline-block;
        position: relative;
        border-radius: 5px;
        cursor: pointer;
      }
    }


    // 默认样式
    .right-warp {
      display: inline-block;
      text-align: center;

      >div {
        display: inline-block;
        margin-top: 30px;
        border-radius: 5px;
        width: 120px;
        height: 55px;
        background: rgb(218, 219, 228);
      }

      span {
        display: inline-block !important;
        margin-top: 5px;
        border: 1px solid red;
      }
    }


    // 右侧选中
    .sel-right-warp {
      border: 3px solid rgb(24, 114, 240);
      border-left: none;
      border-right: none;

      >div {
        background: rgb(24, 114, 240);
      }


    }

    // 左侧选中
    .sel-left-warp {
      border: 3px solid rgb(24, 114, 240);
      border-left: none;
      border-right: none;

      .right-tip {
        background-color: rgb(24, 114, 240) !important;
      }
    }
  }

  // --- 右侧盒子
  .right-tip-wrap {
    position: absolute;
    right: 0;
    margin: 5px 5px 0 0;

    &>div {
      height: 11px;
      width: 30px;
      background-color: rgb(24, 114, 240);
      background-color: rgb(218, 219, 228);
      margin-bottom: 3px;
      border-radius: 2px;
    }
  }

  .sel-right-tip-wrap {
    position: absolute;
    right: 0;
    margin: 5px 5px 0 0;

    &>div {
      height: 13px;
      width: 30px;
      background-color: rgb(24, 114, 240);
      background-color: rgb(218, 219, 228);
      margin-bottom: 3px;
      border-radius: 2px;
    }
  }

}
</style>
