<template>
  <div class="way-filter">
    <!-- v-model="waySelected" -->

    <el-cascader
      v-model="formOp.default"
      :options="options"
      clearable
      placeholder="全国"
      :props="{ checkStrictly: true, expandTrigger: 'hover' }"
      @change="toUnit"
      @visible-change="elCascaderOnClick"
      @expand-change="elCascaderOnClick"
      size="mini"
      :popper-append-to-body="false"
      popper-class="wayPoper"
      ref="cascader"
      style="width: 230px;"
    ></el-cascader>
    <div class="dateTime">
      <el-date-picker
        v-model="year"
        type="month"
        size="small"
        :clearable="false"
        popper-class="n_date__popper"
        style="width: 120px; cursor: pointer;"
        @change="setYear"
        :editable="false"
      ></el-date-picker>
    </div>
  </div>
</template>
<script lang="jsx">
import { mapState, mapMutations } from 'vuex'
import { orgByXZ } from '@/api/ele-control-cabin'
export default {
  data() {
    return {
      year: '',
      formOp: {
        default: [],
      },
      options: [],
      orgValue: [[]],
    }
  },
  computed: {
    ...mapState({
      allRoads: (state) => state.road.allRoads,
    }),
  },
  created() {
    console.log(this.$store.state.appDate)
    this.year = this.formatDate(new Date(this.$store.state.appDate), 'yyyy-MM')
    this.$store.commit('ele/SET_STATE', {
      key: 'currentTime',
      value: this.year,
    })
    this.sysOrgSelect()
  },
  watch: {
    '$route.query.road': {
      handler(val) {
        this.initSelectOrg()
      },
    },
    '$route.query.month': {
      handler(val) {
        val && this.setYear(new Date(val))
      },
    },
  },
  methods: {
    formatDate(date, format) {
      if (!date) {
        return ''
      }

      format = format || 'yyyy-MM-dd hh:mm:ss'
      date = new Date(date)
      let map = {
        M: date.getMonth() + 1, //月份
        d: date.getDate(), //日
        h: date.getHours(), //小时
        m: date.getMinutes(), //分
        s: date.getSeconds(), //秒
        q: Math.floor((date.getMonth() + 3) / 3), //季度
        S: date.getMilliseconds(), //毫秒
      }

      format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
        let v = map[t]
        if (v !== undefined) {
          if (all.length > 1) {
            v = '0' + v
            v = v.substr(v.length - 2)
          }
          return v
        } else if (t === 'y') {
          return (date.getFullYear() + '').substr(4 - all.length)
        }
        return all
      })
      return format
    },
    sysOrgSelect() {
      orgByXZ().then(({ code, msg, data }) => {
        if (code === 0) {
          this.options = this.expandNode(data[0].children || [])

          // 给定的标签数组
          const labelsToRemove = [
            '渝遂扩能',
            '南潼、南充过境高速',
            '阆营高速',
            '泸古高速',
            '丘砚高速',
            '陆寻高速',
            '昆宜高速',
          ]
          function removeLabels(nestedArray, labelsToRemove) {
            // 辅助函数，用于递归过滤节点
            function filterNodes(nodes) {
              // 使用map进行变换，并且用filter去除null值
              return nodes
                .map((node) => {
                  // 如果当前节点需要被移除，则不包含该节点，返回null
                  if (labelsToRemove.includes(node.label)) {
                    return null
                  }

                  // 如果有子节点，递归调用filterNodes
                  if (node.children && node.children.length) {
                    const filteredChildren = filterNodes(node.children)
                    // 如果过滤后的子节点数组为空，也不包含当前节点
                    if (filteredChildren.length === 0) {
                      return null
                    }
                    // 更新当前节点的子节点为过滤后的子节点
                    node.children = filteredChildren
                  }
                  // 返回当前节点
                  return node
                })
                .filter((node) => node !== null) // 移除所有null值
            }

            // 从顶层节点开始递归过滤
            return filterNodes(nestedArray)
          }

          // 调用函数并打印结果
          const result = removeLabels(this.options, labelsToRemove)
          // console.log(result, 'resultresultresult')

          // 只有一项的情况选中第一项
          if (this.options.length === 1) {
            this.initSelectOrg()
            const arr = []
            let item = this.options[0]
            if (item) {
              arr.push(item.organizationId)
              if (item.children.length === 1) {
                item = item.children[0]
                arr.push(item.organizationId)
                if (item.children.length === 1) {
                  item = item.children[0]
                  arr.push(item.organizationId)
                }
              }
            }
            this.toUnit(arr)
            return
          }
          this.toUnit([])
        } else {
          this.$message.error(msg)
        }
      })
    },
    expandNode(data) {
      data.forEach((item, index) => {
        if (index === 0 && this.orgValue.length < 3) {
          this.orgValue.push(item.organizationId)
        }
        item.value = item.organizationId
        item.label = item.organizationName
        if (item.children.length > 0) {
          this.expandNode(item.children)
        } else {
          item.children = null
        }
      })
      return data
    },
    toUnit(node) {
      const targetNode = node ? node : []
      let groupIds = []
      let grysid = []
      let pOrg = {}
      let groupId = {}
      if (targetNode.length === 3) {
        // 选择第三级
        groupIds.push(targetNode[2])
        // 选择第二级
        let thirdArr = this.options
          .filter((item) => item.organizationId === targetNode[0])[0]
          .children.filter((v) => v.organizationId === targetNode[1])[0]
          .children.filter((v) => v.organizationId === targetNode[2])
        grysid = thirdArr.map((v) => v.ysId)
        this.$store.commit('ele/SET_STATE', { key: 'orgType', value: 0 })
      } else if (targetNode.length === 2) {
        // 选择第二级
        let thirdArr = this.options
          .filter((item) => item.organizationId === targetNode[0])[0]
          .children.filter((v) => v.organizationId === targetNode[1])[0]
          .children
        groupIds = thirdArr.map((v) => v.organizationId)
        grysid = thirdArr.map((v) => v.ysId)

        pOrg.orgIds = [targetNode[1]] || []
        this.$store.commit('ele/SET_STATE', { key: 'orgType', value: 1 })
      } else if (targetNode.length === 1) {
        // 选择第一级
        let secArr = this.options.filter(
          (item) => item.organizationId === targetNode[0],
        )[0].children
        if (secArr) {
          secArr.forEach((v) => {
            v.children.forEach((vv) => {
              groupIds.push(vv.organizationId)
              grysid.push(vv.ysId)
            })
          })
        }
        pOrg.masterIds = node || []
        this.$store.commit('ele/SET_STATE', { key: 'orgType', value: 1 })
      } else {
        // 选择第一级
        this.options.forEach((v) => {
          v.children &&
            v.children.forEach((vv) => {
              vv.children &&
                vv.children.forEach((vvv) => {
                  groupIds.push(vvv.organizationId)
                  grysid.push(vvv.ysId)
                })
            })
        })
        this.$store.commit('ele/SET_STATE', { key: 'orgType', value: 1 })
      }
      groupId.groupIds = groupIds
      this.$store.commit('ele/SET_STATE', { key: 'orgCode', value: groupId })
      this.$store.commit('ele/SET_STATE', { key: 'ysId', value: grysid })
      this.$store.commit('ele/SET_STATE', { key: 'pOrg', value: pOrg })
      this.$store.commit('ele/SET_STATE', { key: 'OrgId', value: targetNode })
      this.$store.commit('ele/SET_STATE', {
        key: 'refresh',
        value: new Date().valueOf(),
      })
    },
    setYear(val) {
      const currentTime = this.formatDate(new Date(val), 'yyyy-MM')
      this.year = currentTime
      this.$store.commit('changeDate', currentTime)
      this.$store.commit('ele/SET_STATE', {
        key: 'currentTime',
        value: currentTime,
      })
      this.$store.commit('ele/SET_STATE', {
        key: 'refresh',
        value: new Date().valueOf(),
      })
    },
    initSelectOrg() {
      const { allRoads } = this
      if (!allRoads || allRoads.length < 1) {
        return
      }
      let selectItem
      if (this.$route.query?.road) {
        const id = [this.$route.query.road]
        selectItem = this.allRoads.filter(
          (item) => item.organizationId == id[id.length - 1],
        )[0]
      } else {
        const level3Items = allRoads.filter((item) => item.level === '3')
        const level2Items = allRoads.filter((item) => item.level === '2')
        const level1Items = allRoads.filter((item) => item.level === '1')
        if (level3Items.length === 1) {
          selectItem = level3Items[0]
        } else if (level2Items.length === 1) {
          selectItem = level2Items[0]
        } else if (level1Items.length === 1) {
          selectItem = level1Items[0]
        }
      }
      if (selectItem) {
        if (selectItem.level === '1') {
          this.formOp.default = [selectItem.organizationId]
        } else if (selectItem.level === '2') {
          this.formOp.default = [selectItem.pnode, selectItem.organizationId]
        } else if (selectItem.level === '3') {
          this.formOp.default = [
            selectItem.provinceId,
            selectItem.pnode,
            selectItem.organizationId,
          ]
        }
      }
    },
  },
}
</script>
<style lang="postcss" scoped>
.way-filter {
  display: flex;
  margin-top: 15px;
  margin-bottom: 15px;
  margin-left: 12px;
}

::v-deep(.el-input__inner) {
  color: #fff;
  background: rgba(5, 15, 45, 0.5);
  border: 1px solid #2c4e91;
  height: 30px;
  cursor: pointer;
  line-height: 32px;

  &:hover {
    border: 1px solid #7ebee9;
  }
}

.dateTime {
  margin-left: 15px;
  cursor: pointer;
}
</style>
<style lang="postcss">
.wayPoper {
  background: rgba(5, 15, 45, 0.7) !important;
}

.el-cascader-node {
  color: #fff;
}

.el-cascader-node.is-selectable.in-active-path {
  color: rgba(59, 130, 246, 1) !important;
}

.el-radio__label {
  display: inline-block;
  width: 200px;
  height: 34px;
  position: absolute;
  top: -5px;
}
</style>
