<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" row-key="id" :request-api="listVideoStableApi">
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" v-auth="['demo:videoStable:add']" icon="CirclePlus" @click="openDialog(1, '视频去抖动新增')"> 新增 </el-button>
        <!--        <el-button type="primary" v-auth="['demo:videoStable:import']" icon="Upload" plain @click="batchAdd"> 导入</el-button>-->
        <!--        <el-button type="primary" v-auth="['demo:videoStable:export']" icon="Download" plain @click="downloadFile"> 导出 </el-button>-->
        <el-button
          type="danger"
          v-auth="['demo:videoStable:remove']"
          icon="Delete"
          plain
          :disabled="!scope.isSelected"
          @click="batchDelete(scope.selectedListIds)"
        >
          批量删除
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button
          type="primary"
          link
          icon="View"
          @click="startVideoStable(scope.row)"
          v-if="scope.row.status == '0' || scope.row.status == '3' || scope.row.status == '4'"
        >
          开始
        </el-button>
        <el-popconfirm title="确定终止此任务吗?" @confirm="stopVideoStable(scope.row)" v-if="scope.row.status == '1'">
          <template #reference>
            <el-button type="primary" link icon="View"> 终止 </el-button>
          </template>
        </el-popconfirm>
        <el-button type="primary" link icon="View" @click="compareVideoStable(scope.row)" v-if="scope.row.status == '2'"> 预览 </el-button>
        <el-button type="primary" link icon="View" v-auth="['demo:videoStable:query']" @click="openDialog(3, '视频去抖动查看', scope.row)">
          查看
        </el-button>
        <!-- <el-button type="primary" link icon="EditPen" v-auth="['demo:videoStable:edit']" @click="openDialog(2, '视频去抖动编辑', scope.row)">
          编辑
        </el-button> -->
        <el-button type="primary" link icon="Delete" v-auth="['demo:videoStable:remove']" @click="deleteVideoStable(scope.row)"> 删除 </el-button>
      </template>
    </ProTable>
    <FormDialog ref="formDialogRef" />
    <ImportExcel ref="dialogRef" />
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="80%">
      <el-form :inline="true">
        <el-form-item label="帧率">
          <el-select v-model="imageFps" placeholder="选择帧率" style="width: 200px" @change="changeFps">
            <el-option label="0" value="0"></el-option>
            <el-option label="5" value="5"></el-option>
            <el-option label="15" value="15"></el-option>
            <el-option label="30" value="30"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="跳转至">
          <el-input v-model="newImageIdx" type="number" style="width: 100px" />
          <el-button type="primary" @click="confirmNewImageIdx" style="margin-left: 10px">确认</el-button>
        </el-form-item>
      </el-form>
      <div class="image-dialog">
        <el-image :src="imageUrlList[imageIdx].inputUrl" style="width: 45%"></el-image>
        <el-image :src="imageUrlList[imageIdx].outputUrl" style="width: 45%"></el-image>
      </div>
      <div class="image-dialog-btn" v-if="imageFps == 0">
        <el-button type="primary" @click="pre_picture" :disabled="imageIdx <= 0">上一个</el-button>
        <el-button type="primary" @click="next_picture" :disabled="imageIdx >= imageUrlList.length - 1">下一个</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="VideoStable">
import { ref, reactive } from 'vue'
import { useHandleData } from '@/hooks/useHandleData'
import { useDownload } from '@/hooks/useDownload'
import { ElMessageBox, ElMessage } from 'element-plus'
import ProTable from '@/components/ProTable/index.vue'
import ImportExcel from '@/components/ImportExcel/index.vue'
import FormDialog from '@/components/FormDialog/index.vue'
import { ProTableInstance, ColumnProps, EnumProps } from '@/components/ProTable/interface'
import {
  listVideoStableApi,
  delVideoStableApi,
  addVideoStableApi,
  updateVideoStableApi,
  importTemplateApi,
  importVideoStableDataApi,
  exportVideoStableApi,
  getVideoStableApi,
  startVideoStableApi,
  stopVideoStableApi,
  // getCompareImageApi,
  // getCompareImageCountApi,
  getImagesApi
} from '@/api/modules/demo/videoStable'

const dialogVisible = ref(false)
const imageIdx = ref(0)
const imageUrlList: any = ref([])
const newImageIdx = ref('')

// 直接缓存所有图片
const dialogTitle = ref('')
const imageFps = ref(0)
const intervalChangeFps: any = ref()

const changeFps = () => {
  console.log('changeFps')
  if (intervalChangeFps.value) {
    clearInterval(intervalChangeFps.value)
  }

  if (imageFps.value == 0) {
    return
  }
  imageIdx.value = 1
  intervalChangeFps.value = setInterval(() => {
    next_picture()
  }, 1000 / imageFps.value)
}

const startVideoStable = async (params: any) => {
  const res = await startVideoStableApi(params.id)
  if (res.code === 200) {
    ElMessage.success('任务已经开始，请等待')
  } else {
    ElMessage.error('任务开始失败，请检查！')
  }
  proTable.value?.getTableList()
}

const stopVideoStable = async (params: any) => {
  const res = await stopVideoStableApi(params.id)
  if (res.code === 200) {
    ElMessage.success('任务终止成功')
  } else {
    ElMessage.error('任务终止失败！')
  }
  proTable.value?.getTableList()
}

const confirmNewImageIdx = () => {
  const val = parseInt(newImageIdx.value)
  if (val > 0 && val <= imageUrlList.value.length) {
    imageIdx.value = val - 1
  } else {
    ElMessageBox.alert('跳转索引有误，请检查！')
  }
}

const compareVideoStable = async (params: any) => {
  console.log('compareVideoStable')
  const data: any = await getImagesApi(params.inputOssId)

  imageUrlList.value = data.data
  imageIdx.value = 0

  dialogTitle.value = '预览: 第' + (imageIdx.value + 1) + '张图片 共' + imageUrlList.value.length + '张图片'
  dialogVisible.value = true
}
const next_picture = async () => {
  if (imageIdx.value < imageUrlList.value.length - 1) {
    imageIdx.value = imageIdx.value + 1
  }
  dialogTitle.value = '预览: 第' + (imageIdx.value + 1) + '张图片 共' + imageUrlList.value.length + '张图片'
}
const pre_picture = async () => {
  if (imageIdx.value > 0) {
    imageIdx.value = imageIdx.value - 1
  }
  dialogTitle.value = '预览: 第' + (imageIdx.value + 1) + '张图片 共' + imageUrlList.value.length + '张图片'
}

// ProTable 实例
const proTable = ref<ProTableInstance>()

// 删除视频去抖动信息
const deleteVideoStable = async (params: any) => {
  await useHandleData(delVideoStableApi, params.id, '删除任务【' + params.name + '】？')
  proTable.value?.getTableList()
}

// 批量删除视频去抖动信息
const batchDelete = async (ids: string[]) => {
  await useHandleData(delVideoStableApi, ids, '删除所选任务？')
  proTable.value?.clearSelection()
  proTable.value?.getTableList()
}

// 导出视频去抖动列表
const downloadFile = async () => {
  ElMessageBox.confirm('确认导出视频去抖动数据?', '温馨提示', { type: 'warning' }).then(() =>
    useDownload(exportVideoStableApi, '视频去抖动列表', proTable.value?.searchParam)
  )
}

// 批量添加视频去抖动
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null)
const batchAdd = () => {
  const params = {
    title: '视频去抖动',
    tempApi: importTemplateApi,
    importApi: importVideoStableDataApi,
    getTableList: proTable.value?.getTableList
  }
  dialogRef.value?.acceptParams(params)
}

const formDialogRef = ref<InstanceType<typeof FormDialog> | null>(null)
// 打开弹框的功能
const openDialog = async (type: number, title: string, row?: any) => {
  let res = { data: {} }
  if (row?.id) {
    res = await getVideoStableApi(row?.id || null)
  }
  // 重置表单
  setItemsOptions()
  const params = {
    title,
    width: 580,
    isEdit: type !== 3,
    itemsOptions: itemsOptions,
    model: type == 1 ? {} : res.data,
    api: type == 1 ? addVideoStableApi : updateVideoStableApi,
    getTableList: proTable.value?.getTableList
  }
  formDialogRef.value?.openDialog(params)
}
const statusEnums: EnumProps[] = [
  {
    label: '未开始',
    value: '0',
    disabled: false,
    tagType: 'default'
  },
  {
    label: '进行中',
    value: '1',
    disabled: false,
    tagType: 'primary'
  },
  {
    label: '完成',
    value: '2',
    disabled: false,
    tagType: 'success'
  },
  {
    label: '失败',
    value: '3',
    disabled: false,
    tagType: 'danger'
  },
  {
    label: '已中断',
    value: '4',
    disabled: false,
    tagType: 'default'
  }
]

// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  { type: 'selection', fixed: 'left', width: 70 },
  { prop: 'id', label: '主键ID', width: 180 },
  {
    prop: 'name',
    label: '视频名称',
    search: {
      el: 'input'
    },
    width: 150
  },
  {
    prop: 'status',
    label: '任务状态',
    search: {
      el: 'select'
    },
    width: 100,
    tag: true,
    enum: statusEnums
  },
  {
    prop: 'startTime',
    label: '开始时间',
    // search: {
    //   el: 'date-picker',
    //   props: {
    //     type: 'datetimerange',
    //     valueFormat: 'YYYY-MM-DD HH:mm:ss'
    //   }
    // },
    width: 180
  },
  {
    prop: 'endTime',
    label: '结束时间',
    // search: {
    //   el: 'date-picker',
    //   props: {
    //     type: 'datetimerange',
    //     valueFormat: 'YYYY-MM-DD HH:mm:ss'
    //   }
    // },
    width: 180
  },
  {
    prop: 'costSecond',
    label: '耗时',
    search: {
      el: 'input'
    },
    width: 80
  },
  {
    prop: 'log',
    label: '日志',
    width: 120
  },

  {
    prop: 'block_size',
    label: '网格大小',
    width: 120
  },
  {
    prop: 'radius',
    label: '扩散半径',
    width: 120
  },
  {
    prop: 'buffer_size',
    label: '缓冲区大小',
    width: 120
  },
  {
    prop: 'cornerquality',
    label: '角点质量',
    width: 130
  },
  {
    prop: 'cornerminDistance',
    label: '角点最小距离',
    width: 180
  },
  {
    prop: 'lklevel',
    label: '光流层级',
    width: 120
  },
  {
    prop: 'lkwinSiz',
    label: '光流窗口大小',
    width: 120
  },
  {
    prop: 'remarks',
    label: '备注',
    search: {
      el: 'input'
    },
    width: 120
  },
  {
    prop: 'operation',
    label: '操作',
    width: 230,
    fixed: 'right'
  }
])
// 表单配置项
let itemsOptions: ProForm.ItemsOptions[] = []
const setItemsOptions = () => {
  itemsOptions = [
    {
      label: '任务名称',
      prop: 'name',
      rules: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
      compOptions: {
        placeholder: '请输入任务名称'
      }
    },
    {
      label: '图片集压缩包',
      prop: 'inputOssId',
      rules: [{ required: true, message: '图片集压缩包不能为空', trigger: 'blur' }],
      compOptions: {
        elTagName: 'file-upload',
        fileSize: 4096,
        fileType: ['zip'],
        placeholder: '请上传图片集压缩包'
      }
    },
    {
      label: '网格大小',
      prop: 'block_size',
      rules: [],
      compOptions: {
        type: 'input',
        clearable: true,
        placeholder: '默认50'
      }
    },
    {
      label: '扩散半径',
      prop: 'radius',
      rules: [],
      compOptions: {
        type: 'input',
        clearable: true,
        placeholder: '默认500'
      }
    },
    {
      label: '缓冲区大小',
      prop: 'buffer_size',
      rules: [],
      compOptions: {
        type: 'input',
        clearable: true,
        placeholder: '默认200'
      }
    },
    {
      label: '角点质量',
      prop: 'cornerquality',
      rules: [],
      compOptions: {
        type: 'input',
        clearable: true,
        placeholder: '默认0.2'
      }
    },
    {
      label: '角点最小距离',
      prop: 'cornerminDistance',
      rules: [],
      compOptions: {
        type: 'input',
        clearable: true,
        placeholder: '默认5'
      }
    },
    {
      label: '光流层级',
      prop: 'lklevel',
      rules: [],
      compOptions: {
        type: 'input',
        clearable: true,
        placeholder: '默认3'
      }
    },
    {
      label: '光流窗口大小',
      prop: 'lkwinSiz',
      rules: [],
      compOptions: {
        type: 'input',
        clearable: true,
        placeholder: '默认15'
      }
    },
    {
      label: '备注',
      prop: 'remarks',
      rules: [
        {
          required: false,
          message: '备注不能为空',
          trigger: 'blur'
        }
      ],
      compOptions: {
        placeholder: '请输入备注'
      }
    }
  ]
}
</script>

<style lang="scss" scoped>
.image-dialog {
  display: flex;
  justify-content: center;
  .el-image {
    margin-right: 20px;
    margin-bottom: 20px;
  }
}
.image-dialog-btn {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
