<template>
  <el-form class="search" inline>
    <el-form-item>
      <el-select v-model="organizationIds" placeholder="请选择企业" style="width: 200px" filterable remote
        :remote-method="businessRemote" remote-show-suffix>
        <el-option v-for="item in businessData.options" :key="item.id" :value="item.id" :label="item.name" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-select v-model="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>
    <el-form-item style="float:right">
      <el-button type="primary" icon="Plus" @click="getDetail()">新增预设</el-button>
    </el-form-item>
  </el-form>
  <div class="timer">
    <div class="item" v-for="(item, index) in data.timeList" :key="item">
      <div class="value">
        <span>{{ item.time[0].slice(0, 5) }}</span>
        <span class="solid"></span>
      </div>
      <draggable class="label_box" v-model="item.list" group="componentGroup" :item-key="index.toString()"
        :move="onMove" :end="onEnd">
        <template #item="{ element, index }">
          <div @mousedown.stop style="width: 100%">
            <el-popover placement="bottom" trigger="click" width="300px" popper-class="popper"
              :popper-style="popperStyle" :hide-after="0">
              <div class="title">
                <h2>{{ props.type === 'scene' ? element.takeName : element.name }}</h2>
                <div style="display:flex; justify-content: space-between;">
                  <span v-if="props.type === 'scene'">
                    {{ element.listDate.startTime }} - {{ element.listDate.endTime }}</span>
                  <div v-else>
                    <div v-if="element.listData">{{ element.listDate.startTime.split(' ')[0] }}</div>
                    <div v-if="element.listData">
                      {{ element.listDate.startTime.split(' ')[1] }} - {{ element.listDate.endTime.split(' ')[1] }}
                    </div>
                  </div>
                  <div style="display:flex; align-items: center">
                    <el-icon style="margin-right: 10px" @click="getDetail(element)">
                      <Edit />
                    </el-icon>
                    <el-icon @click="getDelete(element)">
                      <Delete />
                    </el-icon>
                  </div>
                </div>
              </div>
              <div class="main">
                <span>当前门店：{{ storeName(element.storeId) }}</span>
                <span>当前设备：{{ deviceName(element.deviceIds) }}</span>
                <span>当前状态：{{ proxy.selectDictLabel(sys_change_status, element.status) }}</span>
              </div>
              <template #reference>
                <span class="label">{{ props.type === 'scene' ? element.takeName : element.name }}</span>
              </template>
            </el-popover>
          </div>
        </template>
      </draggable>
    </div>
  </div>
</template>

<script setup>
import { settimgTime, removeSetting } from '@/api/content/setting'
import { sceneTime, removeScene } from '@/api/content/scene'
import { useBusinessSelect, useStoreSelect, useDeviceList } from '@/hooks/index'

const { storeData, getStore, storeRemote } = useStoreSelect()
const { businessData, getBusiness, businessRemote } = useBusinessSelect(true)
getBusiness()
const { deviceOptions } = useDeviceList()

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

const props = defineProps({
  path: String,
  type: String,
  date: Date
})

const data = reactive({
  timeList: [
    { time: ['00:00:00', '01:00:00'], list: [] },
    { time: ['01:00:00', '02:00:00'], list: [] },
    { time: ['02:00:00', '03:00:00'], list: [] },
    { time: ['03:00:00', '04:00:00'], list: [] },
    { time: ['04:00:00', '05:00:00'], list: [] },
    { time: ['05:00:00', '06:00:00'], list: [] },
    { time: ['06:00:00', '07:00:00'], list: [] },
    { time: ['07:00:00', '08:00:00'], list: [] },
    { time: ['08:00:00', '09:00:00'], list: [] },
    { time: ['09:00:00', '10:00:00'], list: [] },
    { time: ['10:00:00', '11:00:00'], list: [] },
    { time: ['11:00:00', '12:00:00'], list: [] },
    { time: ['12:00:00', '13:00:00'], list: [] },
    { time: ['13:00:00', '14:00:00'], list: [] },
    { time: ['14:00:00', '15:00:00'], list: [] },
    { time: ['15:00:00', '16:00:00'], list: [] },
    { time: ['16:00:00', '17:00:00'], list: [] },
    { time: ['17:00:00', '18:00:00'], list: [] },
    { time: ['18:00:00', '19:00:00'], list: [] },
    { time: ['19:00:00', '20:00:00'], list: [] },
    { time: ['20:00:00', '21:00:00'], list: [] },
    { time: ['21:00:00', '22:00:00'], list: [] },
    { time: ['22:00:00', '23:00:00'], list: [] },
    { time: ['23:00:00', '00:00:00'], list: [] },
    { time: ['00:00:00', '01:00:00'], list: [] }
  ],
})

// 时间轴表单
const organizationIds = ref(null)
const storeId = ref(null)
const nowDate = ref(new Date(props.date))

// 时间段
function getTime() {
  for (let i = 0; i <= data.timeList.length - 1; i++) {
    data.timeList[i].timer = []
    let start = proxy.hoursToSeconds(data.timeList[i].time[0])
    let end = proxy.hoursToSeconds(data.timeList[i].time[1])
    if (props.type === 'setting') {
      let y = nowDate.value.getFullYear()
      let m = nowDate.value.getMonth()
      let d = nowDate.value.getDate()
      start = new Date(y, m, d).getTime() + start * 1000
      end = new Date(y, m, d).getTime() + end * 1000
    }
    data.timeList[i].timer[0] = start
    data.timeList[i].timer[1] = end
  }
}
getTime()

const popperStyle = ref({
  padding: 0,
  borderRadius: '10px'
})

// 时间轴
function getTimeList() {
  data.timeList.map(i => i.list = [])
  if (props.type === 'scene') {
    sceneTime({ storeId: storeId.value }).then(res => {
      modal(res)
    })
  } else {
    settimgTime({ nowDate: proxy.parseTime(nowDate.value.getTime(), "{y}-{m}-{d}"), storeId: storeId.value }).then(res => {
      modal(res)
    })
  }
}

const modal = (res) => {
  res.data.forEach(i => {
    i.listDate.forEach(j => {
      let start = null
      let end = null
      if (props.type === 'scene') {
        start = proxy.hoursToSeconds(j.startTime)
        end = proxy.hoursToSeconds(j.endTime)
      } else {
        start = new Date(j.startTime).getTime()
        end = new Date(j.endTime).getTime()
      }
      const list = data.timeList.filter((e, index) => {
        let st = e.timer[0]
        let en = e.timer[1]
        if (index !== 24) {
          return start >= st && end <= en || start <= st && end >= en
        }
      })
      list.map(e => {
        e.list = []
        e.list.push({ ...i, listDate: j })
      })
    })
  })
}

watch(() => props.date, (val) => {
  nowDate.value = val
  getTime()
  getTimeList()
})

// 拖拽内容
function onMove(params) {
  if (params.to.childElementCount < 1) {
    return true
  } else {
    return false
  }
}

// 拖拽结束
function onEnd(params) {
  if (params.from.className === 'contentList' &&
    params.to.className === 'label_box' ||
    params.from.className === 'label_box' &&
    params.from.__draggable_component__.itemKey !== params.to.__draggable_component__.itemKey) {
    let query = {
      value: params.item._underlying_vm_.value,
      label: params.item._underlying_vm_.label
    }
    getDetail(query)
  }
}

// 删除
const getDelete = (row) => {
  proxy.$modal.confirm(`是否删除预设名称为：${row.takeName}的数据?`).then(() => {
    if (props.type === 'setting') {
      removeSetting({ id: row.id }).then(res => {
        if (res.code === 0) {
          proxy.$modal.msgSuccess('删除成功！')
          getTimeList()
        }
      })
    } else {
      removeScene({ id: row.id }).then(res => {
        if (res.code === 0) {
          proxy.$modal.msgSuccess('删除成功！')
          getTimeList()
        }
      })
    }
  }).catch(() => { })
}

watch(() => businessData.options, (val) => {
  if (val) {
    organizationIds.value = val[0].id
  }
})

watch(organizationIds, (val) => {
  if (val) {
    storeData.form.tenantId = val
    getStore()
  }
})

watch(() => storeData.storeId, (val) => {
  data.timeList.map(i => i.list = [])
  storeId.value = val
  if (val) {
    getTimeList()
  }
})

// 新增预设
function getDetail(query) {
  proxy.$router.push({
    path: props.path,
    query
  })
}

// 计算
const deviceName = (val) => {
  let e = deviceOptions.value.find(i => i.clientTypeId == val)
  return e ? e.name : val
}

const storeName = (val) => {
  let e = storeData.options.find(i => i.id === val)
  return e ? e.name : val
}
</script>

<style lang="scss" scoped>
.timer {
  display: flex;
  flex-direction: column;
  width: calc(100% - 50px);
  margin-left: 50px;
  overflow-y: auto;
  padding: 20px 20px 20px 50px;

  .item {
    width: 100%;
    height: 100px;
    line-height: 100px;
    position: relative;
    border-left: 1px solid #e3e3e3;
    display: flex;
    align-items: center;

    .value {
      width: 100px;
      margin-left: -50px;

      .solid {
        border-top: 1px solid #e3e3e3;
        width: 100%;
        position: absolute;
        top: 50px;
        left: 0;
      }
    }

    .label_box {
      display: flex;
      width: 100%;
      z-index: 99;
      position: absolute;
      top: 70px;

      .label {
        background-color: #ebf1fe;
        color: #3979F9;
        height: 60px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-left: 4px solid #3979F9;
        border-radius: 4px;
        margin-right: 10px;
        font-size: 12px;
        padding: 0 20px;
        flex: 1;
      }
    }
  }
}

.popper {

  .title,
  .main {
    line-height: 35px;
    padding: 20px;
  }

  .title {
    background-color: #337ecc;
    color: #FFF;
    border-radius: 10px 10px 0 0;
    font-size: 16px;
  }

  .main {
    display: flex;
    flex-direction: column;
  }
}

.search {
  padding-left: 70px;
}
</style>