<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 :title="data.form.takeName">{{ 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 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" prop="tpresetContentInfoReq">
        <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="handleChangeTenant($event, scope.$index)">
                  <el-option v-for="item in businessData.options" :key="item.id" :value="item.id.toString()"
                    :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 data.business_store[scope.$index]" :key="item.id"
                    :value="item.id.toString()" :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 @click="getDelete(scope.$index)">删除</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-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" 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-empty v-show="data.tableData.length === 0" description="暂无数据" />
    </el-dialog>
  </div>
</template>

<script setup>
import { list, timeDetail, timeSubmit } from '@/api/scene/presets'
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 { sys_change_status } = proxy.useDict("sys_change_status")

// 遮罩层
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' }],
    tpresetContentInfoReq: [{ type: 'array', required: true, message: '请新增关联设备', trigger: 'change' }],
    status: [{ required: true, message: '请选择当前状态', trigger: 'change' }]
  },
  dialogForm: {
    pageNum: 1,
    pageSize: 10
  },
  // 播放时间数组
  dateList: [[]],
  tableData: [],
  // 企业—门店
  business_store: [],
})

const total = ref(0)

const getAudioList = () => {
  if (proxy.$route.query.audioList) {
    let e = JSON.parse(proxy.$route.query.audioList)
    data.form.takeId = e.takeId
    data.form.takeName = e.takeName
  }
}
getAudioList()

// 详情
const getDetail = (id) => {
  let e = proxy.$route.query
  if (e.id) {
    timeDetail({ 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()

// 列表
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() {
  if (!proxy.$route.query.disabled) {
    dialogVisible.value = true
    getList()
  } else {
    proxy.$modal.msgError('不可编辑已选音频')
  }
}

// 选择预设音频
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.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 index = ref(0)
const handleChangeTenant = (e, i) => {
  storeData.form.tenantId = e
  index.value = i
  getStore()
}

watch(() => data.form.tpresetContentInfoReq, (val) => {
  if (val.length > 0) {
    val.map(i => {
      if (data.form.id && businessData.options.find(j => j.id == i.tenantId == undefined)) {
        businessData.options.push({
          id: i.tenantId,
          name: i.tenantName
        })
      }
      storeData.form.tenantId = i.tenantId
      getStore()
    })
  }
})

watch(() => storeData.options, (val) => {
  data.business_store[index.value] = val
  data.form.tpresetContentInfoReq.map(i => {
    if (data.form.id && val.find(j => j.id == i.storeId == undefined)) {
      storeData.options.push({
        id: i.storeId,
        name: i.storeName
      })
    }
  })
})

// 删除关联设备
const getDelete = (index) => {
  data.form.tpresetContentInfoReq.splice(index, 1)
}

// 提交
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('/scene/presets')
}

</script>

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

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

.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;
  cursor: pointer;

  span {
    width: 160px;
    height: 40px;
    line-height: 40px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    text-align: center;
    margin-top: 25px;
    padding: 0 10px;
  }
}

.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>