<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>{{ element.takeName }}</h2>
                <div style="display:flex; justify-content: space-between;">
                  <span>{{ element.listDate.startTime }} - {{ element.listDate.endTime }}</span>
                  <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>当前门店：{{ storeData.options.find(i => i.id === element.storeId).name }}</span>
                <span>当前设备：{{ element.deviceIds }}</span>
                <span>当前状态：{{ proxy.selectDictLabel(sys_change_status, element.status) }}</span>
              </div>
              <template #reference>
                <span class="label">{{ element.takeName }}</span>
              </template>
            </el-popover>
          </div>
        </template>
      </draggable>
    </div>
  </div>
</template>

<script setup>
import { timeList, removeScene } from '@/api/content/scene'
import { useBusinessSelect, useStoreSelect } from '@/hooks/index'

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

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

const props = defineProps({
  path: {
    type: String,
    default: null
  }
})

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)

// 时间段
function getTime() {
  for (let i = 0; i <= data.timeList.length - 1; i++) {
    data.timeList[i].timer = []
    data.timeList[i].timer[0] = proxy.hoursToSeconds(data.timeList[i].time[0])
    data.timeList[i].timer[1] = proxy.hoursToSeconds(data.timeList[i].time[1])
  }
}
getTime()

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

// 时间轴
function getTimeList() {
  timeList({ storeId: storeId.value }).then(res => {
    for (let i = 0; i < res.data.length; i++) {
      for (let j = 0; j < res.data[i].listDate.length; j++) {
        let start = proxy.hoursToSeconds(res.data[i].listDate[j].startTime)
        let end = proxy.hoursToSeconds(res.data[i].listDate[j].endTime)
        const index1 = data.timeList.findIndex(e => {
          let st = e.timer[0]
          let en = e.timer[1]
          return st <= start && start <= en || st <= end && end <= en
        })
        data.timeList[index1].list.push({ ...res.data[i], listDate: res.data[i].listDate[j] })
        const index2 = data.timeList.findIndex(e => {
          let st = e.timer[0]
          let en = e.timer[1]
          return st >= start && en <= end || st >= end && en <= start
        })
        data.timeList[index2].list.push({ ...res.data[i], listDate: res.data[i].listDate[j] })
      }
    }
  })
}

// 拖拽内容
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(() => {
    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
  })
}
</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>