<template>
  <div>
    <el-select
      v-model="valuess"
      :multiple="multiple"
      :disabled="disabled"
      size="small"
      @visible-change="visibleChange($event)"
      :clearable="clearable"
      :filterable="filterable"
      :placeholder="$t('openatccomponents.common.select')"
      @change="onChange"
      @focus="onFocus"
    >
      <el-option
        id="aaa"
        v-for="(item, index) in Options"
        :key="index"
        :label="getLable(item.label)"
        :value="item.value"
      >
        <div class="single-model" @click="selectStages(item.value)">
          <xdrdirselector
            Width="60px"
            Height="60px"
            :showlist="item.item"
          ></xdrdirselector>
          <span
            style="
              float: right;
              margin-left: 10px;
              color: #8492a6;
              font-size: 13px;
            "
            >{{ item.label }}</span
          >
        </div>
      </el-option>
    </el-select>
    <span v-if="pattern">{{ getIncludedPhasesDesc(valuess) }}</span>
    <!-- <span id="xrd"></span> -->
    <!-- <xdrdirselector :Data="Data" :Datas="Datas" Width="60px" Height="60px" :showlist="dirArr"></xdrdirselector> -->
  </div>
</template>
<script>
import { getTscControl } from '../../../api/control'
import { getPhaseDesc } from '../../../utils/phasedesc.js'
// import { uploadSingleTscParam } from '../../api/param'
import { getMessageByCode } from '../../../utils/responseMessage'
import xdrdirselector from '../XRDDirSelector/XRDDirSelector.vue'
import PhaseDataModel from '../IntersectionMap/crossDirection/utils'
// import CrossDiagramMgr from '@/EdgeMgr/controller/crossDiagramMgr'
// import { getDirName } from './utils.js'
import { getTheme } from '../../../utils/auth'
export default {
  name: 'SelectCrossPhase',
  components: {
    xdrdirselector
  },
  props: {
    multiple: {
      type: Boolean,
      default: false
    },
    pattern: {
      type: Boolean,
      default: false
    },
    filterable: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    row: {
      type: Object
    },
    valueModel: {
      type: Array
    },
    type: {
      type: String || Array
    },
    phaseOption: {
      type: Array,
      default: () => []
    },
    // placeholder: {
    //   type: String,
    //   default: ''
    // },
    bizType: {
      type: String,
      default: ''
    },
    agentid: {
      type: String,
      default: '10501'
    },
    clearable: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      list: [],
      valuess: [],
      Data: {
        left: '60px',
        top: '10px'
      },
      Datas: {
        left: '60px',
        top: '10px'
      },
      Options: [],
      phaseList: [],
      dirArr: [],
      sidewalkPhaseData: []
    }
  },
  watch: {
    phaseOption: {
      handler (val) {
        this.phaseOption = val
        this.getPhase()
        this.showxdr(this.valuess)
      },
      deep: true
    },
    agentid (val) {
      // this.value = ''
      this.Options = []
      // this.onLoad()
    }
  },
  created () {
    this.PhaseDataModel = new PhaseDataModel()
    this.onLoad()
  },
  methods: {
    getLable (str) {
      const match = str.match(/\d+/)
      if (match) {
        return this.getPhaseDescs(Number(match[0]))
      }
    },
    // getXrd (data) {
    //   let Profile = Vue.extend({
    //     // template: 'xdrdirselector',
    //     components: {
    //       xdrdirselector
    //     },
    //     render (h) {
    //       return h('xdrdirselector', {
    //         props: {
    //           Width: '60px',
    //           Height: '60px',
    //           showlist: data,
    //           Data: {
    //             left: '60px',
    //             top: '10px'
    //           },
    //           Datas: {
    //             left: '60px',
    //             top: '10px'
    //           }
    //         }
    //       })
    //     }
    //   })
    //   let profile = new Profile()
    //   profile.$mount('#xrd')
    // },
    getPhaseDescs (id) {
      let phasedesc = this.phaseOption.filter((item) => {
        return item.id === id
      })[0].direction
      if (!phasedesc || phasedesc.length === 0) return id
      let description = getPhaseDesc(phasedesc, this.$i18n)
      return id + '-' + description
    },
    showxdr (data) {
      let color = getTheme() === 'light' ? '#1E1E1E' : '#F1F3F4'
      this.dirArr = []
      this.phaseOption.filter((item) => {
        if (item.id === data) {
          if (item.direction) {
            if (item.direction.length === 0) {
              let recd = {
                id: 0,
                peddirection: this.getPed(item.peddirection),
                color: color
              }
              this.dirArr.push(recd)
            } else {
              for (let rec of item.direction) {
                let recd = {
                  id: rec,
                  peddirection: this.getPed(item.peddirection),
                  color: color
                }
                this.dirArr.push(recd)
              }
            }
          } else {
            let recd = {
              id: 0,
              peddirection: this.getPed(item.peddirection),
              color: color
            }
            this.dirArr.push(recd)
          }
        }
      })
    },
    onFocus () {
      if (!this.Options || this.Options.length === 0) {
        this.onLoad()
      }
    },
    onLoad () {
      this.getPhase()
      // this.initData()
    },
    setOption (list) {
      if (this.row.callphase) {
        this.valuess = this.row.callphase
        this.showxdr(this.valuess)
      }
      if (this.row.phases) {
        this.valuess = this.row.phases
      }
      if (this.row.linkphase) {
        this.valuess = this.row.linkphase
        this.showxdr(this.valuess)
      }
      if (this.row.includedphases) {
        this.valuess = this.row.includedphases
      }
      if (this.row.data && this.row.data.phase) {
        this.valuess = this.row.data.phase
        this.showxdr(this.valuess)
      }
      let color = getTheme() === 'light' ? '#1E1E1E' : '#F1F3F4'
      this.Options = list.map((item, index) => {
        let dirArr = []
        if (item.direction) {
          if (item.direction.length === 0) {
            let recd = {
              id: 0,
              peddirection: this.getPed(item.peddirection),
              color: color
            }
            dirArr.push(recd)
          } else {
            for (let rec of item.direction) {
              let recd = {
                id: rec,
                peddirection: this.getPed(item.peddirection),
                color: color
              }
              dirArr.push(recd)
            }
          }
        } else {
          let recd = {
            id: 0,
            peddirection: this.getPed(item.peddirection),
            color: color
          }
          dirArr.push(recd)
        }
        let name = ''
        name = this.$t('openatccomponents.pattern.phase') + item.id
        // name = this.getPhaseDescs(item.id)
        return {
          label: name,
          item: dirArr,
          value: item.id
        }
      })
    },
    visibleChange (status) {
      if (!status) {
        this.showxdr(this.valuess)
      }
    },
    onChange (value) {
      if (this.type === 'callphase') {
        this.row.callphase = this.valuess
      } else if (this.type === 'linkphase') {
        this.row.linkphase = this.valuess
      } else if (this.type === 'phase') {
        this.row.data.phase = this.valuess
      } else if (this.multiple && this.type === 'phases') {
        this.row.phases = this.valuess
      } else if (this.multiple && this.type === 'includedphases') {
        this.row.includedphases = this.valuess
      }
      let option = this.Options.filter(item => item.value === value)[0]
      this.$emit('onChange', value, option, this.agentid, this.bizType)
    },
    selectStages (value) {
      this.$emit('selectStages', value)
    },
    getPhase () {
      this.getPedPhasePos(this.phaseOption)
      this.setOption(this.phaseOption)
    },
    initData () {
      let agentId = this.agentid
      getTscControl(agentId).then((data) => {
        if (!data.data.success) {
          if (data.data.code === '4003') {
            this.devStatus = 2
            this.$message.error(this.$t('openatccomponents.errorTip.devicenotonline'))
            return
          }
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        let TscData = JSON.parse(JSON.stringify(data.data.data.data))
        this.handleStageData(TscData) // 处理阶段（驻留）stage数据
      }).catch(error => {
        this.$message.error(error)
        console.log(error)
      })
    },
    getPed (data) {
      if (!data) return
      let ped = []
      let peddirections = []
      let color = getTheme() === 'light' ? '#1E1E1E' : '#F1F3F4'
      for (let walk of this.sidewalkPhaseData) {
        for (let ped of data) {
          let objs = {}
          objs.name = walk.name
          objs.id = walk.id
          objs.color = color
          if (ped === walk.id) {
            peddirections.push(objs)
            peddirections = Array.from(new Set(peddirections))
          }
        }
      }
      ped.push(...peddirections)
      return ped
    },
    getPedPhasePos (phaseList) {
      // 行人相位信息
      this.sidewalkPhaseData = []
      phaseList.forEach((ele, i) => {
        if (ele.peddirection) {
          ele.peddirection.forEach((dir, index) => {
            // 行人相位
            if (this.PhaseDataModel.getSidePos(dir)) {
              this.sidewalkPhaseData.push({
                // key: this.CrossDiagramMgr.getUniqueKey('pedphase'),
                phaseid: ele.id, // 相位id，用于对应相位状态
                id: dir,
                name: this.PhaseDataModel.getSidePos(dir).name
              })
            }
          })
        }
      })
      return this.sidewalkPhaseData
    },
    handleStageData (data) {
      this.stagesList = []
      let stages = data.stages
      for (let stage of stages) {
        let tempList = []
        let directionList = []
        for (let stg of stage) {
          let currPhase = this.phaseList.filter((item) => {
            return item.id === stg
          })[0]
          if (currPhase !== undefined) {
            directionList = [...currPhase.direction, ...directionList]
          }
          // directionList = [...currPhase.direction, ...directionList]
        }
        directionList = [...new Set(directionList)]
        tempList = directionList.map(dir => ({
          id: dir,
          color: '#606266'
        }))
        this.stagesList.push(tempList)
      }
      this.list = this.stagesList
      // this.setOption()
    },
    // init (val) {
    //   let target = val
    //   if (this.multiple) {
    //     target = [val]
    //   }
    //   this.value = target
    // },
    getNameById (id) {
      let res = ''
      for (const item of this.Options) {
        if (id === item.agentid) {
          res = item.name
          break
        }
      }
      return res
    },
    getIncludedPhasesDesc (ids) {
      let str = ''
      for (let id of ids) {
        str = str + this.getPhaseDescs(id) + ' '
      }
      return str
    }
  }
}
</script>
<style lang="scss">

.el-select-dropdown__wrap {
  max-height: 500px !important;
}

#aaa{
  // :deep(.el-select-dropdown__item){
    margin: 10px 0 !important;
  // }
}

</style>
