<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['VRdemo:datasource:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['VRdemo:datasource:remove']"
        >删除</el-button>
      </el-col>-->
    </el-row>

    <el-table
      v-loading="loading"
      :data="spotList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="展示点" align="center" prop="name" />
      <el-table-column label="数据类型" align="center" prop="dataTypeId">
        <template #default="scope">
          <dict-tag :options="data_type" :value="scope.row.dataTypeId" />
        </template>
      </el-table-column>
      <el-table-column
        label="数据源"
        align="center"
        prop="dataSourceTitle"
      ></el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="unloadSpot(scope.row)"
            >卸载</el-button
          >
          <!-- <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDialog(scope.row)"
          >卸载</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <el-table
      v-loading="loading"
      :data="datasourceList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="数据源标题" align="center" prop="title" />
      <el-table-column label="数据类型" align="center" prop="dataTypeId">
        <template #default="scope">
          <dict-tag :options="data_type" :value="scope.row.dataTypeId" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
            v-hasPermi="['VRdemo:datasource:edit']"
          ></el-switch>
        </template>
      </el-table-column>-->
      <el-table-column label="封面" align="center">
        <template #default="scope">
          <QImgPreview
            :src="scope.row.imgPath"
            v-if="scope.row.dataTypeId == 3"
            style="
              max-width: 100%;
              max-height: 100%;
              width: 100px;
              height: 100px;
            "
          />
          <QImgPreview
            :preview-src-list="[]"
            @click="playVideo(scope.row)"
            :src="scope.row.cover"
            v-if="scope.row.dataTypeId == 4"
            style="
              max-width: 100%;
              max-height: 100%;
              width: 100px;
              height: 100px;
            "
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="300px"
      >
        <template #default="scope">
          <!-- <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['VRdemo:datasource:edit']"
          >修改</el-button>-->
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleSetSpot(scope.row)"
            >挂载</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleAddData(scope.row)"
            >管理</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改数据源管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="datasourceRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="数据源标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入数据源标题" />
        </el-form-item>
        <el-form-item label="数据类型:" prop="dataTypeId">
          <el-select
            v-model="form.dataTypeId"
            class="m-2"
            placeholder="Select"
            size="large"
          >
            <el-option
              v-for="item in options"
              :key="item.dataTypeId"
              :label="item.title"
              :value="item.dataTypeId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 挂载spot数据模态框 -->
    <el-dialog :title="title" v-model="openSpot" width="500px" append-to-body>
      <el-form
        ref="datasourceRef"
        :model="formSpot"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="数据源标题" prop="title">
          <el-input v-model="formSpot.title" :disabled="true" />
        </el-form-item>
        <el-form-item label="展示点:" prop="spot">
          <el-select
            v-model="formSpot.spot"
            class="m-2"
            placeholder="Select"
            size="large"
          >
            <el-option
              v-for="item in nameOptions"
              :key="item.name"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormSpot">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 配置图片 -->
    <el-dialog :title="title" v-model="openImg" width="500px" append-to-body>
      <el-form
        ref="dataSourceRef"
        :model="formImg"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="formImg.title" :disabled="true" />
        </el-form-item>
        <el-form-item label="数据类型" prop="dataTypeId">
          <dict-tag :options="data_type" :value="formImg.dataTypeId" />
        </el-form-item>
        <el-form-item label="缩略图" prop="thumbnailUrl">
          <QImgUpload v-model="formImg.thumbnailUrl" />
        </el-form-item>
        <el-form-item label="图片" prop="url">
          <QImgUpload v-model="formImg.url" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitImg">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 配置视频 -->
    <el-dialog :title="title" v-model="openVideo" width="500px" append-to-body>
      <el-form
        ref="dataSourceRef"
        :model="formVideo"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="formVideo.title" :disabled="true" />
        </el-form-item>
        <el-form-item label="数据类型" prop="dataTypeId">
          <dict-tag :options="data_type" :value="formVideo.dataTypeId" />
        </el-form-item>
        <el-form-item label="封面" prop="coverUrl">
          <QImgUpload v-model="formVideo.coverUrl"></QImgUpload>
        </el-form-item>
        <el-form-item label="视频" prop="url">
          <!-- <file-upload v-model="formVideo.path"></file-upload> -->
          <QVidUpload v-model="formVideo.url"></QVidUpload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitVideo">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量卸载spot对话框 -->
    <!-- <el-dialog title="卸载数据源" v-model="openDialog" width="700px" append-to-body>
      <el-table
        :data="chooseList"
        style="width: 100%"
        @selection-change="delSelection"
      >
        <el-table-column type="selection" width="60" />
        <el-table-column prop="title" label="数据源名称" width="600" align="center" />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="delDataSources">确 定</el-button>
          <el-button @click="cancelDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>-->

    <!-- 视频预览 -->
    <el-dialog v-model="videoDialog" :destroy-on-close="true">
      <videoPlay
        width="100%"
        hight="100%"
        :title="videoOptions.title"
        :src="videoOptions.src"
        :poster="videoOptions.poster"
      />
    </el-dialog>
  </div>
</template>

<script setup name="Datasource">
import {
  getSpotByDT,
  removeSpot,
  listSpot,
  listDatasource,
  getDatasource,
  delDatasource,
  addDatasource,
  updateDatasource,
  updateDataSourceStatus,
  listDataType,
} from '@/api/VRdemo/datasource'
import { addImgData } from '@/api/VRdemo/img'
import { addVideo } from '@/api/VRdemo/video'
import { ref } from 'vue'
// import 'vue3-video-play/dist/style.css'
// import { videoPlay } from 'vue3-video-play'
import { reactive } from 'vue'

const { proxy } = getCurrentInstance()
const { data_type } = proxy.useDict('data_type')

const spotList = ref([])
const datasourceList = ref([])
const chooseList = ref([])
const delDatasourceList = ref([])
const open = ref(false)
const loading = ref(true)
// const showSearch = ref(true);
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
// 数据类型下拉框
const options = ref([])
const dataTypeList = ref([])
// 挂载spot模态框
const openSpot = ref(false)
// 卸载spot模态框
const openDialog = ref(false)
// 展示所有spot的下拉框
const nameOptions = ref([])
// 图片模态框开关
const openImg = ref(false)
// 视频模态框开关
const openVideo = ref(false)
// 预览视频窗口开关
const videoDialog = ref(false)

// 过滤条件
// const filteredOptions = computed(() => {
//   return nameOptions.value.filter(option => option.dataTypeId === 3);
// });
const CompanyAppName = ref([])

const videoOptions = reactive({
  src: '', //视频源
  poster: '', //封面
  title: '', //标题
})

const data = reactive({
  form: {},
  formSpot: {},
  formImg: {},
  formVideo: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dataTypeId: null,
    spot: null,
    title: null,
    setting: null,
    status: null,
  },
  rules: {
    dataTypeId: [
      { required: true, message: '数据类型ID不能为空', trigger: 'blur' },
    ],
    spot: [{ required: true, message: '展示点不能为空', trigger: 'blur' }],
    title: [{ required: true, message: '数据源标题不能为空', trigger: 'blur' }],
    // path: [{ required: true, message: "内容不能为空", trigger: "blur" }]
  },
})

const { queryParams, form, rules, formSpot, formImg, formVideo } = toRefs(data)

// 表单重置
function reset() {
  ;(formSpot.value = {}),
    (formImg.value = {}),
    (formVideo.value = {}),
    (form.value = {
      dataSourceId: null,
      companyId: null,
      companyAppId: null,
      dataTypeId: null,
      extendId: null,
      spot: null,
      storageId: null,
      title: null,
      setting: null,
      status: null,
      viewCounts: null,
      clickRate: null,
      cache: null,
      cacheTime: null,
      createBy: null,
      createTime: null,
      updateBy: null,
      updateTime: null,
    })
  proxy.resetForm('datasourceRef')
}

/** 查询数据源管理列表 */
function getList() {
  loading.value = true
  listDatasource(queryParams.value).then((response) => {
    datasourceList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 查询数据类型列表 */
function getDataType() {
  loading.value = true
  listDataType(queryParams.value).then((response) => {
    dataTypeList.value = response.data
    options.value = response.data
  })
}

/** 获取所有spot数据 */
function getSpotList() {
  loading.value = true
  listSpot(queryParams.value).then((response) => {
    spotList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  openSpot.value = false
  openImg.value = false
  openVideo.value = false
  reset()
  getList()
  getSpotList()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.dataSourceId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _dataSourceId = row.dataSourceId || ids.value
  getDatasource(_dataSourceId).then((response) => {
    form.value = response.data
    open.value = true
    title.value = '修改数据源管理'
  })
  getDataType()
}

/** 挂载Spot按钮 */
function handleSetSpot(row) {
  reset()
  // loading.value = true;
  const _dataSourceId = row.dataSourceId || ids.value
  getDatasource(_dataSourceId).then((response) => {
    formSpot.value = response.data
    openSpot.value = true
    title.value = '挂载spot'
  })
  getSpotByDT(_dataSourceId).then((response) => {
    nameOptions.value = response.data
    loading.value = false
  })
}

/** 挂载按钮提交 */
function submitFormSpot() {
  updateDatasource(formSpot.value).then((response) => {
    proxy.$modal.msgSuccess('挂载成功！')
    openSpot.value = false
    getList()
    getSpotList()
  })
}

//卸载spot按钮
function unloadSpot(row) {
  if (row.dataSourceTitle !== null) {
    proxy.$modal
      .confirm(
        '是否卸载展示点"' +
          row.name +
          '"为"' +
          row.dataSourceTitle +
          '"的数据项？'
      )
      .then(function () {
        return removeSpot(row.dataSource)
      })
      .then(() => {
        getList()
        getSpotList()
        proxy.$modal.msgSuccess('卸载成功')
      })
      .catch(() => {})
  } else {
    alert('未挂载展示点')
  }
}

// 打开批量卸载数据源弹窗按钮
function handleDialog(row) {
  chooseList.value = row.dataSource
  openDialog.value = true
}

// 取消批量卸载数据源弹窗按钮
function cancelDialog() {
  openDialog.value = false
  chooseList.value = null
  delDatasourceList.value = null
}

const delSelection = (val) => {
  delDatasourceList.value = val
}

// 批量卸载数据源弹窗方法
function delDataSources() {
  removeSpot({ dataSourceList: delDatasourceList.value }).then((response) => {
    openDialog.value = false
    chooseList.value = null
    delDatasourceList.value = null
    getSpotList()
  })
}

/** 数据源提交按钮 */
function submitForm() {
  proxy.$refs['datasourceRef'].validate((valid) => {
    if (valid) {
      if (form.value.dataSourceId != null) {
        updateDatasource(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addDatasource(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

// 管理按钮开关
function handleAddData(row) {
  reset()
  // loading.value = true;
  const _dataSourceId = row.dataSourceId || ids.value
  getDatasource(_dataSourceId).then((response) => {
    if (response.data.dataTypeId == 3) {
      if (response.imageData !== null) {
        formImg.value = response.imageData
      }
      formImg.value.dataSourceId = response.data.dataSourceId
      formImg.value.title = response.data.title
      formImg.value.dataTypeId = response.data.dataTypeId
      openImg.value = true
    } else if (response.data.dataTypeId == 4) {
      if (response.videoData !== null) {
        formVideo.value = response.videoData
      }
      formVideo.value.dataSourceId = response.data.dataSourceId
      formVideo.value.title = response.data.title
      formVideo.value.dataTypeId = response.data.dataTypeId
      openVideo.value = true
    }
    title.value = '配置数据'
  })
}

// 图片提交按钮
function submitImg() {
  addImgData(formImg.value).then((response) => {
    proxy.$modal.msgSuccess('操作成功')
    openImg.value = false
    getList()
    getSpotList()
  })
}
// 提交视频按钮
function submitVideo() {
  addVideo(formVideo.value).then((response) => {
    proxy.$modal.msgSuccess('操作成功')
    openVideo.value = false
    getList()
    getSpotList()
  })
}

/** 应用状态修改 */
function handleStatusChange(row) {
  let text = row.status === 1 ? '启用' : '停用'
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.title + '"应用吗?')
    .then(function () {
      return updateDataSourceStatus(row.dataSourceId, row.status)
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + '成功')
    })
    .catch(function () {
      row.status = row.status === 0 ? 1 : 0
    })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _dataSourceIds = row.dataSourceId || ids.value
  proxy.$modal
    .confirm('是否确认删除数据源标题为"' + row.title + '"的数据项？')
    .then(function () {
      loading.value = true
      return delDatasource(_dataSourceIds)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'VRdemo/datasource/export',
    {
      ...queryParams.value,
    },
    `datasource_${new Date().getTime()}.xlsx`
  )
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加数据源管理'
  getDataType()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

/**
 * 视频封面执行方法
 */
function playVideo(params) {
  videoDialog.value = true
  videoOptions.src =
    import.meta.env.VITE_STATIC_QINIU_BASE_URL + params.videoPath
  videoOptions.title = params.title
}

getList()
getSpotList()
</script>
