<template>
  <div>
    <div class="mrg-b">
      <div class="mrg-b" v-if="tabIndex===2">
        <div class="mrg-b">
          <el-date-picker
            v-model="date"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </div>
        <div class="time-colot-wrap ">
          <span>图例说明：</span>
          <span>
            <span class="time-color color-free"></span><span>空闲</span>
          </span>
          <span>
            <span class="time-color color-bespeak"></span><span>预约中</span>
          </span>
          <span>
            <span class="time-color color-complete"></span><span>已预约</span>
          </span>
          <span>
            <span class="time-color color-overtime"></span><span>超时</span>
          </span>
          <span>
            <span class="time-color color-default"></span><span>禁用</span>
          </span>
        </div>
      </div>
      <el-table id="table" ref="table" stripe border :max-height="tableMaxHeight" :data="tableData">
        <template v-if="tabIndex===0">
          <table-column label="入库单号" prop="asnNo">
            <template slot-scope="scope">
              <p class="blue" @click="handleOpenDetail(scope.row)">{{ scope.row.asnNo }}</p>
            </template>
          </table-column>
          <table-column label="状态">
            <template slot-scope="scope">
              <p>{{ $utils.keyMatcher(scope.row.status, $keys.stockIn.status).name }}</p>
            </template>
          </table-column>
          <table-column label="入库单类型">
            <template slot-scope="scope">{{ $utils.keyMatcher(scope.row.asnType, $keys.stockIn.asnType).name }}</template>
          </table-column>
          <table-column label="货主">
            <template slot-scope="scope">
              <p>{{ scope.row.ownerCode }}</p>
              <p>{{ scope.row.ownerName }}</p>
            </template>
          </table-column>
          <table-column label="供应商" prop="supplierName"></table-column>
          <table-column label="承运商" prop="carrierName"></table-column>
          <table-column label="预计到货时间">
            <template slot-scope="scope">
              <p>从： {{ scope.row.fmEta }}</p>
              <p>到：{{ scope.row.toEta }}</p>
            </template>
          </table-column>
        </template>

        <template v-if="tabIndex===1">
          <table-column label="装车单号" prop="ldNo"></table-column>
          <table-column label="状态" prop="status">
            <template slot-scope="scope">
              <!-- <p>{{ $utils.keyMatcher(scope.row.status, $keys.stockOut.status).name }}</p> -->
            </template>
          </table-column>
          <table-column label="出库单状态">
            <template slot-scope="scope">
              <!-- <p>{{ $utils.keyMatcher(scope.row.soStatus, $keys.stockOut.soStatus).name }}</p> -->
            </template>
          </table-column>
          <table-column label="装车单类型">
            <!-- <template slot-scope="scope">{{ $utils.keyMatcher(scope.row.ldType, $keys.stockOut.ldType).name }}</template> -->
          </table-column>
          <table-column label="车牌号" prop="vehicleNo"></table-column>
          <table-column label="车型" prop="vehicleType"></table-column>
          <table-column label="驾驶员" prop="driver"></table-column>
          <table-column label="预计装车时间">
            <template slot-scope="scope">
              <p>从： {{ scope.row.fmEta }}</p>
              <p>到：{{ scope.row.toEta }}</p>
            </template>
          </table-column>
        </template>
        <template v-if="tabIndex===2">
          <table-column label="月台名称" width="150px">
            <template slot-scope="scope">
              <p>{{scope.row.dockName}}({{scope.row.dockUseTypeNameCn}})</p>
            </template>
          </table-column>
          <table-column :render-header="renderHeader" >
            <template slot-scope="scope">
              <div
                v-for="(item, index) in scope.row.data"
                :key="index"
                :class="['time-item-base', item.theme]"
                :data-label="item.label"
              ></div>
            </template>
          </table-column>
        </template>
      </el-table>
    </div>
    <div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>
<script>
import { time } from 'apec-fe-utils'
export default {
  data () {
    return {
      timeLabels: [
        { label: '00:00' },
        { label: '01:00' },
        { label: '02:00' },
        { label: '03:00' },
        { label: '04:00' },
        { label: '05:00' },
        { label: '06:00' },
        { label: '07:00' },
        { label: '08:00' },
        { label: '09:00' },
        { label: '10:00' },
        { label: '11:00' },
        { label: '12:00' },
        { label: '13:00' },
        { label: '14:00' },
        { label: '15:00' },
        { label: '16:00' },
        { label: '17:00' },
        { label: '18:00' },
        { label: '19:00' },
        { label: '20:00' },
        { label: '21:00' },
        { label: '22:00' },
        { label: '23:00' }
      ],
      date: time.formatDate(new Date()),
      date1: time.formatTimeObj(new Date())
    }
  },
  props: {
    tableData: Array,
    markDockData: Array,
    pageSize: Number,
    currentPage: Number,
    total: Number,
    type: String,
    tabIndex: Number,
    urlKey: String,
  },
  mounted () {
  },
  methods: {

    getData (url, param) { return this.$https.post(url, param) },

    handleOpenDetail (row) {
      const headUrl = this.$API.platform.DockDispatchList.getDetailHead
      const dockUrl = this.$API.platform.DockDispatchList.getDetaildock
      const listUrl = this.$API.platform.DockDispatchList.getDetailList
      const queryDock = this.$API.platform.DockDispatchList.queryDock
      console.log('3', row.asnNo)
      const param = {
        dockUseType: 'UNLOAD,LU',
        isEable: 'Y',
        orderNo: row.asnNo,
        asnNo: row.asnNo
      }
      this.$https.all([this.getData(headUrl, param), this.getData(dockUrl, param), this.getData(listUrl, param), this.getData(queryDock, param)]).then(res => {
        // console.log(res)
        const head = res[0].rows[0]
        const dock = res[1].rows
        const list = res[2].rows
        const queryDock = res[3].rows
        this.$emit('handleOpenDetail', head, dock, list, queryDock)
      })
    },

    formatTime (time) {
      if (time === null) return
      return parseInt(time.replace(':', ''))
    },
    initData () {
      let freeTheme = 'color-free'
      let overtimeTheme = 'color-overtime'
      let completeTheme = 'color-complete'
      const timeObj = time.formatTimeObj(new Date())
      const currentTime = `${timeObj.hh}:${timeObj.mm}`
      this.tableData.forEach((json, index) => {
        console.log(json)
        json.data = []
        let fmPlanTime, toPlanTime
        for (let i = 0; i < this.timeLabels.length; i++) {
          let item = this.timeLabels[i]

          let array = item.label.split(':')

          for (let j = 0; j < 4; j++) {
            let ms = parseInt(array[1]) + 15 * (j + 1)
            let obj
            let t, t1

            if (ms <= 0 || ms === 60) {
              ms = '00'
              array[0] = `${Number(array[0]) + 1}`
            }

            obj = {
              label: array[0] + ':' + ms,
              label2: currentTime,
              theme: 'color-default',
              dockCode: json.dockCode
            }

            t = this.formatTime(obj.label)

            t1 = this.formatTime(obj.label2)
            // console.log(t1)
            if (this.date === time.formatDate(new Date())) {
              if (t >= this.formatTime(json.fmTime1) && t <= this.formatTime(json.toTime1)) {
                if (t1 >= t) {
                  obj.theme = overtimeTheme
                } else {
                  obj.theme = freeTheme
                }
              } else if (t >= this.formatTime(json.fmTime2) && t <= this.formatTime(json.toTime2)) {
                if (t1 >= t) {
                  obj.theme = overtimeTheme
                } else {
                  obj.theme = freeTheme
                }
              } else if (t >= this.formatTime(json.fmTime3) && t <= this.formatTime(json.toTime3)) {
                if (t1 >= t) {
                  obj.theme = overtimeTheme
                } else {
                  obj.theme = freeTheme
                }
              }
            } else {
              if (t >= this.formatTime(json.fmTime1) && t <= this.formatTime(json.toTime1)) {
                obj.theme = freeTheme
              } else if (t >= this.formatTime(json.fmTime2) && t <= this.formatTime(json.toTime2)) {
                obj.theme = freeTheme
              } else if (t >= this.formatTime(json.fmTime3) && t <= this.formatTime(json.toTime3)) {
                obj.theme = freeTheme
              }
            }

            if (json.children) {
              for (let x = 0; x < json.children.length; x++) {
                let ele = json.children[x]
                fmPlanTime = ele.fmPlanTime
                toPlanTime = ele.toPlanTime

                if (fmPlanTime <= t && toPlanTime >= t) {
                  obj.theme = completeTheme
                }
              }
            }

            json.data.push(obj)
          }
        }
      })
    },

    renderHeader (h, { column, $index }) {
      return (
        h('div', { style: { 'padding': '2px' } }, [
          h('div', { style: { 'padding': 0 } }, this.timeLabels.map(item => {
            return h('span', {
              class: { 'item-base': true }
            }, item.label)
          }))
        ])
      )
    },

    choice () {
      const $trs = document.querySelectorAll('.el-table__body-wrapper .el-table__row')
      // console.log($tr)
      const theme = 'color-bespeak' // 预约颜色
      const selectedTheme = 'selected'
      const checkClass = 'time-item-base' // 检查是不是时间刻度的元素
      const freeTheme = 'color-free'
      const overtimeTheme = 'color-overtime'
      let x, y, ox, oy
      let moveFlag = false
      let arr1 = new Set()
      $trs.forEach((ele, index) => {
        // 鼠标按下
        ele.onmousedown = function (event) {
          moveFlag = true
          const selected = document.querySelectorAll('div.selected')
          if (selected) {
            selected.forEach(item => {
              item.classList.remove(theme, selectedTheme)
            })
          }
        }
        // 鼠标移动
        ele.onmousemove = function (event) {
          let o = event.target // 获得当前tr下的所有子元素
          if (moveFlag) {
            if (o.classList.contains(checkClass) && o.classList.contains(freeTheme) && !o.classList.contains(overtimeTheme)) {
              o.classList.add(theme)
              arr1.add(o.dataset.label)
              // console.log(arr1)
            }
          }
        }

        // 鼠标抬起
        ele.onmouseup = function (event) {
          moveFlag = false
          const selected = document.querySelectorAll('div.color-bespeak')
          if (selected) {
            selected.forEach(item => {
              item.classList.add(selectedTheme)
            })
          }
        }
      })
    },

    // 每页显示条数
    handleSizeChange (pageSize) {
      const query = { 'page.limitCount': pageSize, 'page.currentPage': this.currentPage }
      this.$emit('getList', this.urlKey, query)
    },

    // 当前页码
    handleCurrentChange (currentPage) {
      const query = { 'page.limitCount': this.pageSize, 'page.currentPage': currentPage }
      this.$emit('getList', this.urlKey, query)
    },

  },
  watch: {
    tableData: {
      handler (val) {
        if (this.tabIndex === 2) {
          this.markDockData.forEach((item, i) => {
            val.forEach((ele, j) => {
              if (ele.children) {
                if (item.dockCode === ele.dockCode) {
                  let obj1 = time.formatTimeObj(item.fmPlanTime)
                  let obj2 = time.formatTimeObj(item.toPlanTime)
                  const json = { fmPlanTime: `${obj1.hh}${obj1.mm}`, toPlanTime: `${obj2.hh}${obj2.mm}` }
                  ele.children.push(json)
                }
              } else {
                ele.children = []
                if (item.dockCode === ele.dockCode) {
                  let obj1 = time.formatTimeObj(item.fmPlanTime)
                  let obj2 = time.formatTimeObj(item.toPlanTime)
                  const json = { fmPlanTime: `${obj1.hh}${obj1.mm}`, toPlanTime: `${obj2.hh}${obj2.mm}` }
                  ele.children.push(json)
                }
              }
            })
          })
          this.initData()
          // this.$nextTick(() => {
          //   this.choice()
          // })
        }
      },
      deep: true
    },

  }

}
</script>
<style lang="scss">
.mrg-b {
  margin-bottom: 20px;
}
.mrg-l {
  margin-left: 10px;
}
.blue {
  cursor: pointer;
  color: #0682ea;
}
.time-colot-wrap span{
  display: inline-block;
  vertical-align: middle;
  padding: 0 5px

}
.time-color{
  display: inline-block;
  width: 20px;
  height: 20px;
}

.item-base {
  display: inline-block;
  width: 47.5px;
  border-left: 1px solid #bdb7b7;
  text-align: center;
}

.time-item-base {
  display: inline-block;
  width: 8px;
  height: 40px;
  margin: 0 2px;
}

.color-default {
  background-color: rgb(140,140,140);;
}

.color-free {
  background-color: rgb(240,240,240);
}

.color-bespeak {
  background-color: cyan;
}

.color-complete{
   background-color: blue;
}

.color-overtime{
  background-color: rgb(190, 190, 190);
  // background-color: red;
}
</style>
