<template>
  <div class='app-container'>
    <el-form class="form" label-width="100px" ref="form" :model="data.form" :rules="data.rules">
      <el-form-item class="list" label="预设音频：" prop="takeId">
        <div v-if="data.form.takeId" class="file" @click="getDialog">
          <img src="@/assets/icons/svg/file.svg" width="70" height="70" />
          <span>{{ data.form.takeName }}</span>
        </div>
        <el-button v-else icon="Plus" @click="getDialog">新增</el-button>
      </el-form-item>
      <el-form-item label="播放时间：" prop="listDate">
        <div class="date" v-for="(item, index) in data.dateList">
          <el-time-picker ref="picker" v-model="data.dateList[index]" is-range format="HH:mm:ss" value-format="HH:mm:ss"
            start-placeholder="开始时间" end-placeholder="结束时间" @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 label="关联设备：" style="width: 900px">
        <el-table :data="data.form.tpresetContentInfoReq">
          <el-table-column label="所属企业" align="center">
            <template #default="scope">
              <el-form-item :prop="`tpresetContentInfoReq.${scope.$index}.tenantId`"
                :rules="{ required: true, trigger: 'change' }">
                <el-select v-model="scope.row.tenantId" placeholder="请选择企业" style="width: 200px" filterable remote
                  :remote-method="businessRemote" remote-show-suffix @change="handleChange">
                  <el-option v-for="item in businessData.options" :key="item.id" :value="item.id" :label="item.name" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="所属门店" align="center">
            <template #default="scope">
              <el-form-item :prop="`tpresetContentInfoReq.${scope.$index}.storeId`"
                :rules="{ required: true, trigger: 'change' }">
                <el-select v-model="scope.row.storeId" placeholder="请选择门店" style="width: 200px" filterable remote
                  :remote-method="storeRemote" remote-show-suffix>
                  <el-option v-for="item in storeData.options" :key="item.id" :value="item.id" :label="item.name" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="所属设备" align="center">
            <template #default="scope">
              <el-form-item :prop="`tpresetContentInfoReq.${scope.$index}.deviceType`"
                :rules="{ required: true, trigger: 'change' }">
                <el-select v-model="scope.row.deviceType" placeholder="请选择所属设备">
                  <el-option v-for="item in deviceOptions" :key="item.clientTypeId" :value="item.clientTypeId"
                    :label="item.name" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="danger" link>删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item style="width: 800px">
        <el-button icon="Plus" @click="getAdd">新增关联</el-button>
      </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" title="导入内容" width="970">
      <el-form inline>
        <el-form-item v-for="item in data.tableData" :key="item.takeId">
          <div class="file hover" @click="handleChecked(item)">
            <img src="@/assets/icons/svg/file.svg" width="70" height="70" />
            <span>{{ item.takeName }}</span>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { list, timeSubmit } from '@/api/content/scene.js'
import { useBusinessSelect, useStoreSelect, useDeviceList } from '@/hooks/index.js'

// 公共方法
const { deviceOptions } = useDeviceList()
const { storeData, getStore, storeRemote } = useStoreSelect(true)
const { businessData, getBusiness, businessRemote } = useBusinessSelect(true)
getBusiness()

const { proxy } = getCurrentInstance();

// 遮罩层
const loading = ref(false)

const data = reactive({
  form: {
    listDate: [],
    tpresetContentInfoReq: [{}]
  },
  rules: {
    takeId: [{ required: true, message: '请选择预设音频', trigger: 'change' }],
    listDate: [{ type: 'array', required: true, message: '请选择播放时间', trigger: 'change' }]
  },
  dialogForm: {
    pageNum: 1,
    pageSize: 10
  },
  // 播放时间数组
  dateList: [[]],
  tableData: []
})

const total = ref(0)

// 列表
function getList() {
  loading.value = true
  list(data.dialogForm).then(res => {
    if (res.code === 0) {
      data.tableData = res.data.records
      total.value = res.data.total
      loading.value = false
    }
  })
}

// 弹窗
const dialogVisible = ref(false)
// 打开弹窗
function getDialog() {
  dialogVisible.value = true
  getList()
}
// 选择预设音频
function handleChecked(item) {
  data.form.takeId = item.takeId
  data.form.takeName = item.takeName
  dialogVisible.value = false
  proxy.$modal.msgSuccess('选择成功！')
}

// 增加时间
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.listDate = []
    data.form.listDate = []
    const start = proxy.hoursToSeconds(e[0])
    const end = proxy.hoursToSeconds(e[1])
    for (let i = 0; i < data.dateList.length; i++) {
      if (i !== index) {
        let st = proxy.hoursToSeconds(data.dateList[i][0])
        let en = proxy.hoursToSeconds(data.dateList[i][1])
        if (start >= st && start <= en || end >= st && end <= en || start <= st && end >= en) {
          data.dateList.splice(index, 1)
          proxy.$modal.msgError("该时间段已设置！")
          return false
        }
      }
    }
    data.dateList.map(i => {
      data.form.listDate.push({
        startTime: i[0],
        endTime: i[1]
      })
    })
  }
}

// 添加门店
const getAdd = () => {
  data.form.tpresetContentInfoReq.push({})
}

const handleChange = (e) => {
  storeData.form.tenantId = e
  getStore()
}

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

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

</script>

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

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

.list {
  :deep(.el-form-item__content) {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }
}

.file {
  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;
  line-height: 10px;
  cursor: pointer;

  span {
    margin-top: 20px;
  }
}

.hover:hover {
  box-shadow: 0 0 10px 2px #a0cfff;
  transition: all 0.5s;
}

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

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

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