<template>
  <div class='app-container'>
    <el-form class="form" label-width="100px" ref="form" :model="data.form" :rules="data.rules">
      <el-form-item class="chooseAudio" label="插播音频：" prop="audioList">
        <div :class="['audio_box', audioListHidden ? 'audio_box_hidden' : '']">
          <div class="audioList" v-for="(item, index) in data.form.audioList" :key="item.id"
            :style="{ 'height': item.type !== 2 ? '45px' : '' }">
            <el-tag size="large" :closable="checkClose()" @close="handleClose(index)">
              {{ item.audioName }}
            </el-tag>
          </div>
        </div>
        <el-button type="primary" link v-if="data.form.audioList.length >= 15"
          :icon="audioListHidden ? 'ArrowDown' : 'ArrowUp'" style="width: 100%; height: 20px; margin-bottom: 10px"
          @click="handleHidden" />
        <div style="width: 100%;">
          <el-button v-if="checkClose()" icon="Plus" @click="getDialog">新增</el-button>
        </div>
      </el-form-item>
      <el-form-item class="chooseAudio" label="内容设定：" prop="name">
        <el-tag v-if="data.form.name" size="large" style="height: 50px; line-height: 20px; margin-bottom: 10px">
          <div>内容设定：{{ data.form.name }}</div>
          <div>插播时段：{{ data.disabledDate[0] }} - {{ data.disabledDate[1] }}</div>
        </el-tag>
        <div style="width: 100%;">
          <el-button icon="Plus" @click="getContentDialog">选择内容</el-button>
        </div>
      </el-form-item>
      <el-form-item label="播放时间：" prop="listDate">
        <div class="date" v-for="(item, index) in data.dateList">
          <el-date-picker v-model="data.dateList[index]" type="datetimerange" start-placeholder="开始时间"
            end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="getDisabledDate" @change="handleChangeDate($event, index)" />
          <el-link v-show="data.dateList.length > 1" icon="CircleClose" :underline="false"
            @click="handleDeleteDate(index)" />
          <el-link v-show="data.dateList.length - 1 === index" icon="CirclePlus" :underline="false"
            @click="handlePushDate" />
        </div>
      </el-form-item>
      <el-form-item v-if="data.form.id" label="当前状态：" prop="status">
        <el-select v-model="data.form.status" placeholder="请选择当前状态">
          <el-option v-for="item in sys_change_status" :key="item.value" :value="Number(item.value)"
            :label="item.label" />
        </el-select>
      </el-form-item>
    </el-form>
    <div class="form-btn">
      <el-button @click="getClose">取消</el-button>
      <el-button type="primary" @click="getSubmit">确定</el-button>
    </div>

    <el-dialog v-model="dialogVisible_audio" title="选择音频" width="1000px">
      <el-form inline>
        <el-form-item label="内容分类：">
          <el-select v-model="audioData.form.type" placeholder="请选择内容分类">
            <el-option v-for="item in data.radioOptions" :key="item.value" :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item v-show="audioData.form.type !== 2" label="音频ID:">
          <el-input v-model="audioData.form.id" placeholder="请输入音频ID" />
        </el-form-item>
        <el-form-item label="音频名称：">
          <el-input v-model="audioData.form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item v-show="audioData.form.type === 1" label="歌手名称：">
          <el-input v-model="audioData.form.singerName" placeholder="请输入歌手名称" />
        </el-form-item>
        <el-form-item v-show="audioData.form.type === 0" label="音频分类：">
          <el-select v-model="audioData.form.sceneId" placeholder="请选择分类">
            <el-option v-for="item in audioClassData.options" :key="item.id" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="getSearch">搜索</el-button>
          <el-button icon="Refresh" @click="getRefresh">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table ref="table" :data="audioData.tableData" :row-key="rowKey" @selection-change="handleSelectionChange"
        @select="handleSelectChange" @select-all="handleSelectAllChange" v-loading="audioData.loading">
        <el-table-column type="selection" width="55" key="selection" />
        <el-table-column label="ID" prop="id" align="center" key="id" show-overflow-tooltip />
        <el-table-column label="音频名称" prop="name" align="center" key="name" show-overflow-tooltip />
        <el-table-column v-if="audioData.form.type == 1" label="歌手名称" prop="singerName" key="singerName"
          align="center" />
        <el-table-column v-if="audioData.form.type !== 1" label="时长" prop="playTime" align="center" key="playTime">
          <template #default="scope">
            {{ playTime(scope.row.playTime) }}
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="sceneId" align="center" key="sceneId" :formatter="sceneFormatter" />
        <el-table-column label="当前状态" prop="status" align="center" key="status" :formatter="statusFormatter" />
        <el-table-column label="更新时间" prop="updateTime" align="center" key="updateTime" show-overflow-tooltip />
      </el-table>
      <pagination v-show="audioData.total > 0" :total="audioData.total" v-model:page="audioData.form.pageNum"
        v-model:limit="audioData.form.pageSize" @pagination="getAudio" />
      <template #footer>
        <el-button type="primary" @click="getPush">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogVisible_content" title="选择内容" width="1000px">
      <el-form inline>
        <el-form-item label="内容名称：">
          <el-input v-model="settingData.form.name" placeholder="请输入内容名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getSearchContent">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="settingData.tableData">
        <el-table-column label="内容ID" prop="id" align="center" width="200" />
        <el-table-column label="内容名称" prop="name" align="center" width="200" />
        <el-table-column label="当前状态" prop="status" align="center" width="100" :formatter="statusFormatter" />
        <el-table-column label="播放时段" align="center">
          <template #default="scope">
            {{ scope.row.startTime }} - {{ scope.row.endTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template #default="scope">
            <el-button type="primary" link @click="handleCheckTime(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { submit } from '@/api/insert/insertContent'
import { useAudioList, useAudioClass, useSettingList } from '@/hooks/index'

const { proxy } = getCurrentInstance();

const { audioData, getAudio } = useAudioList()
const { audioClassData, getAudioClass } = useAudioClass()
getAudioClass()
const { settingData, getSetting } = useSettingList()

const { sys_change_status } = proxy.useDict("sys_change_status")

const data = reactive({
  // 表单
  form: {
    audioList: [],
    listDate: []
  },
  // 时间段
  dateList: [[]],
  // 限制时段
  disabledDate: [],
  // 分页
  radioOptions: [{
    value: 0,
    label: '内容列表'
  }, {
    value: 1,
    label: 'Ohplay音频'
  }],
  // 多选
  selectionList: [],
  // 校验
  rules: {
    audioList: [{
      required: true, message: '请选择音频', trigger: 'change'
    }],
    name: [{
      required: true, message: '请选择需要插播的内容设定', trigger: 'change'
    }],
    listDate: [{
      required: true, message: '请选择播放时间', trigger: 'change'
    }],
    status: [{
      required: true, message: '请选择当前状态', trigger: 'change'
    }]
  },
  business_store: []
})

const getPushTime = (e) => {
  if (e.startTime) {
    let y = new Date().getFullYear()
    let m = new Date().getMonth() + 1
    let d = new Date().getDate()
    let startTime = proxy.parseTime(new Date(`${y}-${m}-${d} ${e.startTime}`).getTime(), '{y}-{m}-{d} {h}:{i}:{s}')
    let endTime = proxy.parseTime(new Date(`${y}-${m}-${d} ${e.endTime}`).getTime(), '{y}-{m}-{d} {h}:{i}:{s}')
    data.dateList[0] = [startTime, endTime]
    data.form.listDate.push({
      startTime: startTime,
      endTime: endTime
    })
  }
}

// 传参
const getAudioList = () => {
  if (proxy.$route.query.audioList) {
    var e = JSON.parse(proxy.$route.query.audioList)
    data.form.audioList.push({
      audioId: e.id,
      audioName: e.name,
      audioType: e.audioType,
      categoryId: e.sceneId,
      type: e.type,
    })
    getPushTime(e)
  }
}
getAudioList()

// 详情
const getDetail = () => {
  let e = proxy.$route.query
  if (e.id) {
    detail({ id: e.id, storeId: e.storeId }).then(res => {
      if (res.code === 0) {
        data.form = res.data
        data.dateList = []
        res.data.listDate.map(i => {
          data.dateList.push([i.startTime, i.endTime])
        })
      }
    })
  }
}
getDetail()

// 检测是否是编辑
const checkClose = () => {
  return proxy.$route.query.disabled == undefined ? true : false
}

// 弹窗
const dialogVisible_audio = ref(false)
// 打开弹窗
function getDialog() {
  dialogVisible_audio.value = true
  getAudio()
  // 监听
  watch(() => audioData.tableData, (val) => {
    if (audioData.form.type !== 2) {
      nextTick(() => {
        proxy.$refs.table.clearSelection()
        if (val && data.selectionList.length > 0) {
          data.selectionList.map(i => {
            let row = val.find(j => j.id === i.audioId)
            if (row) {
              proxy.$refs.table.toggleRowSelection(row, true)
            }
          })
        }
      })
    }
  })
}

const dialogVisible_content = ref(false)
const getContentDialog = () => {
  dialogVisible_content.value = true
  getSetting()
}

// 搜索
const getSearch = () => {
  audioData.form.pageNum = 1
  getAudio()
}

const getSearchContent = () => {
  settingData.form.pageNum = 1
  getSetting()
}

// 重置
const getRefresh = () => {
  audioData.form = {
    pageNum: 1,
    pageSize: 10,
    type: audioData.form.type
  }
  getAudio()
}

// 返回id
const rowKey = (e) => {
  return e.id
}

// 多选
const handleSelectionChange = (e) => {
  e.map(i => {
    if (data.selectionList.findIndex(j => j.audioId === i.id) === -1) {
      data.selectionList.push({
        audioId: i.id,
        audioName: i.name,
        audioType: i.audioType,
        categoryId: i.sceneId,
        type: i.type
      })
    }
  })
}

// 取消勾选
const handleSelectChange = (arr, row) => {
  if (arr.findIndex(i => i.id === row.id) === -1) {
    let index = data.selectionList.findIndex(i => i.audioId === row.id)
    data.selectionList.splice(index, 1)
  }
}

// 取消全选
const handleSelectAllChange = (e) => {
  if (e.length === 0) {
    for (let i = 0; i < audioData.tableData.length; i++) {
      for (let j = 0; j < data.selectionList.length; j++) {
        if (audioData.tableData[i].id === data.selectionList[j].audioId) {
          data.selectionList.splice(j, 1)
        }
      }
    }
  }
}

// 选择时段
const handleCheckTime = (e) => {
  data.form.timeId = e.timeId
  data.form.name = e.name
  data.disabledDate = [e.startTime, e.endTime]
  proxy.$modal.msgSuccess('选择成功！')
  dialogVisible_content.value = false
}

// 插播音频过多隐藏
const audioListHidden = ref(false)
// 确定
const getPush = () => {
  data.form.audioList = []
  data.form.audioList = JSON.parse(JSON.stringify(data.selectionList))
  proxy.$modal.msgSuccess('选择成功！')
  dialogVisible_audio.value = false
  audioListHidden.value = data.form.audioList.length >= 15 ? true : false
}

// 展开隐藏
const handleHidden = () => {
  audioListHidden.value = audioListHidden.value ? false : true
}

// 删除音频
const handleClose = (index) => {
  data.form.audioList.splice(index, 1)
}

// 删除所属门店
const getDelete = (index) => {
  data.form.tpresetContentInfoReq.splice(index, 1)
}

// 增加时间
function handlePushDate() {
  let boolean = false
  data.dateList.map(i => boolean = i.length === 0 ? true : false)
  if (boolean) {
    proxy.$modal.msgError('有时间段未填')
  } else {
    data.dateList.push([])
  }
}

// 删除时间
function handleDeleteDate(index) {
  data.dateList.splice(index, 1)
}

// 校验时间
const handleChangeDate = (e, index) => {
  if (e !== null) {
    data.form.listDate = []
    const start = new Date(e[0]).getTime()
    const end = new Date(e[1]).getTime()

    let disabledStart = new Date(data.disabledDate[0]).getTime()
    let disabledEnd = new Date(data.disabledDate[1]).getTime()

    if (start > disabledStart && end < disabledEnd) {
      for (let i = 0; i < data.dateList.length; i++) {
        if (i !== index) {
          let st = new Date(data.dateList[i][0]).getTime()
          let en = new Date(data.dateList[i][1]).getTime()

          if (start >= st && start <= en || end >= st && end <= en || start <= st && end >= en || end <= st && start >= en) {
            data.dateList[index] = []
            proxy.$modal.msgError("该时间段已设置！")
            return false
          }
        }
        data.form.listDate.push({
          startTime: data.dateList[i][0],
          endTime: data.dateList[i][1]
        })
      }
    } else {
      data.dateList[index] = []
      proxy.$modal.msgError("请在所选内容设定时间范围内插播")
    }
  }
}

// 禁选时间
const getDisabledDate = (e) => {
  if (data.disabledDate.length > 0) {
    return e.getTime() < new Date(data.disabledDate[0]).getTime() - 8.64e7 || e.getTime() > new Date(data.disabledDate[1]).getTime()
  }
}

// 所属企业
const index = ref(0)
const handleChangeTenant = (e, i) => {
  storeData.form.tenantId = e
  index.value = i
  getStore()
}

// 取消
const getClose = () => {
  proxy.$tab.closeOpenPage('/insert/insertContent')
}

// 提交
const getSubmit = () => {
  proxy.$refs.form.validate(valid => {
    if (valid) {
      submit(data.form).then(res => {
        if (res.code === 0) {
          proxy.$modal.msgSuccess('提交成功！')
          getClose()
        }
      })
    } else {
      return false
    }
  })
}

// 字典
const statusFormatter = (row) => {
  return proxy.selectDictLabel(sys_change_status.value, row.status)
}

const sceneFormatter = (row) => {
  let e = audioClassData.options.find(i => i.id === row.sceneId)
  return row.sceneId && e ? audioClassData.options.find(i => i.id === row.sceneId).name : '/'
}

// 监听
watch(() => audioData.form.type, (val) => {
  data.selectionList = []
  getAudio()
})
</script>

<style lang="scss" scoped>
.form {
  .el-form-item {
    width: 500px;
  }

  .el-table__row {
    .el-form-item {
      width: 100%;
    }
  }
}

.chooseAudio {
  .audio_box {
    display: flex;
    flex-wrap: wrap;

    .audioList {
      margin-right: 10px;
    }
  }
}

.audio_box_hidden {
  height: 135px;
  overflow: hidden;
}

.audio {
  width: 200px;
  height: 200px;
  border: 1px solid #e9e9eb;
  border-radius: 8px;
  margin-bottom: 15px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  box-shadow: 0 0 6px 0 #e9e9eb;

  span {
    width: 160px;
    height: 40px;
    line-height: 40px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    text-align: center;
  }
}

.date {
  display: flex;
  align-items: center;
  margin-bottom: 15px;

  .el-link {
    margin-left: 10px;
    font-size: 16px;
  }
}

.date:last-child {
  margin: 0;
}
</style>