<template>
  <el-select
    v-model="value"
    :multiple="multiple"
    :disabled="disabled"
    :size="size"
    collapse-tags
    :clearable="clearable"
    filterable
    :placeholder="placeholder"
    @change="onChange"
    @focus="onFocus"
  >
    <el-option
      v-for="(item, index) in Options"
      :key="index"
      :label="item.label"
      :value="item.value"
    >
      <div class="single-model" @click="selectStages(item.value)" >
        <div>
          <xdrdirselector Width="60px" Height="60px" :showlist="item.item"></xdrdirselector>
        </div>
        <div>
          <span style="float: right; color: #8492a6; font-size: 13px">{{ formatLabel(item.label) }}</span>
        </div>
      </div>
    </el-option>
  </el-select>
</template>
<script>
import { getIntersectionInfo } from '../../../api/template'
// import { uploadGBTscParams } from '../../api/paramGB'
import { getMessageByCode } from '../../../utils/responseMessage'
import xdrdirselector from '../../components/XRDDirSelector'
import PhaseDataModel from '../../components/IntersectionMap/crossDirection/utils.js'
import { getDirName } from './utils.js'
import { getTheme } from '../../../utils/auth'

export default {
  name: 'SelectCrossPhase',
  components: {
    xdrdirselector
  },
  props: {
    size: {
      type: String,
      default: ''
    },
    multiple: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: ''
    },
    bizType: {
      type: String,
      default: ''
    },
    agentid: {
      type: String,
      default: '10501'
    },
    clearable: {
      type: Boolean,
      default: false
    },
    defaultValue: {
      type: Number,
      default: -1
    }
  },
  data () {
    return {
      isMock: false,
      list: [],
      value: [],
      Options: [],
      phaseList: [],
      sidewalkPhaseData: []
    }
  },
  watch: {
    defaultValue (val) {
      if (val === -1) {
        this.value = []
      }
    },
    agentid (val) {
      this.value = ''
      this.Options = []
      // this.onLoad()
    }
  },
  created () {
    this.onLoad()
    this.PhaseDataModel = new PhaseDataModel()
    // this.CrossDiagramMgr = new CrossDiagramMgr()
    if (!this.placeholder) {
      this.placeholder = this.$t('openatccomponents.phase.stage')
    }
  },
  methods: {
    formatLabel (label) {
      let res = label
      if (label && label.length > 11) {
        res = label.substring(0, 8) + '...'
      }
      return res
    },
    onFocus () {
      if (!this.Options || this.Options.length === 0) {
        this.onLoad()
      }
    },
    onLoad () {
      this.initData()
    },
    setOption (list) {
      let color = getTheme() === 'light' ? '#1E1E1E' : '#F1F3F4'
      this.Options = list.map((item, index) => {
        let dirArr = []
        for (let rec of item) {
          const peddirection = (rec.peddirection && this.getPed(rec.peddirection)) || []
          let recd = {
            id: rec.id,
            peddirection: peddirection,
            color: color
          }
          dirArr.push(recd)
        }
        let nameArr = getDirName(dirArr)
        let name = ''
        nameArr = nameArr.map(record => this.$t(record))
        name = nameArr.join(',')
        const _index = index + 1
        name = this.$t('openatccomponents.phase.stage') + _index + ' ' + name
        // console.log(nameArr, 'nameArr')
        const res = {
          label: name,
          item: dirArr,
          value: _index
        }
        return res
      })
    },
    onChange (value) {
      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)
    },
    async initData () {
      let agentId = this.agentid
      let phaseList = []
      let stageList = []
      await getIntersectionInfo(agentId).then(data => {
        let res = data.data
        if (this.isMock) {
          // mockData
          // let mockData = require('./mock/gb_features.json')
          // console.log('mockData', mockData)
          // res = mockData
        }
        if (!res.success) {
          let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
          if (data.data.data) {
            // 子类型错误
            let childErrorCode = data.data.data.errorCode
            if (childErrorCode) {
              let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
              this.$message.error(parrenterror + ',' + childerror)
            }
          } else {
            this.$message.error(parrenterror)
          }
          return
        }
        phaseList = res.data.param.Phase.PhaseConfig.filter(item => item.direction && item.direction.length > 0)
        stageList = res.data.param.Stage.StageConfig.filter(item => item.IncludedPhase && item.IncludedPhase.length > 0)
        this.phaseList = phaseList
        this.$emit('getRcpTscParams', res.data.param)
        this.handleStageData(stageList, phaseList) // 处理阶段（驻留）stage数据
      })
    },
    // handleStageData (data) {
    //   if (!data) return
    //   let peddirections = this.getPed(data)
    //   let stagesTemp = []
    //   let tempList = []
    //   for (let stg of data) {
    //     let directionList = []
    //     let currPhase = this.phaseList.filter((item) => {
    //       return item.id === stg
    //     })[0]
    //     if (currPhase !== undefined) {
    //       directionList.push(...currPhase.direction)
    //       directionList = Array.from(new Set(directionList))
    //     }
    //     if (directionList.length === 0) {
    //       tempList.push({
    //         id: '',
    //         color: '#454545',
    //         peddirection: peddirections
    //       })
    //     } else {
    //       tempList = directionList.map(dir => ({
    //         id: dir,
    //         color: '#454545',
    //         peddirection: peddirections
    //       }))
    //     }
    //     let newTemp = tempList.filter(item => item.id !== '')
    //     stagesTemp.push(...newTemp)
    //   }
    //   return stagesTemp
    // },
    getPed (data) {
      let ped = []
      let peddirections = []
      for (let walk of this.sidewalkPhaseData) {
        for (let ped of data) {
          let objs = {}
          objs.name = walk.name
          objs.id = walk.id
          if (ped === walk.id) {
            peddirections.push(objs)
            peddirections = Array.from(new Set(peddirections))
          }
        }
      }
      ped.push(...peddirections)
      return ped
    },
    getPedPhasePos (phaseList) {
      // 行人相位信息
      this.sidewalkPhaseData = []
      console.log(phaseList, 'this.this.phaseList')
      phaseList.forEach((ele, i) => {
        if (ele.peddirection) {
          ele.peddirection.forEach((dir, index) => {
          // 行人相位
            if (this.PhaseDataModel.getSidePos(dir)) {
              const spd = {
                // key: this.CrossDiagramMgr.getUniqueKey('pedphase'),
                phaseid: ele.Index, // 相位id，用于对应相位状态
                id: dir,
                name: this.PhaseDataModel.getSidePos(dir).name
              }
              this.sidewalkPhaseData.push(spd)
            }
          })
        }
      })
      return this.sidewalkPhaseData
    },
    handleStageData (_stageList, _phaseList) {
      console.log('handleStageData', _stageList, _phaseList)
      this.stagesList = []
      let stages = _stageList
      for (let stageItem of stages) {
        const stage = stageItem.IncludedPhase
        let tempList = []
        let directionList = []
        let pedestrianList = []
        for (let stg of stage) {
          let currPhase = _phaseList.filter((item) => {
            return item.Index === stg
          })[0]
          if (!currPhase || !currPhase.direction) {
            continue
          } else {
            directionList = [...(currPhase.direction || []), ...directionList]
            pedestrianList = [...(currPhase.peddirection || []), ...pedestrianList]
          }
          // directionList = [...currPhase.direction, ...directionList]
        }
        directionList = [...new Set(directionList)]
        pedestrianList = [...new Set(pedestrianList)]
        tempList = directionList.map((dir, _index) => ({
          id: dir,
          color: '#606266',
          peddirection: pedestrianList || []
        }))
        this.stagesList.push(tempList)
      }
      this.list = this.stagesList
      this.getPedPhasePos(_phaseList)
      this.setOption(this.list)
      if (this.defaultValue !== -1) {
        this.init(this.defaultValue)
      }
    },
    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
    }
  }
}
</script>
<style scoped>
.single-model {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
