/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
<div class="cross-phase-dir cross-phase-dir-text">
  <div v-for="phase in phaselist" :key="phase.id">
    {{$t('openatccomponents.overview.phase')}}{{phase.id}} - {{phase.dirname}}
  </div>
</div>
</template>
<script>
import {
  getTscPhase
} from '../../../api/cross.js'
import { getMessageByCode } from '../../../utils/responseMessage.js'
import { images } from '../../../utils/phaseList.js'
export default {
  name: 'phase-direction-text',
  props: {
    agentid: {
      type: String
    },
    phaseidArray: {
      type: Array
    }
  },
  data () {
    return {
      phaselist: [],
      DirectionMap: new Map() // 当前设备的相位方向Map
    }
  },
  mounted () {
    this.getCurPhaseDirection()
  },
  methods: {
    getCurPhaseDirection () {
      this.DirectionMap = new Map()
      this.phaselist = []
      if (this.agentid === undefined || this.agentid === '') return
      getTscPhase(this.agentid).then(res => {
        if (!res.data.success) {
          if (res.data.code === '4003') {
            this.$message.error(this.$t('openatccomponents.errorTip.devicenotonline'))
            return
          }
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        if (!res.data.data.data.phaseList) return
        res.data.data.data.phaseList.forEach(ele => {
          let dirname = this.getPhaseName(ele.direction).name
          this.DirectionMap.set(ele.id, {...ele, dirname})
        })
        this.getPhaseDirTextByPhaseid()
      })
    },
    getName (status) {
      let name = ''
      for (let i = 0; i < status.length; i++) {
        if (!status[i]) continue
        name = name + ',' + this.$t(images[i].name)
      }
      if (name !== '') {
        const obj = {
          name: name.substr(1)
        }
        return obj
      } else {
        return {
          name: ''
        }
      }
    },
    getPhaseName (desc) {
      // 根据相位描述数组得到相位名称
      let status = []
      for (let obj of images) {
        if (desc.length > 0 && desc.includes(obj.id)) {
          status.push(1)
        } else {
          status.push(0)
        }
      }
      return this.getName(status)
    },
    getPhaseDirTextByPhaseid () {
      this.phaselist = this.phaseidArray.map(phaseid => {
        let phaseinfo = this.DirectionMap.get(phaseid)
        return phaseinfo
      })
    }
  }
}
</script>

<style scoped>
</style>
