<template>
  <div class="page_container" :class="{'enClass': $i18n.locale === 'en-us'}">
    <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="$t('Customize')" 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
                    width="500"
                    placement="bottom"
                    trigger="manual"
                    :ref="`popover-${i}`">
                    <el-row type="flex" justify="space-between" align="middle" style="margin-bottom: .2rem">
                      <el-col style="width: calc(100% - .55rem)"><el-input :placeholder="$t('Modifyname')" v-model="stationName"></el-input></el-col>
                      <el-button type="success" icon="el-icon-check" size="mini" style="width: .5rem; height: .4rem" :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[$langPre.computedProp('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="$t('Taskchain')" 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">
              <i class="el-icon-caret-right icon-caret-right" :style="i === 0 ? 'display: none' : ''"></i>
              <div class="relative point_item point_checked">
                <el-row type="flex" align="middle" class="zbox">
                  <el-col :span="17">
                    <p class="point_checked_p1">{{ e.station_name }}</p>
                  </el-col>
                  <el-col :span="7" style="border-left: 1px solid #fff;">
                    <p class="point_checked_p2">{{ radioOption | findByValue(e.action_type) }}</p>
                  </el-col>
                </el-row>
                <el-button class="absolute icon-delt" type="danger" icon="el-icon-delete" circle @click="deletePoint(i)"></el-button>
              </div>
            </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 button_control_s" :class="{'button_control_disabled': !chainId}" :disabled="disabled" @click="_deleteTaskChain"><p>{{$t('Deletetaskchain')}}</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>{{$t('Empty')}}</p></button></el-col>
          <el-col :span="24" class="button_box"><button class="button_control" :disabled="disabled" @click="_cancelTask"><p>{{$t('Canceltask')}}</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>{{$t('Savetask')}}</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>{{$t('SendTask')}}</p></button></el-col>
        </el-row>
      </el-col>
    </el-row>
    <save-chain v-if="saveVisible" ref="saveChain" @dataFormSubmit="dataFormSubmit"/>
  </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: [
        {zh_label: '取货', en_label: 'Pickup', zh_text: '取', en_text: 'Pick', value: 'Ascend'},
        {zh_label: '放货', en_label: 'Drop', zh_text: '放', en_text: 'Drop', value: 'Descend'},
        {zh_label: '移动', en_label: 'Move', zh_text: '移', en_text: 'Move', value: 'Move'},
        {zh_label: '返回点', en_label: 'Return', zh_text: '返', en_text: 'Return', value: 'Return'}],
      dataList: [],
      newData: [],
      linkData: [],
      chainId: null,
      disabled: false,
      loading: null,
      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)
        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)
      } catch (e) {
        this.$message.error(e)
        this.loading.close()
        this.disabled = false
        this.closePopover(i)
      }
    },
    // 切换标签
    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.$t('Twostationsnotsame'))
        this.closePopover(i)
        return
      }
      if (this.newData.length > 4) {
        this.$message(this.$t('Select5stations'))
        this.closePopover(i)
        return
      }
      if (this.newData.length > 0 && this.newData[this.newData.length - 1].action_type === 'Return') {
        this.$message(this.$t('Returnpointselected'))
        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
      }
    },
    deletePoint (index) {
      this.newData.splice(index, 1)
    } 
  }
}
</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 calc((100% - .6rem) / 3 + .3rem)
  &:first-child
    width calc((100% - .6rem) / 3)
    .point_checked
      width 100%
.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: 2; /* 定义显示的行数 */
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
.point_item_i
  display flex
  align-items center
  justify-content center
.point_checked
  width calc(100% - .17rem)
  height .43rem
  margin-bottom: 0.04rem;
  padding 0
  background-image none
  border: 1px solid #7595d3;
  background-color: #162f74;
  box-shadow 0px 0px 4px 1px rgba(142, 169, 232, 36%)
  p
    color #3CC1FF
    line-height .18rem
  .point_checked_p1
    font-size .18rem
    padding: 0 0.04rem;
  .point_checked_p2
    font-size: 0.18rem;
    font-weight: 700;
    text-align: center;
    padding-right: 0.02rem;
.result_w
  flex-wrap wrap
  height 1rem
  border 1px solid #1E9FE7
  padding 0.04rem 0.05rem
  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
  width 24%
  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
  font-size 24px
  height 65px
  &: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 18%
  margin-bottom .2rem
  max-height .65rem
  text-align center
  &:last-child
    margin-bottom 0
  .button_control
    height 100%
    p
      font-size .3rem
  .button_control_s
    p
      font-size .27rem
.icon-delt
  padding 0
  height: 0.3rem;
  line-height: .3rem;
  width: 0.3rem;
  font-size: .16rem;
  right: -0.1rem;
  top: -0.1rem;
  &:focus, &:hover
    background-color: #c3390c;
    border-color: #ed865c;
.enClass
  .button_control p
    line-height .22rem
  .button_control_s p
    font-size 0.22rem
  .point_checked .point_checked_p2
    font-size .14rem
</style>
