<template>
  <div>
    <div>
      <Form
        :model="formInline"
        ref="form1"
        label-position="left"
      >
        <Col span="5" v-if="user_level ==='2'">
          <FormItem label="" key="cityId"  prop="cityId" :rules="[{ required: true, message: '必填', trigger: 'change' },]">
            <Select
              v-model="formInline.cityId"
              @on-change="changeArea('2', formInline.cityId)"
              placeholder="请选择市"
              style="width: 90%"
            >
              <Option
                v-for="item in areaData.list1"
                :value="item.parent_id"
                :key="item.parent_id"
              >{{ item.name }}</Option
              >
            </Select>
          </FormItem>
        </Col>
        <Col span="5" v-if="user_level ==='3' || user_level ==='2'">
          <FormItem
            prop="areaId"
            key="areaId"
            :label-width="0"
            :rules="[
                      { required: true, message: '必填', trigger: 'change' },
                    ]"
          >
            <Select
              v-model="formInline.areaId"
              placeholder="请选择区"
              style="width: 90%"
              @on-change="areaSelected"
            >
              <Option
                v-for="item in areaData.list2"
                :value="item.parent_id"
                :key="item.parent_id"
              >{{ item.name }}</Option
              >
            </Select>
          </FormItem>
        </Col>
        <Col span="2" v-if="user_level ==='3' || user_level ==='2'">
          <Button  @click="revert">重置</Button>
        </Col>
      </Form>
    </div>
    <!-- 一级预警 -->
    <div v-if="currentAlarmLevel === '1'" class="box" style="width:100%;height: 80vh">
      <div class="top-box"  @click="toPage(`/riskFactorWarn?type=1&status=1&history=1&cityId=${formInline.cityId || ''}&areaId=${formInline.areaId || ''}`)">
        <img src="@/assets/contradictionImgs/warn1-1.png" alt="">
        <div class="num">{{ warningData.eventRiskFactor || 0 }}</div>
        <div class="title">风险因子预警历史</div>
      </div>
      <div class="top-box" @click="toPage(`/groupEventWarn?alarmLevel=1&history=1&cityId=${formInline.cityId || ''}&areaId=${formInline.areaId || ''}`)">
        <img src="@/assets/contradictionImgs/warn1-2.png" alt="">
        <div class="num">{{ warningData.groupEvent || 0 }}</div>
        <div class="title">群体性事件预警历史</div>
      </div>
      <div class="top-box" @click="toPage(`/keyAreaWarn?type=1&history=1&cityId=${formInline.cityId || ''}&areaId=${formInline.areaId || ''}`)">
        <img src="@/assets/contradictionImgs/warn1-3.png" alt="">
        <div class="num">{{ warningData.focusAreas || 0 }}</div>
        <div class="title">重点领域预警历史</div>
      </div>
      <div class="top-box" @click="toPage(`/keyAreaWarnList?is_involve_everyone_count=2&alarmLevel=1&history=1&cityId=${formInline.cityId || ''}&areaId=${formInline.areaId || ''}`)">
        <img src="@/assets/contradictionImgs/warn1-4.png" alt="">
        <div class="num">{{ warningData.involveEveryone || 0 }}</div>
        <div class="title">涉众预警历史</div>
      </div>
    </div>

    <!-- 二级预警 -->
    <div v-else-if="currentAlarmLevel === '2'" class="box" style="width:100%;height: 80vh">
      <div class="top-box"  @click="toPage(`/riskFactorWarn?type=2&status=1&history=2&cityId=${formInline.cityId || ''}&areaId=${formInline.areaId || ''}`)">
        <img src="@/assets/contradictionImgs/warn1-1.png" alt="">
        <div class="num">{{ warningData.eventRiskFactor || 0 }}</div>
        <div class="title">风险因子预警历史</div>
      </div>
      <div class="top-box" @click="toPage(`/groupEventWarn?alarmLevel=2&history=2&cityId=${formInline.cityId || ''}&areaId=${formInline.areaId || ''}`)">
        <img src="@/assets/contradictionImgs/warn1-2.png" alt="">
        <div class="num">{{ warningData.groupEvent || 0 }}</div>
        <div class="title">群体性事件预警历史</div>
      </div>
      <div class="top-box" @click="toPage(`/keyAreaWarn?type=2&history=2&cityId=${formInline.cityId || ''}&areaId=${formInline.areaId || ''}`)">
        <img src="@/assets/contradictionImgs/warn1-3.png" alt="">
        <div class="num">{{ warningData.focusAreas || 0 }}</div>
        <div class="title">重点领域预警历史</div>
      </div>
      <div class="top-box" @click="toPage(`/keyAreaWarnList?is_involve_everyone_count=1&alarmLevel=2&history=2&cityId=${formInline.cityId || ''}&areaId=${formInline.areaId || ''}`)">
        <img src="@/assets/contradictionImgs/warn1-4.png" alt="">
        <div class="num">{{ warningData.involveEveryone || 0 }}</div>
        <div class="title">涉众预警历史</div>
      </div>
    </div>

    <!-- 三级预警 -->
    <div v-else-if="currentAlarmLevel === '3'" class="box box-level-3" style="width:100%;height: 80vh">
      <div class="top-box" @click="toPage(`/levelWarnList?history=1&cityId=${formInline.cityId || ''}&areaId=${formInline.areaId || ''}`)">
        <img src="@/assets/contradictionImgs/warn2-1.png" alt="" class="topimg">
        <div class="num">{{ warningData.importantUser || 0 }}</div>
        <div class="title">重点人预警历史</div>
      </div>
      <div class="top-box" @click="toPage(`/overdueEventWarn?alarmLevel=3&history=1&cityId=${formInline.cityId || ''}&areaId=${formInline.areaId || ''}`)">
        <img src="@/assets/contradictionImgs/warn2-2.png" alt="" class="topimg">
        <div class="num">{{ warningData.overdueEvent || 0 }}</div>
        <div class="title">矛盾超期预警历史</div>
      </div>
      <div class="top-box" @click="toPage(`/riskFactorWarn?type=3&status=1&history=3&cityId=${formInline.cityId || ''}&areaId=${formInline.areaId || ''}`)">
        <img src="@/assets/contradictionImgs/warn2-3.png" alt="" class="topimg">
        <div class="num">{{ warningData.eventRiskFactor || 0 }}</div>
        <div class="title">风险因子预警历史</div>
      </div>
      <div class="top-box" @click="toPage(`/groupEventWarn?alarmLevel=3&history=3&cityId=${formInline.cityId || ''}&areaId=${formInline.areaId || ''}`)">
        <img src="@/assets/contradictionImgs/warn2-4.png" alt="" class="topimg">
        <div class="num">{{ warningData.groupEvent || 0 }}</div>
        <div class="title">群体性事件预警历史</div>
      </div>
      <div class="top-box" @click="toPage(`/keyAreaWarnList?is_involve_everyone_count=0&alarmLevel=3&history=3&cityId=${formInline.cityId || ''}&areaId=${formInline.areaId || ''}`)">
        <img src="@/assets/contradictionImgs/warn2-5.png" alt="" class="topimg">
        <div class="num">{{ warningData.involveEveryone || 0 }}</div>
        <div class="title">涉众预警历史</div>
      </div>
    </div>
  </div>
</template>

<script>
import { selectCityList, getWarningStatisticsCountHistory } from '@/api/contradiction.js'

export default {
  props: {
    alarmLevel: {
      type: String,
      default: '1'
    }
  },
  data () {
    return {
      formInline: {},
      user_level: '',
      currentAlarmLevel: '1', // 当前显示的预警等级
      areaData: {
        list1: [],
        list2: [],
        list3: [],
        list4: []
      },
      warningData: {
        eventRiskFactor: 0, // 风险因子预警
        groupEvent: 0, // 群体性事件预警
        focusAreas: 0, // 重点领域预警
        involveEveryone: 0, // 涉众预警
        overdueEvent: 0, // 矛盾超期预警
        importantUser: 0, // 重点人预警
        total: 0 // 预警总数
      }
    }
  },
  watch: {
    // 监听路由变化
    '$route': {
      handler (to, from) {
        // 路由变化时更新预警等级
        this.updateAlarmLevel()
      },
      immediate: false,
      deep: true
    },
    // 监听props变化
    alarmLevel: {
      handler (newVal) {
        this.currentAlarmLevel = newVal
        this._getWarningStatisticsCountHistory()
      },
      immediate: true
    }
  },
  async mounted () {
    this.updateAlarmLevel()
    this.user_level = this.$store.state.user.severUserInfo.company_grade
    if (this.user_level === '2') {
      await this.getCityData('1')
    }
    if (this.user_level === '3') {
      await this.getCityData('2', this.$store.state.user.severUserInfo.company_id)
    }
    // this._getWarningStatisticsCountHistory()
  },
  methods: {
    revert () {
      // 清空表单数据
      this.formInline = {}
      // 清除表单验证状态，避免显示必填提示
      this.$refs.form1.resetFields()
    },
    // 更新当前预警等级
    updateAlarmLevel () {
      // 优先使用props，其次使用路由参数
      this.currentAlarmLevel = this.alarmLevel || this.$route.query.alarmLevel || '1'
    },
    async getCityData (level, id) {
      if (!id && level === '2') {
        this.areaData['list' + level] = []
        return
      }
      let res = await selectCityList({ parent_id: id })
      if (res.data.errcode === 0) {
        this.areaData['list' + level] = res.data.data
        return
      }
      this.$Message.error(res.errmsg)
    },
    async changeArea (level, parent_id) {
      await this.getCityData(level, parent_id)
      // 选择城市或区县后重新获取统计数据
      this._getWarningStatisticsCountHistory()
    },
    toPage (url) {
      // 获取当前选择的城市和区县
      const { cityId, areaId } = this.formInline
      // 解析已有的url参数
      let [baseUrl, queryStr] = url.split('?')
      let params = new URLSearchParams(queryStr || '')
      if (cityId) params.set('cityId', cityId)
      if (areaId) params.set('areaId', areaId)
      this.$router.push({
        path: baseUrl,
        query: Object.fromEntries(params.entries())
      })
    },
    // 获取预警统计数据
    _getWarningStatisticsCountHistory () {
      getWarningStatisticsCountHistory({
        alarmLevel: this.currentAlarmLevel, // 预警等级（1一级预警 2二级预警 3三级预警）
        cityId: this.formInline.cityId, // 传递城市参数
        areaId: this.formInline.areaId // 传递区县参数
      }).then(res => {
        if (res.data.errcode === 0) {
          this.warningData = {
            eventRiskFactor: res.data.data.eventRiskFactor || 0,
            groupEvent: res.data.data.groupEvent || 0,
            focusAreas: res.data.data.focusAreas || 0,
            involveEveryone: res.data.data.involveEveryone || 0,
            overdueEvent: res.data.data.overdueEvent || 0,
            importantUser: res.data.data.importantUser || 0,
            total: res.data.data.total || 0
          }
        } else {
          this.$Message.error(res.data.errmsg || '获取预警统计数据失败')
        }
      }).catch(error => {
        console.error('获取预警统计数据失败:', error)
        this.$Message.error('获取预警统计数据失败')
      })
    },
    // 区县选择后触发查询
    areaSelected () {
      // 区县选择后重新获取统计数据
      this._getWarningStatisticsCountHistory()
    }
  }
}
</script>

<style scoped lang="less">
.box{
  display: flex;
  justify-content: space-around;
  align-items: flex-start;
  flex-wrap: wrap;

  // 为三级预警专门添加的样式
  &.box-level-3 {
    flex-wrap: nowrap;

    .top-box {
      width: 19%;
    }
  }

  .top-box{
    display: flex;
    flex-direction:column;
    justify-content: center;
    align-items: center;
    width: 24%;
    height: 200px;
    border-radius: 16px;
    background: #ffeeec;
    border: 1px solid #c53535;
    cursor: pointer;
    margin-bottom: 20px;

    .title{
      font-family: "PingFang SC";
      font-weight: 400;
      font-size: 14px;
      text-align: center;
      color: #2e3038;
    }
    .num{
      font-family: "Montserrat";
      font-weight: 500;
      font-size: 36px;
      text-align: center;
      color: #c53535;
    }
  }
}

.topimg {
  width: 60px;
  height: 60px;
}
</style>
