<template>
  <div>
    <el-form ref="form" :model="formData" inline label-position="top">
      <el-row :gutter="40">
        <el-col :span="24">
          <el-collapse v-model="activeNames">
            <el-collapse-item title="基础信息" name="1">
              <el-form-item label="入库单号：" class="form-item">
                <span>{{formData.asnNo}}</span>
              </el-form-item>
              <el-form-item label="状态：" class="form-item">
                <span>{{ $utils.keyMatcher(formData.status, $keys.stockIn.status).name }}</span>
              </el-form-item>
              <el-form-item label="入库单类型" class="form-item">
                <span>{{ $utils.keyMatcher(formData.asnType, $keys.stockIn.asnType).name }}</span>
              </el-form-item>
              <el-form-item label="物流单号" class="form-item">
                <span>{{ formData.logisticNo }}</span>
              </el-form-item>
              <el-form-item label="货主编码：" class="form-item">
                <span>{{formData.ownerCode}}</span>
              </el-form-item>
              <el-form-item label="货主名称：" class="form-item">
                <span>{{formData.ownerName}}</span>
              </el-form-item>
              <el-form-item label="供应商名称：" class="form-item">
                <span>{{formData.supplierName}}</span>
              </el-form-item>
              <el-form-item label="承运商名称：" class="form-item">
                <span>{{formData.carrierName}}</span>
              </el-form-item>
              <el-form-item label="预计到货时间从：" class="form-item">
                <span>{{formData.fmEta}}</span>
              </el-form-item>
              <el-form-item label="预计到货时间到：" class="form-item">
                <span>{{formData.toEta}}</span>
              </el-form-item>
              <el-form-item label="订单时间：" class="form-item">
                <span>{{formData.orderTime}}</span>
              </el-form-item>
              <el-form-item label="是否已经预约月台：" class="form-item">
                <span>{{formData.isAppointDock}}</span>
              </el-form-item>
              <el-form-item label="优先级别：" class="form-item">
                <span>{{formData.priority}}</span>
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
        </el-col>
      </el-row>
      <el-row class="row-mrg-t">
        <el-col :span="24">
          <el-collapse v-model="activeNames">
            <el-collapse-item title="调度明细" name="2">
              <el-row>
                <el-button type="primary" @click="handleAdd">新增</el-button>
                <el-button type="primary" @click="handleDel">删除</el-button>
                <el-button type="primary" @click="handleOccupy">占用月台</el-button>
                <el-button type="primary" @click="handleRelease">释放月台</el-button>
              </el-row>
              <el-row>
                <el-table :data="listData" @selection-change="handleChange">
                  <el-table-column type="selection" fixed align="center" width="55"></el-table-column>
                  <el-table-column label="月台预约号" prop="appointId">
                    <template slot-scope="scope">
                      <p class="blue">{{scope.row.appointId}}</p>
                    </template>
                  </el-table-column>
                  <el-table-column label="状态">
                    <template
                      slot-scope="scope"
                    >{{ $utils.keyMatcher(scope.row.status, $keys.platform.status).name }}</template>
                  </el-table-column>
                  <el-table-column label="适用车型" prop="vehicleType"></el-table-column>
                  <el-table-column label="月台" prop="dock">
                    <template slot-scope="scope">
                      <p>{{scope.row.dockCode}}</p>
                      <p>{{scope.row.dockName}}</p>
                    </template>
                  </el-table-column>
                  <el-table-column label="预约时长(分钟)" prop="planMinute"></el-table-column>
                  <el-table-column label="预约时间" prop="planTime">
                    <template slot-scope="scope">
                      <p>从：{{scope.row.fmPlanTime}}</p>
                      <p>到：{{scope.row.toPlanTime}}</p>
                    </template>
                  </el-table-column>
                  <el-table-column label="车牌号" prop="vehicleNo" :formatter="formatColumn"></el-table-column>
                  <el-table-column label="驾驶员" prop="driver"></el-table-column>
                  <el-table-column label="实际时间">
                    <template slot-scope="scope">
                      <p>从：{{scope.row.fmActTime}}</p>
                      <p>到：{{scope.row.toActTime}}</p>
                    </template>
                  </el-table-column>
                  <el-table-column label="实际时长(分钟)" prop="actMinute"></el-table-column>
                </el-table>
              </el-row>
            </el-collapse-item>
          </el-collapse>
        </el-col>
      </el-row>
      <el-row>
        <el-collapse v-model="activeNames">
          <el-collapse-item title="月台调度看板" name="3">
            <div>
              <div class="mrg-b">
                <el-date-picker
                  v-model="date1"
                  value-format="yyyy-MM-dd"
                  type="date"
                  placeholder="选择日期"
                ></el-date-picker>
                <el-button class="mrg-l" type="primary" @click="handleSearch">查询</el-button>
              </div>
              <div class="time-colot-wrap">
                <span>开始时间：
                  <el-date-picker
                    v-model="date2"
                    format="yyyy-MM-dd HH:mm"
                    value-format="yyyy-MM-dd HH:mm"
                    type="datetime"
                    placeholder="选择日期"
                  ></el-date-picker>
                </span>
                <span>结束时间：
                  <el-date-picker
                    v-model="date3"
                    format="yyyy-MM-dd HH:mm"
                    value-format="yyyy-MM-dd HH:mm"
                    type="datetime"
                    placeholder="选择日期"
                  ></el-date-picker>
                </span>
                <el-button type="primary" @click="handleConfirm">确认</el-button>
                <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>
            <div>
              <el-table
                id="table"
                ref="table"
                stripe
                border
                :max-height="tableMaxHeight"
                :data="dockData"
              >
                <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"
                      :data-dockCode="item.dockCode"
                    ></div>
                  </template>
                </table-column>
              </el-table>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-row>
    </el-form>
    <div class="row-mrg-t">
      <el-button v-auth="50100020207" type="primary" @click="$router.back()">关闭</el-button>
    </div>

    <goods-form
      :goodsFormVisible="goodsFormVisible"
      :mode="mode"
      :code="code"
      :tableData="dockData"
      :currentRow="currentRow"
      @close="goodsFormVisible=false"
      @handleConfirm="handleSave"
      @handleConfirmAdd="handleSaveAdd"
      @handleImplement="handleImplement"
    ></goods-form>
  </div>
</template>
<script>
import { time } from 'apec-fe-utils'
import GoodsForm from './childrenForm/goods-form'
export default {
  components: {
    GoodsForm
  },
  created () {
    this.formData = this.$route.params[0]
    this.dockData = this.$route.params[1]
    this.listData = this.$route.params[2]
    this.markDockData = this.$route.params[3]
    this.objFormat()
    console.log(this.dockData)
    // this.chenckTime()
  },
  data () {
    return {
      needRefresh: false,
      activeNames: ['1', '2', '3'],
      goodsFormVisible: false,
      listData: [],
      dockData: [],
      markDockData: [],
      formData: {},
      date1: time.formatDate(new Date()),
      date2: '',
      date3: '',
      dockCode: '',
      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' }
      ],
      arr: [],
      rows: [],
      mode: '',
      code: '',
      currentRow: {}
    }
  },
  mounted () { },
  methods: {

    formatTime (time) {
      if (time === null) return
      return parseInt(time.replace(':', ''))
    },
    initData () {
      let freeTheme = 'color-free'
      let completeTheme = 'color-complete'
      let overtimeTheme = 'color-overtime'
      const timeObj = time.formatTimeObj(new Date())
      const currentTime = `${timeObj.hh}:${timeObj.mm}`
      const nowDate = time.formatDate(new Date())
      this.dockData.forEach((json, index) => {
        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}` < 10 ? `0${Number(array[0]) + 1}` : `${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)
            if (this.date1 === nowDate) {
              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
                // console.log(ele.currentDate === nowDate)
                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 vm = this
      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()
      let arr2 = 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', arr1)
              arr2.add(o.dataset.dockcode)
            }
          }
        }

        // 鼠标抬起
        ele.onmouseup = function (event) {
          let o = event.target
          moveFlag = false
          const selected = document.querySelectorAll('div.color-bespeak')
          if (selected) {
            selected.forEach(item => {
              item.classList.add(selectedTheme)
            })
          }
          this.arr = Array.from(arr1).map(item => {
            return parseInt(item.replace(':', ''))
          }).sort((a, b) => {
            return a - b
          })
          vm.dockCode = [...arr2]
          vm.date2 = `${vm.date1} ${String(this.arr[0]).substring(0, 2)}:${String(this.arr[0]).substring(2)}`
          vm.date3 = `${vm.date1} ${String(this.arr[this.arr.length - 1]).substring(0, 2)}:${String(this.arr[this.arr.length - 1]).substring(2)}`
        }
      })
    },

    objFormat () {
      const now = time.formatDate(new Date())
      if (this.dockData.length && this.markDockData.length) {
        this.markDockData.forEach((item, i) => {
          let obj1 = time.formatTimeObj(item.fmPlanTime)
          let obj2 = time.formatTimeObj(item.toPlanTime)
          let itemTime = `${obj1.y}-${obj1.m}-${obj1.d}`
          this.dockData.forEach((ele, j) => {
            if (ele.children) {
              if (itemTime === now && item.dockCode === ele.dockCode) {
                const json = { currentDate: `${obj1.y}-${obj1.m}-${obj1.d}`, 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 = { currentDate: `${obj1.y}-${obj1.m}-${obj1.d}`, fmPlanTime: `${obj1.hh}${obj1.mm}`, toPlanTime: `${obj2.hh}${obj2.mm}` }
              //   ele.children.push(json)
              // }
              if (itemTime === now && item.dockCode === ele.dockCode) {
                const json = { currentDate: `${obj1.y}-${obj1.m}-${obj1.d}`, fmPlanTime: `${obj1.hh}${obj1.mm}`, toPlanTime: `${obj2.hh}${obj2.mm}` }
                ele.children.push(json)
              }
            }
          })
        })
      }
    },

    getData (url, param) {
      return this.$https.post(url, param)
    },
    handleSearch () {
      const dockurl = this.$API.platform.DockDispatchList.getqueryWmDock
      const url = this.$API.platform.DockDispatchList.getDetaildock
      const param = { dockUseType: 'UNLOAD,LU', isEable: 'Y' }
      const dockParam = { currentDate: JSON.stringify(this.date1), type: JSON.stringify('asn') }
      this.$https.all([this.getData(url, param), this.getData(dockurl, dockParam)]).then(res => {
        // console.log(res)
        this.dockData = res[0].rows
        this.markDockData = res[1]
        this.objFormat()
        this.initData()
      })
    },

    // 重新请求
    reGetData () {
      const dockUrl = this.$API.platform.DockDispatchList.getDetaildock // 看板
      const wmDockUrl = this.$API.platform.DockDispatchList.getqueryWmDock // 预约时间
      const listUrl = this.$API.platform.DockDispatchList.getDetailList // 列表
      console.log('2', this.formData.asnNo)
      const param = {
        dockUseType: 'UNLOAD,LU',
        isEable: 'Y',
        orderNo: this.formData.asnNo,
        asnNo: this.formData.asnNo
      }

      const dockParam = { currentDate: JSON.stringify(this.date1), type: JSON.stringify('asn') }
      this.$https.all([this.getData(dockUrl, param), this.getData(listUrl, param), this.getData(wmDockUrl, dockParam)]).then(res => {
        console.log(res)
        this.dockData = res[0].rows
        this.listData = res[1].rows
        this.markDockData = res[2]
        this.objFormat()
        this.initData()
      })
    },

    handleConfirm () {
      const url = this.$API.platform.DockDispatchList.saveTime
      const wmDockDetail = { statue: 'APPOINT', dockCode: this.dockCode[0], orderType: 'ASN', orderNo: this.formData.asnNo }
      const param = {
        wmDockDetail: JSON.stringify(wmDockDetail),
        appointFm: this.date2,
        appointTo: this.date3
      }
      this.$https.post(url, param).then(res => {
        this.reGetData()
      })
    },
    handleChange (selection) {
      this.rows = selection.map(item => {
        return item
      })
      console.log(this.rows)
    },

    checklength () {
      if (!this.rows.length) {
        this.$message.warning('请选择数据')
        return false
      } else {
        return true
      }
    },

    // 新增
    handleAdd () {
      this.mode = 'add'
      this.goodsFormVisible = true
    },
    // 删除
    handleDel () {
      if (!this.checklength()) return
      const url = this.$API.platform.DockDispatchList.delTime
      const param = { wmDockDetails: JSON.stringify(this.rows) }
      this.$https.post(url, param).then(res => {
        this.reGetData()
      })
    },
    // 执行
    handleImplement (data, code) {
      let url
      if (code === 'qccupy') {
        url = this.$API.platform.DockDispatchList.occupy
      } else {
        url = this.$API.platform.DockDispatchList.release
      }
      console.log(111, data)
      const wmDockDetail = { ...this.rows[0], ...data }
      const param = { wmDockDetail: JSON.stringify(wmDockDetail) }
      this.$https.post(url, param).then(res => {
        this.reGetData()
        this.goodsFormVisible = false
      })
    },

    // 占用月台
    handleOccupy () {
      if (!this.checklength()) return
      if (this.rows.length > 1) return this.$message.warning('只能选择一条数据')
      if (this.rows[0].status !== 'APPOINT') return this.$message.warning('不是预约状态')
      this.mode = 'other'
      this.code = 'qccupy'
      this.currentRow = { ...this.rows[0], ...{ status: 'USE' } }
      // this.currentRow = this.rows[0]
      this.goodsFormVisible = true
    },
    // 释放月台
    handleRelease () {
      if (!this.checklength()) return
      if (this.rows.length > 1) return this.$message.warning('只能选择一条数据')
      if (this.rows[0].status !== 'USE') return this.$message.warning('不是占用状态')
      this.mode = 'other'
      this.code = 'release'
      this.currentRow = { ...this.rows[0], ...{ status: 'RELEASE' } }
      this.goodsFormVisible = true
    },

    handleSave (data) {
      const url = this.$API.platform.DockDispatchList.saveTime
      const wmDockDetail = { ...{ vehicleType: 'VE', orderType: 'ASN', orderNo: this.formData.asnNo }, ...data }
      const param = {
        wmDockDetail: JSON.stringify(wmDockDetail)
      }
      this.$https.post(url, param).then(res => {
        this.reGetData()
        this.goodsFormVisible = false
      })
    },
    handleSaveAdd () {

    },

  },
  watch: {
    dockData: {
      handler () {
        this.initData()
        this.$nextTick(() => {
          this.choice()
        })
      },
      deep: true
    },
  },
  beforeRouteLeave (to, from, next) {
    this.needRefresh && (to.meta.needRefresh = true)
    next()
  }
}
</script>
 <style lang="scss" scoped>
.el-collapse {
  border: 1px solid #ebeef5;
  .el-collapse-item__header {
    padding-left: 10px;
    font-weight: bold;
    background-color: #f5f5f5;
    border-bottom: 1px solid #ebeef5 !important;
  }
  .el-collapse-item__content {
    padding-top: 25px;
    padding-left: 15px;
  }
}
.row-mrg-t {
  margin-top: 20px;
}
.operation-info {
  display: flex;
  justify-content: space-between;
}
.form-item {
  min-width: 260px;
}
.blue {
  cursor: pointer;
  color: #0682ea;
}
.mrg-b {
  margin-bottom: 20px;
}
.mrg-l {
  margin-left: 10px;
}
</style>
