<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; margin: 0">
      <el-button type="primary" plain icon="Plus" @click="getDetail()"
        v-hasPermi="['content:setting:add', 'scene:presets:add', 'insert:insertContent:add']">新增</el-button>
    </el-form-item>
  </el-form>
  <div class="chart">
    <div class="time" v-for="item in data.timeList" :key="item">
      <div class="label">{{ item }}:00</div>
      <div class="line" />
    </div>
    <div class="grid">
      <draggable class="label_box" v-model="data.list" group="componentGroup" item-key="item"
        chosen-class="chosenClass">
        <template #item="{ element, index }">
          <div :style="{
        display: getDisplay(element), top: getTop(element), left: getLeft(element),
        height: getHeight(element), width: getWidth(element)
      }" :class="[element.status === 0 ? 'grid-item' : 'grid-item-disabled']">
            <el-popover placement="right" width="300px" popper-class="popper" :popper-style="popperStyle"
              :hide-after="0" trigger="click">
              <div class="title">
                <h2>{{ element.name }}</h2>
                <div style="display:flex; justify-content: space-between;">
                  {{ element.startTime }} - {{ element.endTime }}
                  <div style="display:flex; align-items: center">
                    <el-icon style="margin-right: 10px" @click="getDetail({ ...element, disabled: true })"
                      v-hasPermi="['content:setting:edit', 'scene:presets:edit', 'insert:insertContent:edit']">
                      <Edit />
                    </el-icon>
                    <el-icon @click="getDelete(element)"
                      v-hasPermi="['content:setting:delete', 'scene:presets:delete', 'insert:insertContent:delete']">
                      <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>
                <div style="height: 100%">
                  <div class="info">{{ element.startTime }} - {{ element.endTime }}</div>
                  <div class="info">{{ element.name }}</div>
                </div>
              </template>
            </el-popover>
          </div>
        </template>
      </draggable>
    </div>
  </div>
</template>

<script setup>
import { settimgTime, removeSetting } from '@/api/content/setting'
import { sceneTime, removeScene } from '@/api/scene/presets'
import { insetTime } from '@/api/insert/insertContent'
import { useBusinessSelect, useStoreSelect, useDeviceList } from '@/hooks/index'
import { checkPermi } from '@/utils/permission'

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: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'],
  list: [],
  number: {}
})

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

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

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

const modal = (res) => {
  data.list = []
  data.number = []
  if (res.code === 0 && res.data) {
    res.data.forEach(i => {
      i.listDate.forEach(j => {
        data.list.push({
          startTime: props.type === 'scene' ? j.startTime : j.startTime.split(' ')[1],
          endTime: props.type === 'scene' ? j.endTime : j.endTime.split(' ')[1],
          timeId: j.timeId,
          id: i.id,
          deviceIds: i.deviceIds,
          name: i.name ? i.name : i.takeName,
          status: i.status,
          storeId: i.storeId,
          sort: 0,
          index: 0,
          request: true
        })
      })
    })
    data.list.sort((a, b) => proxy.hoursToSeconds(a.startTime) - proxy.hoursToSeconds(b.startTime))
    for (let i = 0; i < data.list.length; i++) {
      if (data.list[i + 1] !== undefined) {
        let st = proxy.hoursToSeconds(data.list[i + 1].startTime)
        let start = proxy.hoursToSeconds(data.list[i].startTime)
        let end = proxy.hoursToSeconds(data.list[i].endTime)
        if (st >= start && st < end) {
          data.list[i + 1].sort = data.list[i].sort
          data.list[i + 1].index = data.list[i].index + 1
        } else {
          data.list[i + 1].sort = data.list[i].sort + 1
          data.list[i + 1].index = 0
        }
      }
    }
    for (let i = 0; i < data.list.length; i++) {
      const index = data.list[i].sort
      if (data.number[index]) {
        data.number[index].push(data.list[i])
      } else {
        data.number[index] = [data.list[i]]
      }
    }
  }
}

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

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

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

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

watch(() => storeData.storeId, (val) => {
  storeId.value = val
})

watch(storeId, (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
}

const getDisplay = (val) => {
  return val.startTime ? '' : 'none'
}

const getTop = (val) => {
  if (val.startTime && val.request) {
    return proxy.hoursToSeconds(val.startTime) / 3600 * 60 + 'px'
  }
}

const getLeft = (val) => {
  if (val.startTime && val.request) {
    return val.index * (100 / data.number[val.sort].length) + '%'
  }
}

const getHeight = (val) => {
  if (val.request) {
    if (val.startTime) {
      return (proxy.hoursToSeconds(val.endTime) - proxy.hoursToSeconds(val.startTime)) / 3600 * 60 + 'px'
    }
  } else {
    return 0
  }
}

const getWidth = (val) => {
  if (val.startTime && val.request) {
    let e = 100 / data.number[val.sort].length + '%'
    return `calc(${e} - 10px)`
  }
}
</script>

<style lang="scss" scoped>
.chart {
  height: 100vh;
  overflow-y: auto;
  position: relative;
  margin-left: 20px;
  user-select: none;

  .time {
    width: 100%;
    height: 60px;
    display: flex;

    .label {
      width: 50px;
      height: 100%;
      line-height: 60px
    }

    .line {
      width: calc(100% - 50px);
      border-top-width: 1px;
      border-left-width: 1px;
      border-right-width: 1px;
      border-bottom-width: 0;
      border-style: solid;
      border-color: #e3e3e3;
    }
  }

  .time:nth-child(24) .line {
    border-bottom-width: 1px;
  }

  .grid {
    position: absolute;
    top: 0;
    left: 50px;
    width: calc(100% - 50px);

    .label_box {
      height: 1440px;
    }

    .grid-item {
      position: absolute;
      margin: 0 5px;
      background-color: rgb(57 121 249 / 10%);
      border-left: 4px solid #3979F9;
      border-radius: 4px;
      overflow: hidden;
      color: #337ecc;

      .info {
        padding: 10px 0 0 10px;
      }
    }

    .grid-item-disabled {
      position: absolute;
      margin: 0 5px;
      background-color: rgb(144 147 153 / 20%);
      border-left: 4px solid #909399;
      border-radius: 4px;
      overflow: hidden;
      color: #909399;

      .info {
        padding: 10px 0 0 10px;
      }
    }
  }
}

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

.chosenClass {
  background: rgba(57, 121, 249, 0.1) !important;
}
</style>