<template>
  <div class="page_container">
    <el-row type="flex" class="t_box" justify="space-between">
      <el-col :span="20">
        <div style="height: calc(100% - 1rem);overflow: hidden;">
          <el-tabs v-model="activeName" @tab-click="tabClick" style="height: 100%;">
            <el-tab-pane label="自定义" name="zdy">
              <el-row type="flex" class="r_box">
                <el-col class="point_item" v-for="(e, i) in dataList" :key="'zdy' + i">
                  <el-popover
                    placement="bottom"
                    trigger="manual"
                    :ref="`popover-${i}`">
                    <el-row type="flex" justify="space-between" align="middle" style="margin-bottom: .1rem">
                      <el-col :span="18"><el-input placeholder="修改名称" v-model="stationName" @focus="show" data-layout="normal"></el-input></el-col>
                      <el-button type="success" icon="el-icon-check" size="mini" style="height: .3rem" :disabled="disabled" @click="_updateStation(e, i)"></el-button>
                    </el-row>
                    <el-row type="flex" justify="space-between">
                      <el-button class="task_button" :class="{'task_checked': e.action_type === el.value}" v-for="el in radioOption" :key="el.value" @click="radioInput(e, i, el.value)">{{ el.label }}</el-button>
                    </el-row>
                    <div slot="reference" class="zbox point_item_i" @click="openPopover(i)"><p>{{ e.station_name }}</p></div>
                  </el-popover>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="任务链" name="rwl">
              <el-row type="flex" class="r_box">
                <el-col class="point_item" v-for="(e, i) in linkData" :key="'rwl' + i">
                  <div class="zbox point_item_i" @click="handleLinkCheck(e)"><p>{{ e.chain_name }}</p></div>
                </el-col>
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </div>
        <el-row type="flex" class="result_w" justify="start" align="top">
          <el-col class="pp_item" v-for="(e, i) in newData" :key="'new' + i">
            <el-row type="flex" align="middle">
              <div class="point_item point_checked">
                <el-row type="flex" align="middle" class="zbox">
                  <el-col :span="18">
                    <p style="padding-left: 0.02rem;">{{ e.station_name }}</p>
                  </el-col>
                  <el-col :span="6" style="border-left: 1px solid #fff;"><p style="font-size: .12rem;font-weight: 700;text-align: center;padding-right: 0.02rem;">{{ radioOption | findByValue(e.action_type) }}</p></el-col>
                </el-row>
              </div>
              <i class="el-icon-caret-right icon-caret-right" :style="i === newData.length - 1 ? 'visibility: hidden' : ''"></i>
            </el-row>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="4" style="padding: 0 .1rem;">
        <el-row type="flex" justify="center" style="flex-wrap: wrap;height: 100%;align-content: flex-end;">
          <el-col v-if="activeName === 'rwl'" :span="24" class="button_box"><button class="button_control" :class="{'button_control_disabled': !chainId}" :disabled="disabled" @click="_deleteTaskChain"><p style="font-size: .28rem">删除任务链</p></button></el-col>
          <el-col v-if="activeName === 'zdy'" :span="24" class="button_box"><button class="button_control" :class="{'button_control_disabled': !newData.length}" @click="newData = []"><p>清空</p></button></el-col>
          <el-col :span="24" class="button_box"><button class="button_control" :disabled="disabled" @click="_cancelTask"><p>取消任务</p></button></el-col>
          <el-col v-if="activeName === 'zdy'" :span="24" class="button_box"><button class="button_control" :class="{'button_control_disabled': !newData.length}" :disabled="disabled" @click="_saveTask"><p>保存任务</p></button></el-col>
          <el-col :span="24" class="button_box"><button class="button_control" :class="{'button_control_disabled': !newData.length}" :disabled="disabled" @click="_sendTask"><p>发送任务</p></button></el-col>
        </el-row>
      </el-col>
    </el-row>
    <save-chain v-if="saveVisible" ref="saveChain" @dataFormSubmit="dataFormSubmit"/>
    <!-- <vue-touch-keyboard id="keyboard" :options="options" v-if="visible" :layout="layout" :cancel="hide" :accept="accept" :input="input" :next="next" /> -->
  </div>
</template>

<script>
import SaveChain from './save-chain.vue'
// import { queryStation, queryTaskChain } from '../../config/mork.js'
import { queryStation, queryTaskChain, queryTaskChainDtl, sendTask, saveTask, cancelTask, deleteTaskChain, updateStation } from '../../config/getData.js'
export default {
  name: 'ModuleDevice',
  components: {
    SaveChain
  },
  data () {
    return {
      activeName: 'zdy',
      stationName: '',
      radioOption: [{label: '取货', text: '取', value: 'Ascend'}, {label: '放货', text: '放', value: 'Descend'}, {label: '移动', text: '移', value: 'Move'}, {label: '返回点', text: '返', value: 'Return'}],
      dataList: [],
      newData: [],
      linkData: [],
      chainId: null,
      disabled: false,
      loading: null,
      visible: false,
      layout: 'normal',
      input: null,
      options: {
        useKbEvents: false,
        preventClickEvent: false
      },
      saveVisible: false
    }
  },
  mounted () {
    this._queryStation()
    document.addEventListener('click', this.handleGlobalClick)
  },
  beforeDestroy () {
    document.removeEventListener('click', this.handleGlobalClick)
  },
  methods: {
    handleGlobalClick (event) {
      // 遍历所有 popover
      for (let i = 0; i < this.dataList.length; i++) {
        const popover = this.$refs[`popover-${i}`]
        if (popover && popover[0]) {
          if (popover[0].$el.contains(event.target)) {
            return
          }
          if (document.querySelector('#keyboard') && document.querySelector('#keyboard').contains(event.target)) {
            return
          }
          popover[0].doClose()
        }
      }
    },
    // 站点查询
    async _queryStation () {
      this.dataList = []
      try {
        let res = await queryStation()
        if (res && res.data) {
          this.dataList = [...res.data]
        }
      } catch (e) {
        this.$message.error(e)
      }
    },
    // 任务链查询
    async _queryTaskChain () {
      this.linkData = []
      this.chainId = null
      try {
        let res = await queryTaskChain()
        if (res && res.data) {
          this.linkData = [...res.data]
        }
      } catch (e) {
        this.$message.error(e)
      }
    },
    // 点击自定义站点
    openPopover (index) {
      const popover = this.$refs[`popover-${index}`]
      if (popover && popover[0]) {
        for (let i = 0; i < this.dataList.length; i++) {
          if (i !== index) {
            this.closePopover(i)
          }
        }
        popover[0].doShow()
        this.stationName = ''
      }
    },
    // 关闭弹窗
    closePopover (index) {
      const popover = this.$refs[`popover-${index}`]
      if (popover && popover[0]) {
        popover[0].doClose()
      }
    },
    // 修改站点名称
    async _updateStation (e, i) {
      this.disabled = true
      if (this.stationName === '') {
        this.disabled = false
        this.closePopover(i)
        this.visible = false
        return
      }
      try {
        this.loading = this.$loading({
          lock: true,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.6)'
        })
        let res = await updateStation(e.station_code, this.stationName)
        if (res) {
          this.$message(res.message)
          this._queryStation()
        }
        this.loading.close()
        this.disabled = false
        this.closePopover(i)
        this.visible = false
      } catch (e) {
        this.$message.error(e)
        this.loading.close()
        this.disabled = false
        this.closePopover(i)
        this.visible = false
      }
    },
    // 切换标签
    tabClick () {
      this.newData = []
      this.chainId = null
      if (this.activeName === 'zdy') {
        this._queryStation()
      } else if (this.activeName === 'rwl') {
        this._queryTaskChain()
      }
    },
    // 选取动作类型
    radioInput (e, i, value) {
      const lastItem = this.newData.length > 0 ? this.newData[this.newData.length - 1].station_code : null
      if (lastItem === e.station_code) {
        this.$message('相邻的两个站点不能相同')
        this.closePopover(i)
        return
      }
      if (this.newData.length > 4) {
        this.$message('最多选取5个站点')
        this.closePopover(i)
        return
      }
      if (this.newData.length > 0 && this.newData[this.newData.length - 1].action_type === 'Return') {
        return
      }
      e.action_type = value
      this.newData.push({station_code: e.station_code, station_name: e.station_name, action_type: e.action_type})
      this.closePopover(i)
    },
    // 点击任务链点位
    handleLinkCheck (e) {
      this.newData = []
      this.chainId = ''
      this._queryTaskChainDtl(e.chain_id)
    },
    // 任务链明细
    async _queryTaskChainDtl (id) {
      try {
        let res = await queryTaskChainDtl(id)
        if (res && res.data) {
          this.newData = [...res.data]
          this.chainId = id
        } else {
          this.newData = []
          this.chainId = ''
        }
      } catch (e) {
        this.$message.error(e)
        this.newData = []
        this.chainId = ''
      }
    },
    // 发送任务
    async _sendTask () {
      this.disabled = true
      if (!this.newData.length) {
        this.disabled = false
        return
      }
      try {
        this.loading = this.$loading({
          lock: true,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.6)'
        })
        let res = await sendTask(this.newData)
        if (res) {
          this.$message(res.message)
          this._queryStation()
          this.newData = []
        }
        this.loading.close()
        this.disabled = false
      } catch (e) {
        this.$message.error(e)
        this.loading.close()
        this.disabled = false
      }
    },
    // 保存任务
    async _saveTask () {
      if (!this.newData.length) {
        return
      }
      this.saveVisible = true
      this.$nextTick(() => {
        this.$refs.saveChain.init()
      })
    },
    async dataFormSubmit (data) {
      this.disabled = true
      try {
        this.loading = this.$loading({
          lock: true,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.6)'
        })
        let res = await saveTask(this.newData, data)
        if (res) {
          this.$message(res.message)
          this._queryStation()
          this.newData = []
        }
        this.loading.close()
        this.disabled = false
      } catch (e) {
        this.$message.error(e)
        this.loading.close()
        this.disabled = false
      }
    },
    // 取消任务
    async _cancelTask () {
      this.disabled = true
      try {
        this.loading = this.$loading({
          lock: true,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.6)'
        })
        let res = await cancelTask()
        if (res) {
          this.$message(res.message)
          this._queryStation()
          this.newData = []
        }
        this.loading.close()
        this.disabled = false
      } catch (e) {
        this.$message.error(e)
        this.loading.close()
        this.disabled = false
      }
    },
    // 删除任务链
    async _deleteTaskChain () {
      this.disabled = true
      if (!this.chainId) {
        this.disabled = false
        return
      }
      try {
        this.loading = this.$loading({
          lock: true,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.6)'
        })
        let res = await deleteTaskChain(this.chainId)
        if (res) {
          this.$message(res.message)
          this.newData = []
          this.chainId = ''
          this._queryTaskChain()
        }
        this.loading.close()
        this.disabled = false
      } catch (e) {
        this.$message.error(e)
        this.loading.close()
        this.disabled = false
      }
    },
    show (e) {
      // 关闭中文keyboard
      let arr = document.querySelectorAll('.hg-theme-default')
      arr.forEach((ele) => {
        ele.style.visibility = 'hidden'
      })
      this.input = e.target
      this.layout = e.target.dataset.layout
      if (!this.visible) {
        this.visible = true
      }
    },
    hide () {
      this.visible = false
    },
    accept () {
      this.hide()
    },
    next () {
      let inputs = document.querySelectorAll('input')
      let found = false;
      [].forEach.call(inputs, (item, i) => {
        if (!found && item === this.input && i < inputs.length - 1 && this.input.dataset.next === '1') {
          found = true
          this.$nextTick(() => {
            inputs[i + 1].focus()
          })
        }
      })
      if (!found) {
        this.input.blur()
        this.hide()
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
.t_box
  height 100%
  background-color rgba(0, 19, 48, 70%)
  box-shadow inset 1px 1px 7px 2px #4d9bcd
  padding .1rem
  overflow hidden
.r_box
  height 100%
  overflow-y auto
  flex-wrap wrap
  align-content flex-start
.pp_item
  width 33%
.point_item
  width 19.6%
  height 0.6rem
  padding 0.1rem
  margin-bottom 0.02rem
  background center / 100% 100% url(../../images/new/bg2.png) no-repeat
  p
    font-size .2rem
    font-family 'SourceHanSansCN-Bold'
    line-height .2rem
    color #B4C1D8
    text-align center
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3; /* 定义显示的行数 */
    overflow: hidden;
    text-overflow: ellipsis;
.point_item_i
  display flex
  align-items center
  justify-content center
.point_checked
  width calc(100% - .17rem)
  height .4rem
  padding 0
  background-image url(../../images/new/bg1.png)
  p
    color #3CC1FF
    font-size .16rem
.result_w
  height 1rem
  border 1px solid #1E9FE7
  padding .1rem
  background-color rgba(10, 73, 164, 80%)
.icon-caret-right
  width .3rem
  font-size .2rem
  color #fff
  line-height .4rem
.result_items
  flex-wrap wrap
  align-content flex-start
  overflow-y auto
  max-height 100%
.task_button
  line-height 1
  white-space nowrap
  vertical-align middle
  border 1px solid #233553
  border-left 0
  -webkit-appearance none
  text-align center
  box-sizing border-box
  margin 0
  color #9ff0fc
  background center / 100% 100% url(../../images/new/tab_bg.png) no-repeat
  padding 0.1rem
  font-size 0.14rem
  &:first-child
    border-left 1px solid #233553
  &:active, &:hover
    border-color #146fd0
    border-left 1px solid #146fd0
.task_button_checked
  border-color #146fd0
  border-left 1px solid #146fd0
.task_checked
  color #FFF
  background-color #409EFF
  border-color #409EFF
  &:first-child
    border-left-color #409EFF
.button_box
  height 20%
  margin-bottom .16rem
  text-align center
  &:last-child
    margin-bottom 0
  .button_control
    height 100%
    p
      font-size .3rem
</style>
