<template>
  <div class="contradiction-div">
    <div class="head-title">重点领域预警列表</div>
    <div class="search-div clearfix">
      <div class="search-area">
        <div class="search-content">
          <Row class="mb10">
            <Col span="6">
              <span>纠纷编号：</span>
              <Input style="width: 70%" v-model="searchInfo.eventCode" />
            </Col>
            <Col span="6">
              <span>纠纷大类：</span>
              <Select
                v-model="searchInfo.info"
                @on-clear="clearDispute('info')"
                @on-change="changeDispute(searchInfo.info)"
                :clearable="true"
                style="width: 70%"
              >
                <Option
                  v-for="item in dictData.list1"
                  :value="JSON.stringify(item)"
                  :key="item.value"
                  >{{ item.label }}</Option
                >
              </Select>
            </Col>
            <Col span="6">
              <span>纠纷小类：</span>
              <Select
                v-model="searchInfo.eventTypeId"
                :clearable="true"
                style="width: 70%"
              >
                <Option
                  v-for="item in dictData.list2"
                  :value="item.value"
                  :key="item.value"
                  >{{ item.label }}</Option
                >
              </Select>
            </Col>
            <Col span="6">
              <span>开始时间：</span>
              <DatePicker
                type="date"
                v-model="searchInfo.startTime"
                placeholder="请选择开始时间"
              ></DatePicker>
            </Col>
          </Row>
          <Row class="mb10">
            <Col span="6">
              <span>结束时间：</span>
              <DatePicker
                type="date"
                v-model="searchInfo.endTime"
                placeholder="请选择结束时间"
              ></DatePicker>
            </Col>
            <Col span="6">
              <span>统计范围：</span>
              <Select
                v-model="searchInfo.cityId"
                @on-change="changeArea('2', searchInfo.cityId)"
                :clearable="true"
                placeholder="请选择市"
                style="width: 70%"
              >
                <Option
                  v-for="item in areaData.list1"
                  :value="item.parent_id"
                  :key="item.parent_id"
                  >{{ item.name }}</Option
                >
              </Select>
            </Col>
            <Col span="4" class="mr5">
              <Select
                v-model="searchInfo.areaId"
                @on-change="changeArea('3', searchInfo.areaId)"
                :clearable="true"
                placeholder="请选择区"
                style="width: 100%"
              >
                <Option
                  v-for="item in areaData.list2"
                  :value="item.parent_id"
                  :key="item.parent_id"
                  >{{ item.name }}</Option
                >
              </Select>
            </Col>
            <Col span="4" class="mr5">
              <Select
                v-model="searchInfo.streetId"
                @on-change="changeArea('4', searchInfo.streetId)"
                :clearable="true"
                placeholder="请选择街道"
                style="width: 100%"
              >
                <Option
                  v-for="item in areaData.list3"
                  :value="item.parent_id"
                  :key="item.parent_id"
                  >{{ item.name }}</Option
                >
              </Select>
            </Col>
            <Col span="4">
              <Select
                v-model="searchInfo.communityId"
                placeholder="请选择社区"
                :clearable="true"
                style="width: 100%"
              >
                <Option
                  v-for="item in areaData.list4"
                  :value="item.parent_id"
                  :key="item.parent_id"
                  >{{ item.name }}</Option
                >
              </Select>
            </Col>
          </Row>
          <Row class="">
            <Alert v-if="$route.query.status === '2'" type="warning">在矛盾纠纷录入中，选择“涉众”，并选择5人以上，触发预警。</Alert>
            <Alert v-if="$route.query.is_involve_everyone_count === '2'" type="warning">在矛盾纠纷录入中，选择“涉众”，并选择300人以上，触发预警。</Alert>
            <Alert v-if="$route.query.is_involve_everyone_count === '1'" type="warning">在矛盾纠纷录入中，选择“涉众”，并选择31-300人，触发预警。</Alert>
            <Alert v-if="$route.query.is_involve_everyone_count === '0'" type="warning">在矛盾纠纷录入中，选择“涉众”，并选择5-30人，触发预警。</Alert>
          </Row>
        </div>
        <!-- <div class="search-buttons">
          <Button type="primary" @click="searchData" style="margin-right: 10px;">搜索</Button>
           <Col span="12">
            <Button  @click="resert">重置</Button>
          </Col>
        </div> -->
         <div style="width: 10%; float: left">
        <Row>
          <Col span="12">
            <Button type="primary" @click="searchData">搜索</Button>
          </Col>
          <Col offset="2" span="10">
            <Button type="primary" @click="resert">重置</Button>
          </Col>
        </Row>
      </div>
      </div>
    </div>
    <div class="table-container">
      <vxe-table
        :data="dataList"
        :loading="loading"
        stripe
        show-overflow
        size="small"
        resizable
        align="center"
        header-align="center"
        empty-text="暂无数据"
      >
        <vxe-column title="序号" align="center" type="seq" width="60" />
        <vxe-column title="纠纷编号" align="center" field="eventCode" />
        <vxe-column title="纠纷大类" align="center" field="eventCategoryId" />
        <vxe-column title="纠纷小类" align="center" field="eventTypeId" />
        <vxe-column title="纠纷发生地" align="center" field="place" />
        <vxe-column title="风险等级" align="center" field="riskLevel">
          <template v-slot="{ row }">
            <div class="flex-div">
              <div v-if="row.riskLevel == '一般矛盾纠纷'">
                <img
                  class="level-option-img"
                  src="@/assets/images/warning4.png"
                  alt=""
                />
                <span style="padding-left: 10px">一般矛盾纠纷</span>
              </div>
              <div v-if="row.riskLevel == '复杂矛盾纠纷'">
                <img
                  class="level-option-img"
                  src="@/assets/images/warning5.png"
                  alt=""
                />
                <span style="padding-left: 10px">复杂矛盾纠纷</span>
              </div>
              <div v-if="row.riskLevel == '重大矛盾纠纷'">
                <img
                  class="level-option-img"
                  src="@/assets/images/warning6.png"
                  alt=""
                />
                <span style="padding-left: 10px">重大矛盾纠纷</span>
              </div>
            </div>
          </template>
        </vxe-column>
        <vxe-column title="发生时间" align="center" field="occurrenceTime" />
<!--        <vxe-column title="化解状态" align="center" field="is_resolve">-->
<!--          <template v-slot="{ row }">-->
<!--            <div>{{ row.is_resolve === '1' ? '已化解' : '未化解' }}</div>-->
<!--          </template>-->
<!--        </vxe-column>-->
        <vxe-column
          title="操作"
          align="center"
          fixed="right"
          class-name="small-padding fixed-width"
          width="100"
        >
          <template v-slot="{ row }">
            <Button type="primary" class="mr5" @click="getEventInfo(row)"
              >详情</Button
            >
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <Page
      class="page_style"
      :total="params.totalRecord"
      :current="params.pageNo"
      :page-size="params.pageSize"
      @on-change="changePageNo"
      show-total
      show-sizer
      @on-page-size-change="size"
    />
  </div>
</template>
<script>
import {
  selectDictList,
  selectCityList,
  findInvolveEveryonePageList
} from '@/api/contradiction.js'
import { date2str } from '@/api/eventlist.js'
export default {
  name: 'keyAreaWarnList',
  meta: {
    notCache: true
  },
  data () {
    return {
      dictData: {
        list1: [],
        list2: []
      },
      areaData: {
        list1: [],
        list2: [],
        list3: [],
        list4: []
      },
      searchInfo: {},
      dataList: [],
      loading: false,
      params: {
        pageNo: 1,
        pageSize: 10,
        totalRecord: 0,
        eventType: '2'
      },
      isRouteEntered: false
    }
  },
  mounted () {
    this.getDictList('1')
    this.getCityData('1')
    // 立即加载数据
    this.getList()
  },
  created () {
    console.log('组件创建 - created')
  },
  updated () {
    console.log('组件更新 - updated')
  },
  activated () {
    this.getList()
  },

  methods: {
    getDictList (level, id) {
      selectDictList({ type: 'event_category', parent_id: id }).then(res => {
        if (res.data.errcode === 0) {
          this.dictData.list = res.data.data
          this.dictData['list' + level] = res.data.data
          return
        }
        this.$Message.error(res.errmsg)
      })
    },
    clearDispute (res) {
      // 清空纠纷大类
      this.$nextTick(() => {
        // clearable后会直接把searchInfo里的该字段删除掉
        this.$set(this.searchInfo, 'event_category_id', '')
        this.$set(this.searchInfo, res, res === 'info' ? '{}' : '')
      })
    },
    changeDispute (item) {
      this.searchInfo.event_category_id = JSON.parse(item).value
      this.getDictList('2', JSON.parse(item).id)
    },
    getCityData (level, id) {
      selectCityList({ parent_id: id }).then(res => {
        if (res.data.errcode === 0) {
          this.areaData['list' + level] = res.data.data
          return
        }
        this.$Message.error(res.errmsg)
      })
    },
    changeArea (level, parent_id) {
      this.getCityData(level, parent_id)
    },
    getList (item) {
      // 创建一个新的参数对象
      let requestParams = {
        pageNo: this.params.pageNo,
        pageSize: this.params.pageSize
      }
      // 处理搜索条件
      if (item) {
        // 合并搜索条件
        Object.keys(item).forEach(key => {
          if (item[key] !== null && item[key] !== undefined && item[key] !== '') {
            requestParams[key] = item[key]
          }
        })
        // 处理日期格式
        if (requestParams.startTime) {
          requestParams.startTime = date2str(requestParams.startTime)
        }
        if (requestParams.endTime) {
          requestParams.endTime = date2str(requestParams.endTime)
        }
      }
      if (this.$route.query.status) {
        requestParams.status = this.$route.query.status
      }
      if (this.$route.query.is_involve_everyone_count) {
        requestParams.is_involve_everyone_count = this.$route.query.is_involve_everyone_count
      }
      if (this.$route.query.alarmLevel) {
        requestParams.alarmLevel = this.$route.query.alarmLevel
      }
      // 显示加载中
      this.loading = true
      // 调用API
      findInvolveEveryonePageList(requestParams).then(res => {
        this.loading = false
        if (res.data.errcode === 0) {
          // 处理返回数据
          if (res.data.data && Array.isArray(res.data.data.results)) {
            this.dataList = res.data.data.results
            this.dataList.forEach(item => {
              item.place = item.city + item.area + item.street + item.community
            })
            this.params.totalRecord = res.data.data.totalRecord || 0
          } else {
            this.dataList = []
            this.params.totalRecord = 0
          }
        } else {
          this.$Message.error(res.data.errmsg || '获取数据失败')
          this.dataList = []
        }
      }).catch(err => {
        this.loading = false
        this.$Message.error('获取数据失败' + err)
        this.dataList = []
      })
    },
    size (pageSize) {
      this.params.pageSize = pageSize
      this.changePageNo()
    },
    changePageNo (pageNo) {
      this.params.pageNo = pageNo
      this.getList(this.params)
    },
    searchData () {
      // 重置页码
      this.params.pageNo = 1

      // 处理event_category_id
      if (this.searchInfo.info && this.searchInfo.info !== '{}') {
        try {
          const categoryInfo = JSON.parse(this.searchInfo.info)
          this.searchInfo.event_category_id = categoryInfo.value
        } catch (e) {
          console.error('解析纠纷大类信息失败:', e)
        }
      }

      // 调用getList方法，传递处理后的搜索条件
      this.getList(this.searchInfo)
    },
    resert () {
      this.searchInfo = {}
      this.params.pageNo = 1
      this.searchData()
    },
    getEventInfo (row) {
      // 详情页
      this.$router.push({
        name: 'contradictionRegisterAdd',
        params: {
          what: 'edit',
          id: row.id,
          level: '',
          isInfo: true,
          isShowInfo: true // 控制化解过程显隐
        }
      })
    }
  },
  computed: {
    serverUserInfo () {
      return this.$store.state.user.severUserInfo
    }
  },
  deactivated () {
    console.log('组件停用 - deactivated，页面离开时调用')
    // 可以在这里清除一些资源或状态
  },
  inject: {
    reload: {
      default: () => {}
    }
  }
}
</script>
<style scoped lang="less">
.contradiction-div {
  padding: 10px;
  width: 100%;
  height: 100%;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
}
.search-div {
  width: 100%;
  padding: 15px;
  border: 1px solid skyblue;
  border-radius: 5px;
  background-color: #f6fdfd;
  margin-bottom: 15px;
}
.search-area {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
.search-content {
  flex: 1;
  padding-right: 15px;
}
.search-buttons {
  width: 80px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding-top: 5px;
}
.mb10 {
  margin-bottom: 10px;
}
.mt8 {
  margin-top: 8px;
}
.mr15 {
  margin-right: 15px;
}
.mr5 {
  margin-right: 5px;
}
.page_style {
  margin-top: 15px;
  margin-bottom: 15px;
  text-align: right;
  width: 100%;
}
.flex-div {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}
.level-option-img {
  width: 20px;
  height: 20px;
  vertical-align: middle;
  margin-bottom: 3px;
}
.head-title {
  width: 100%;
  height: 35px;
  font-size: 16px;
  line-height: 30px;
}
.clearfix:after {
  content: "";
  display: table;
  clear: both;
}
.table-container {
  width: 100%;
  overflow-x: auto;
  margin-bottom: 15px;
  flex: 1;
  position: relative;
}
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.table-title {
  font-size: 16px;
  font-weight: bold;
}
.table-actions {
  display: flex;
  gap: 10px;
}
.empty-tips {
  text-align: center;
  padding: 20px 0;
  color: #999;
}
</style>
