/**
 * 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="app-container" ref="pattern-container">
    <el-table :data="newPatternList" :max-height="tableHeight" id="footerBtn" :show-header="isShowTableHeader">
      <el-table-column :type="isAllowedExpand ? 'expand' : ''" v-if="isAllowedExpand">
        <template slot-scope="scope">
          <div v-if="isAllowedExpand && isSingleCrossMode" class="optimizetype">
              <span>{{$t('openatccomponents.pattern.optimizetype')}}</span>
              <el-select v-model="value" clearable :placeholder="$t('openatccomponents.common.select')">
                <el-option
                    v-for="item in typeOptions"
                    :key="item.value"
                    :label="$t('openatccomponents.overview.type' + item.value)"
                    :value="item.value"
                    >
                </el-option>
                </el-select>
                <span class="optimiNum">{{$t('openatccomponents.pattern.optimizecycle')}}</span>
                <el-input v-model="optimizecycle" clearable :placeholder="$t('openatccomponents.common.enter')"></el-input>
              <el-button type="primary" @click="onOptimizeClick(scope.row, scope.$index)">{{$t('openatccomponents.pattern.inoptimize')}}</el-button>
          </div>
          <div class="components-container board">
            <XiaoKanBan v-for="n in scope.row.ringCount"
                        :key="n"
                        :isSingleCrossMode="isSingleCrossMode"
                        class="kanban todo"
                        :list="scope.row.rings[n-1]"
                        :header-text="$t('openatccomponents.pattern.ring') +' '+n"
                        :index="scope.$index"
                        @fatherMethod="fatherMethod"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="No" width="45" minWidth="40" v-if="isShowColumn('no')">
        <template slot-scope="scope">
          <span>{{scope.$index+1}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('openatccomponents.greenwaveoptimize.deviceid')" width="100" minWidth="40" v-if="isShowColumn('agentid')">
        <template slot-scope="scope">
          <span>{{scope.row.agentid}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('openatccomponents.overview.crossname')" width="120" minWidth="40" v-if="isShowColumn('name')">
        <template slot-scope="scope">
          <span>{{getDevName(scope.row)}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('openatccomponents.greenwaveoptimize.period')" width="100" minWidth="40" v-if="isShowColumn('period')">
        <template slot-scope="scope">
          <span>{{getPeriod(scope.row)}}</span>
        </template>
      </el-table-column>
      <el-table-column property="isValid" :label="$t('openatccomponents.token.isValid')" align="center" width="80" prop="isused" v-if="isShowColumn('isused')">
        <template slot-scope="scope">
          <el-switch
            style="padding-left: 5px;"
            v-model="scope.row.isused"
            active-color="#299BCC">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('openatccomponents.greenwaveoptimize.pattern')" width="120" minWidth="40" v-if="isShowColumn('patternName')">
        <template slot-scope="scope">
          <span>{{scope.row.patternDesc}}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('openatccomponents.greenwaveoptimize.pattern')"
        width="120"
        align="center"
        v-if="isShowColumn('patternid')">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.patternid"
            size="small"
            :loading="loading"
            @focus="getCurPattern(scope.row.agentid)"
            @change="changeCurPattern(scope.row,$event)">
              <el-option v-for="option in (scope.row.allPatterns)"
                         :key="option.patternid"
                         :label="option.patterndesc"
                         :value="option.patternid">
                <span>{{ option.patterndesc }}</span>
              </el-option>
          </el-select>
          <span></span>
        </template>
      </el-table-column>
      <el-table-column  align="center" :label="$t('openatccomponents.greenwaveoptimize.offset')" width="85" prop="offset" v-if="isShowColumn('offset')">
        <template slot-scope="scope">
          <el-input-number v-if="isAllowedExpand" :controls="false" :min="0" :step="1" v-model.number="scope.row.offset" size="small" style="width:70%;"></el-input-number>
          <span v-else>
            {{ scope.row.offset }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('openatccomponents.greenwaveoptimize.cycle')" width="60" prop="cycle" v-if="isShowColumn('cycle')">
      </el-table-column>
      <el-table-column align="center" :label="$t('openatccomponents.pattern.plan')" v-if="isShowColumn('pattern')">
        <template slot-scope="scope">
          <div class="pattern-figure">
            <pattern-list
              v-if="getControlType(scope.row) === 'ring'"
              :patternStatusList="JSON.parse(JSON.stringify(scope.row.rings))"
              :cycles="scope.row.cycle"
              :maxCycle="maxCycle"
              :phaseList="JSON.parse(JSON.stringify(scope.row.currPhase))"
              :contrloType="getControlType(scope.row)"
            >
            </pattern-list>
            <pattern-list
              v-else
              :patternId="scope.row.patternid"
              :contrloType="getControlType(scope.row)"
              :index="scope.$index"
              :cycleChange="false"
              :maxCycle="maxCycle"
              :stagesChange="getSelectedPattern(scope.row).stagesList"
              :patternStatusList="getSelectedPattern(scope.row).rings"
              :patternList="JSON.parse(JSON.stringify(scope.row.allPatterns))"
              :allPatternList="JSON.parse(JSON.stringify(scope.row.allPatterns))"
              :cycles="scope.row.cycle"
              :phaseList="JSON.parse(JSON.stringify(scope.row.currPhase))"
              :agentId="scope.row.agentid"
              :showBarrier="false">
            </pattern-list>
          </div>
         </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import XiaoKanBan from '../../XiaoKanBan/index.vue'
// import { getPatternList } from '../../../../api/route'
import { getIntersectionInfo } from '../../../../api/template'
import { getMessageByCode } from '../../../../utils/responseMessage'
import { getDuration } from '../../../../api/cross'
// import { getDirName } from '../../../components/SelectCrossPhase/utils.js'
export default {
  name: 'PatternTable',
  components: {
    XiaoKanBan
  },
  props: {
    devicesData: {
      type: Array,
      default: () => []
    },
    optList: {
      type: Array
    },
    isSingleCrossMode: {
      type: Boolean,
      default: false
    },
    tableColums: {
      type: Array,
      default: () => []
    },
    isAllowedExpand: {
      type: Boolean,
      default: true
    },
    isShowGenerateButton: {
      type: Boolean,
      default: true
    },
    isShowTableHeader: {
      type: Boolean,
      default: true
    },
    maxTableHeight: {
      type: Number,
      default: 200
    }
  },
  computed: {
    maxCycle () {
      if (!this.newPatternList || this.newPatternList.length === 0) {
        return ''
      }
      let max = ''
      for (let i = 0; i < this.newPatternList.length; i++) {
        let row = this.newPatternList[i]
        let cycle = row.cycle
        if (cycle !== undefined && cycle !== null) {
          let numCycle = Number(cycle)
          if (max === '' || numCycle > max) {
            max = numCycle
          }
        }
      }
      return max
    }
  },
  data () {
    return {
      typeOptions: [{
        value: 'flow-split-opt'
      }, {
        value: 'cycle-opt'
      }],
      value: 'flow-split-opt',
      optimizecycle: 0,
      controlType: 'stage',
      loading: true,
      tableHeight: 460,
      screenHeight: window.innerHeight, // 屏幕高度
      newPatternList: []
    }
  },
  created () {
  },
  watch: {
    maxTableHeight: function () {
      this.$nextTick(() => {
        this.tableHeight = this.maxTableHeight // 动态更新高度
      })
    },
    optList: {
      handler: function (val) {
        if (val && val.length > 0) {
          // for () {

          // }
        }
      },
      deep: true
    },
    newPatternList: {
      handler: function (val) {
        console.log('onNewPatternListChange', val)
        this.$emit('onNewPatternListChange', val)
      },
      deep: true
    }
  },
  mounted: function () {
  },
  methods: {
    onOptimizeClick (row, index) {
      let msg = this.$t('openatccomponents.pattern.algorithmEngineOptimization')
      const loading = this.$loading({
        lock: true,
        text: msg,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      setTimeout(() => {
        loading.close()
        this.handeleOptimizeClick(row, index)
      }, 1000)
    },
    handeleOptimizeClick (row, index) {
      let newPha = []
      for (let i = 0; i < row.rings.length; i++) {
        newPha.push(...row.rings[i])
      }
      let phaseData = newPha.map(item => {
        return {
          id: item.id,
          flowperhour: item.flowperhour,
          saturation: item.saturation
        }
      })
      let patternList = row.allPatterns
      if (row.feature && row.feature.patternList && row.feature.patternList.length > 0) {
        patternList = row.feature.patternList
      }
      let pattern = patternList.filter((item) => item.id === row.patternid)[0]
      let phaseList = row.currPhase
      let reqData = {
        'type': this.value,
        'optcycle': this.optimizecycle ? this.optimizecycle : 0,
        'phaseList': phaseList,
        'pattern': pattern,
        'phases': phaseData
      }
      let isValidata = []
      for (let j = 0; j < newPha.length; j++) {
        let comNum = (newPha[j].length / 4) * 1700 * 0.8
        isValidata.push(newPha[j].flowperhour > comNum)
      }
      if (isValidata.includes(true)) {
        this.$confirm(this.$t('openatccomponents.overview.maxFlow'),
          this.$t('openatccomponents.common.alarm'), {
            confirmButtonText: this.$t('openatccomponents.common.confirm'),
            cancelButtonText: this.$t('openatccomponents.common.cancel'),
            type: 'warning'
          }).then(() => {
          this.doOptimize(row, index, reqData)
        }).catch(() => {})
      } else {
        this.doOptimize(row, index, reqData)
      }
    },
    doOptimize (row, index, reqData) {
      // let _this = this
      getDuration(reqData).then(data => {
        if (data.data.success) {
          this.$message({
            type: 'success',
            message: this.$t('openatccomponents.pattern.success')
          })
          // let cycle = 0
          for (let i = 0; i < row.rings.length; i++) {
            for (let j = 0; j < row.rings[i].length; j++) {
              for (let h = 0; h < data.data.data.phase.length; h++) {
                if (row.rings[i][j].id === data.data.data.phase[h].id) {
                  row.rings[i][j].value = data.data.data.phase[h].duration
                  // cycle = cycle + row.rings[i][j].value
                }
              }
            }
          }
        }
      }).catch(error => {
        console.log(error)
      })
    },
    isShowColumn (colum) {
      let res = true
      if (this.tableColums && this.tableColums.length > 0) {
        res = this.tableColums.find(item => item === colum)
      }
      return res
    },
    getPeriod (row) {
      let period = row.timeperiodrange || row.period
      let res = ''
      if (period && period.length > 0) {
        res = period[0].substring(0, 5) + '-' + period[1].substring(0, 5)
      }
      return res
    },
    getDevName (row) {
      let res = row.name ? row.name : ''
      if (this.devicesData) {
        let dev = this.devicesData.find(item => item.agentid === row.agentid)
        res = dev ? dev.name : res
      }
      return res
    },
    onPatternTable (routeData, patternList, phaseList) {
      if (!patternList || patternList.length === 0) {
        // this.$message.error('方案为空！')
        return
      }
      if (!phaseList || phaseList.length === 0) {
        // this.$message.error('相位为空！')
        return
      }
      // this.routeData = routeData
      // this.patternList = patternList
      // this.phaseList = phaseList
      this.handlePatternList(routeData, patternList, phaseList)
    },
    // 依据anengid获取设备信息,同时兼容单路口数据按序index取值
    getDevFromDevsOrIndex (devs, agentid, index) {
      let res
      // check special
      let isSingleCrossMode = false
      if (devs && devs.length > 1 && devs[0] && devs[1] && devs[0].agentid === devs[1].agentid) {
        isSingleCrossMode = true
        // check errData
        if (index === undefined || index === null) {
          console.log('getDevFromDevsOrIndex Err: index is null')
        }
      }
      if (!isSingleCrossMode) {
        res = devs.filter(ist => ist && ist.agentid === agentid)[0]
      } else {
        res = devs[index]
        console.log('getDevByIndex:', res)
      }
      return res || {}
    },
    handlePatternList (routeData, patternList, phaseList) {
      this.newPatternList = []
      let devs = routeData.devs
      let index = 0
      for (let pattern of patternList) {
        let obj = {}
        let id = pattern.agentid
        obj.agentid = id
        let count = [] // 计算相位有几个环
        if (pattern.feature !== undefined && pattern.feature.patternList.length !== 0) {
          let currPatternList = pattern.feature.patternList
          // let dev = devs.filter(ist => ist.agentid === id)[0]
          let dev = this.getDevFromDevsOrIndex(devs, id, index)
          index = index + 1
          let patternId = dev.patternid
          let currPattern
          if (Array.isArray(currPatternList)) {
            currPattern = currPatternList.filter(cpl => cpl.id === patternId)[0]
            if (!currPattern) {
              currPattern = currPatternList[0]
            }
          } else {
            currPattern = currPatternList
          }
          if (!currPattern) {
            currPattern = currPatternList[0]
          }
          // let currPattern = currPatternList.filter(cpl => cpl.id === patternId)[0]
          if (currPattern.desc === '') {
            obj.desc = this.$t('openatccomponents.greenwaveoptimize.pattern') + currPattern.id
          } else {
            obj.desc = currPattern.desc
          }
          obj = {...obj, ...dev}
          obj.id = currPattern.id
          obj.offset = currPattern.offset
          obj.cycle = currPattern.cycle
          obj.patternId = currPattern.id
          obj.patternid = currPattern.id
          obj.patternDesc = currPattern.desc === '' ? `${this.$t('openatccomponents.greenwaveoptimize.pattern')}${currPattern.id}` : currPattern.desc
          obj.allPatterns = currPatternList.map(ele => {
            let patterndesc = ele.desc === '' ? `${this.$t('openatccomponents.greenwaveoptimize.pattern')}${currPattern.id}` : ele.desc
            return {
              patternid: ele.id,
              patterndes: ele.desc,
              patterndesc: patterndesc,
              ...ele
            }
          })
          let rings = currPattern.rings || []
          let phaseItem = phaseList.filter(phl => phl.agentid === id)[0]
          let currPhase = (phaseItem && phaseItem.feature && phaseItem.feature.phaseList) ? phaseItem.feature.phaseList : []
          obj.currPhase = currPhase
          obj.phaseList = currPhase
          // 计算有几个环
          for (let ring of rings) {
            if (!ring || ring.length === 0) continue
            for (let rr of ring) {
              if (!rr) continue
              rr.desc = []
              let targetPhase = currPhase.filter(curp => curp && curp.id === rr.id)[0]
              if (!targetPhase) continue
              let direction = targetPhase.direction || [] // 相位方向集合
              let phaseRing = targetPhase.ring
              count.push(phaseRing)
              for (let dir of direction) {
                let obj = {}
                obj.id = dir
                rr.desc.push(obj)
              }
            }
          }
          obj.rings = rings
        }
        let ringCount = Array.from(new Set(count)) // 去除数组重复的元素
        ringCount = ringCount.sort(this.sortNumbers) // 把数组中的值按照从小到大的顺序重新排序
        obj.ringCount = ringCount
        this.newPatternList.push(obj)
      }
      console.log('handlePatternList newPatternList', this.newPatternList)
    },
    sortNumbers (a, b) {
      return a - b
    },
    fatherMethod (val) {
      let index = val.index
      let cycle = val.cycle
      this.newPatternList[index].cycle = cycle
    },
    changeCurPattern (row, curPatternid) {
      // 修改当前方案（allPatterns： 所有可选项）
      const selectedPattern = row.allPatterns.filter(ele => ele && ele.patternid === curPatternid)[0]
      if (!selectedPattern) {
        console.warn('changeCurPattern: selectedPattern not found for patternid:', curPatternid)
        return
      }
      const data = {
        agentid: row.agentid,
        patternid: curPatternid,
        patterndes: selectedPattern.patterndes,
        allPatterns: row.allPatterns
      }
      row.desc = data.patternDesc
      row.patternId = data.patternid
      row.patternid = data.patternid
      row.patterndes = data.patterndes
      row.allPatterns = data.allPatterns
      row.patternid = data.patternid
      let selectPattern = row.allPatterns.filter(item => item && item.patternid === row.patternid)[0]
      if (!selectPattern) {
        console.warn('changeCurPattern: selectPattern not found for patternid:', row.patternid)
        return
      }
      let res = this.getRings(selectPattern.rings, row.phaseList)
      row.rings = res.rings
      row.ringCount = res.ringCount
      // row.rings = selectPattern.rings
      row.cycle = selectPattern.cycle
      row.offset = selectPattern.offset
      row.currPhase = row.phaseList
    },
    getRings (ringsList, phaseList) {
      let res = {}
      let rings = JSON.parse(JSON.stringify(ringsList || []))
      let count = []
      // 计算有几个环
      for (let ring of rings) {
        if (!ring || ring.length === 0) continue
        for (let rr of ring) {
          if (!rr) continue
          rr.desc = []
          let targetPhase = phaseList.filter(curp => curp && curp.id === rr.id)[0]
          if (!targetPhase) continue
          let direction = targetPhase.direction || [] // 相位方向集合
          let phaseRing = targetPhase.ring
          count.push(phaseRing)
          for (let dir of direction) {
            let obj = {}
            obj.id = dir
            rr.desc.push(obj)
          }
        }
      }
      let ringCount = Array.from(new Set(count)) // 去除数组重复的元素
      ringCount = ringCount.sort(this.sortNumbers) // 把数组中的值按照从小到大的顺序重新排序
      res = {
        rings: rings,
        ringCount: ringCount
      }
      return res
    },
    getControlType (row) {
      let contrloType = 'ring'
      let allPatternList = row.feature && row.feature.patternList ? row.feature.patternList : row.allPatterns
      if (!allPatternList || allPatternList.length === 0) {
        return contrloType
      }
      let firstPattern = allPatternList[0]
      if (
        !firstPattern.contrloType &&
        firstPattern.rings &&
        firstPattern.rings.length > 0
      ) {
        contrloType = 'ring'
      } else if (
        !firstPattern.contrloType &&
        (!firstPattern.rings || firstPattern.rings.length === 0)
      ) {
        contrloType = 'stage'
      } else {
        contrloType = firstPattern.contrloType || 'ring'
      }
      let res = contrloType
      return res
    },
    getSelectedPattern (row) {
      let res = []
      let patternList = row.feature && row.feature.patternList ? row.feature.patternList : row.allPatterns
      let pattern = patternList.find(item => item.id === row.patternid)
      if (pattern) {
        res = JSON.parse(JSON.stringify(pattern))
      }
      return res
    },
    getCurPattern (agentid) {
      // 获取当前设备所有可选方案
      this.loading = true
      let _this = this
      getIntersectionInfo(agentid).then(res => {
        this.loading = false
        if (!res.data.success) {
          let commomMsg = this.$t('openatccomponents.overview.signalID') + ' : ' + agentid
          let msg = getMessageByCode(res.data.code, this.$i18n.locale)
          if (res.data.data) {
            // 子类型错误
            let childErrorCode = res.data.data.errorCode
            if (childErrorCode) {
              let childerror = getMessageByCode(res.data.data.errorCode, this.$i18n.locale)
              msg = msg + ' - ' + childerror
            }
          }
          msg = msg + ' - ' + commomMsg
          this.$message.error(msg)
          return
        }
        let allPatternList = res.data.data.param.patternList
        _this.newPatternList.forEach(ele => {
          if (ele.agentid === agentid) {
            ele.allPatterns = allPatternList.map(ele => {
              return {
                ...ele,
                patternid: ele.id,
                patterndes: ele.desc,
                patterndesc: ele.desc === '' ? `${_this.$t('openatccomponents.greenwaveoptimize.pattern')}${ele.id}` : ele.desc
              }
            })
          }
        })
      })
    }
  }
}
</script>

<style lang="scss">
  .board {
    width: 100%;
    margin-left: 10PX;
    display: flex;
    justify-content: flex-start;
    gap: 10PX;
    align-items: flex-start;
  }
  .optimizetype{
    font-size: 14PX;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    gap: 10PX;
    padding-left: 20PX;
    .el-input {
      width: 120PX;
    }
    // .el-select{
    //   width: 170PX;
    // }
    // .el-button {
    //   margin-left: 10PX;
    // }
    .optimiNum {
      padding-left: 10PX;
    }
  }
</style>
