<template>
  <div class="contradiction-div">
    <div class="head-title">{{ pageTitle }}</div>
    <div class="search-div">
      <div style="width:100%;">
        <Row class="mb10">
          <Col span="6">
            <span>纠纷类别：</span>
            <Select v-model="searchInfo.event_category_id" style="width:70%;" clearable>
              <Option v-for="(item, index) in dictData.list1" :value="item.value" :key="index">{{ item.label }}</Option>
            </Select>
          </Col>
          <Col span="6">
            <span>开始月份：</span>
            <DatePicker type="month" v-model="searchInfo.start_time" placeholder="请选择开始月份"></DatePicker>
          </Col>
          <Col span="6">
            <span>结束月份：</span>
            <DatePicker type="month" v-model="searchInfo.end_time" placeholder="请选择结束月份"></DatePicker>
          </Col>
          <Col span="6">
            <Button type="primary" @click="searchData">搜索</Button>
            <Button type="primary" @click="resert" style="margin-left: 10px;">重置</Button>
          </Col>
        </Row>
        <Row class="">
          <Alert v-if="type ==='1'"  type="warning">某一领域矛盾纠纷数量比上一月增长50%以上。</Alert>
          <Alert v-if="type ==='2'"  type="warning">某一领域矛盾纠纷数量比上一月增长30%—50%。</Alert>
        </Row>
      </div>
    </div>
    <vxe-table  :data="dataList"  stripe show-overflow  size="small" resizable align="center" header-align="center">
      <vxe-column title="序号" align="center" type="seq"/>
      <vxe-column title="纠纷大类" align="center"  field="eventCategoryName"/>
      <vxe-column title="统计月份" align="center" field="statisticalTime"/>
      <vxe-column title="上月环比" align="center" field="percentage">
        <template v-slot="{ row }">
          <div>{{row.percentage}}%</div>
        </template>
      </vxe-column>
      <vxe-column title="操作" align="center"  fixed="right" class-name="small-padding fixed-width">
        <template v-slot="{ row }">
          <Button type="primary" class="mr5" @click="getInfo(row)">详情</Button>
        </template>
      </vxe-column>
    </vxe-table>
    <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"/>
    <Modal v-model="modal" width="1000" title="预警详情">
      <div class="search-div">
        <!-- <div style="float: left;"> -->
        <Row class="mb10">
          <Col span="8">
            <span>纠纷大类：</span>
            <Select v-model="searchInfo1.info" @on-clear="clearDispute('info')" @on-change="changeDispute(searchInfo1.info)" :clearable="true" style="width:70%" disabled>
              <Option v-for="item in dictData.list1" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </Col>
          <Col span="8">
            <span>纠纷小类：</span>
            <Select v-model="searchInfo1.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="7">
            <span>统计月份：</span>
            <DatePicker type="date" v-model="searchInfo1.occurrenceDate" placeholder="请选择统计月份"></DatePicker>
          </Col> -->
          <Col span="1">
            <Button type="primary" @click="searchInfoData">搜索</Button>
          </Col>
        </Row>
        <Row class="mb10">
          <Col span="8">
            <span>统计范围：</span>
            <Select v-model="searchInfo1.cityId" @on-change="changeArea('2',searchInfo1.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="5" class="mr5">
            <Select v-model="searchInfo1.areaId" @on-change="changeArea('3',searchInfo1.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="5" class="mr5">
            <Select v-model="searchInfo1.streetId" @on-change="changeArea('4',searchInfo1.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="5">
            <Select v-model="searchInfo1.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>
      </div>
      <Table stripe :columns="columns1" :data="monthFocusList">
        <template slot-scope="{ row, index }" slot="riskLevel">
          <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>
        <template slot="disputeDescription" slot-scope="{ row }">
          <div class="text-limit">{{ row.disputeDescription }}</div>
        </template>
        <template slot="address" slot-scope="{ row }">
          <div class="text-limit">{{ row.address }}</div>
        </template>
        <template slot-scope="{row, index}" slot="isResolve">
          <div v-if="row.isResolve === '1'">已化解</div>
          <div v-if="row.isResolve === '2'">未化解</div>
        </template>
        <template slot-scope="{row, index}" slot="action">
          <Button type="primary" class="mr5" @click="getEventInfo(row)">详情</Button>
        </template>
      </Table>
      <Page class="page_style"  :total="params1.totalRecord" :current="params1.pageNo"
            :page-size="params1.pageSize" @on-change="changePageNo1" show-total  show-sizer @on-page-size-change="size1"/>
    </Modal>
  </div>
</template>
<script>
import {
  selectDictList,
  selectCityList,
  updateFocusAreasType,
  selectWarningAreaPageList,
  fousAreaWarringPageList,
  fousAreaWarringPageHistoryList, selectWarningAreaPageHistoryList
} from '@/api/contradiction.js'
import { date2str } from '@/api/eventlist.js'
export default {
  name: 'register',
  data () {
    return {
      modal: false,
      dictData: {
        list1: [],
        list2: []
      },
      areaData: {
        list1: [],
        list2: [],
        list3: [],
        list4: []
      },
      user_types: [],
      searchInfo: {},
      searchInfo1: {},
      monthFocusList: [],
      columns1: [
        { type: 'index', title: '序号', align: 'center', width: '80px' },
        { title: '风险等级', slot: 'riskLevel', align: 'center' },
        { title: '纠纷大类', key: 'eventCategoryName', align: 'center' },
        { title: '纠纷小类', key: 'eventTypeName', align: 'center' },
        { title: '纠纷发生地', slot: 'address', align: 'center' },
        { title: '纠纷描述', slot: 'disputeDescription', align: 'center' },
        { title: '纠纷发生时间',
          key: 'occurrenceTime',
          align: 'center',
          render: (h, params) => {
            const time = params.row.occurrenceTime
            if (!time) return h('span', '-')
            const date = new Date(time)
            if (isNaN(date.getTime())) return h('span', time)
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            const hours = String(date.getHours()).padStart(2, '0')
            const minutes = String(date.getMinutes()).padStart(2, '0')
            return h('span', `${year}-${month}-${day} ${hours}:${minutes}`)
          }
        },
        { title: '是否完结', slot: 'isResolve', align: 'center' },
        { title: '操作', fixed: 'right', slot: 'action', align: 'center' }
      ],
      columns: [
        { type: 'index', title: '序号', align: 'center', width: '80px' },
        { title: '纠纷大类', key: 'event_category_name', align: 'center' },
        { title: '统计月份', key: 'occurrence_date', align: 'center' },
        { title: '当期发生数量（年初以来）', key: 'year_num', align: 'center' },
        { title: '去年同比', slot: 'on_year', align: 'center' },
        { title: '上月环比', slot: 'link_relative_ratio', align: 'center' },
        { title: '风险状态', slot: 'type', align: 'center' },
        { title: '操作', slot: 'action', align: 'center' }
      ],
      dataList: [],
      params: {
        pageNo: 1,
        pageSize: 10,
        totalRecord: 0
      },
      type: '',
      params1: {
        pageNo: 1,
        pageSize: 10,
        totalRecord: 0,
        event_category_id: ''
      },
      id: '',
      list_url: '',
      pageTitle: '',
      fid: ''
    }
  },
  beforeDestroy () {
    this.list_url = ''
    this.searchInfo = {}
    this.params.pageNo = 1
    this.params.pageSize = 10
  },
  mounted () {
    // 重点事 type:'0'   一级预警 type :'1'   二级预警 type :'2'   三级预警 type :'3'   重点事触发历史 type: '4'
    this.type = this.$route.query.type
    // 新增 搜索条件默认时间 当前年1-12月
    this.searchInfo.start_time = new Date().getFullYear() + '-01'
    this.searchInfo.end_time = new Date().getFullYear() + '-12'
    const { history, cityId, areaId } = this.$route.query
    // 重点领域预警历史
    if (history) {
      this.list_url = selectWarningAreaPageHistoryList
      this.pageTitle = '重点领域预警历史'
    } else {
      this.list_url = selectWarningAreaPageList
      this.pageTitle = '重点领域预警'
    }
    if (cityId) {
      this.searchInfo.cityId = cityId
    }
    if (areaId) {
      this.searchInfo.areaId = areaId
    }
    this.getDictList('1')
    this.getCityData('1')
    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.searchInfo1, 'event_category_id', '')
        this.$set(this.searchInfo1, res, res === 'info' ? '{}' : '')
      })
    },
    changeDispute (val) {
      const id = this.dictData.list1.find(item => item.value === val).id
      this.getDictList('2', 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) {
      // 当选择被清空时，parent_id 为空，避免请求接口并级联清空下级
      if (!parent_id) {
        // 级联清空从当前层级的下一级开始
        const listKeys = ['', 'list1', 'list2', 'list3', 'list4']
        const modelKeys = ['', 'cityId', 'areaId', 'streetId', 'communityId']
        const start = Math.min(Number(level), listKeys.length - 1) + 0
        for (let i = start; i < listKeys.length; i++) {
          if (listKeys[i]) this.areaData[listKeys[i]] = []
          if (modelKeys[i]) this.$set(this.searchInfo1, modelKeys[i], '')
        }
        return
      }
      this.getCityData(level, parent_id)
    },
    getList (item) {
      // if (item) {
      //   this.params = Object.assign(this.params, item)
      //   if (this.params.start_time) {
      //     this.params.start_time = date2str(this.params.start_time)
      //   }
      //   if (this.params.end_time) {
      //     this.params.end_time = date2str(this.params.end_time)
      //   }
      // }
      // 检查开始月份和结束月份的有效性
      if (this.searchInfo.start_time && this.searchInfo.end_time) {
        // 对于月份选择器，我们只需要比较年和月
        const startDate = new Date(this.searchInfo.start_time)
        const endDate = new Date(this.searchInfo.end_time)
        const startYearMonth = startDate.getFullYear() * 12 + startDate.getMonth()
        const endYearMonth = endDate.getFullYear() * 12 + endDate.getMonth()
        if (endYearMonth < startYearMonth) {
          this.$Message.error('结束月份不能早于开始月份')
          return
        }
      }
      let params = {
        pageNo: this.params.pageNo,
        pageSize: this.params.pageSize,
        eventCategoryId: this.searchInfo.event_category_id,
        alarmLevel: this.type,
        occurrenceStartDate: this.searchInfo.start_time ? this.formatDate(this.searchInfo.start_time) : '',
        occurrenceEndDate: this.searchInfo.end_time ? this.formatDate(this.searchInfo.end_time) : '',
        areaId: this.$route.query.areaId,
        cityId: this.$route.query.cityId
      }
      this.list_url(params).then(res => {
        if (res.data.errcode === 0) {
          if (res.data.data.totalRecord <= this.params.pageSize && res.data.data.pageNo > 1) {
            this.params.pageNo = 1
            this.getList()
          } else {
            this.dataList = res.data.data.results
            this.params.totalRecord = res.data.data.totalRecord
          }
          return
        }
        this.$Message.error(res.data.errmsg)
      }).catch(err => {
        console.error('获取数据失败:', err)
        this.$Message.error('获取数据失败')
      })
    },
    size (pageSize) {
      this.params.pageSize = pageSize
      this.searchData()
    },
    changePageNo (pageNo) {
      this.params.pageNo = pageNo
      this.getList()
    },
    searchData () { // 搜索
      this.params.pageNo = 1
      // 检查开始月份和结束月份的有效性
      if (this.searchInfo.start_time && this.searchInfo.end_time) {
        // 对于月份选择器，我们只需要比较年和月
        const startDate = new Date(this.searchInfo.start_time)
        const endDate = new Date(this.searchInfo.end_time)
        const startYearMonth = startDate.getFullYear() * 12 + startDate.getMonth()
        const endYearMonth = endDate.getFullYear() * 12 + endDate.getMonth()
        if (endYearMonth < startYearMonth) {
          this.$Message.error('结束月份不能早于开始月份')
          return
        }
      }
      const { cityId, areaId } = this.$route.query
      if (cityId) {
        this.searchInfo.cityId = cityId
      }
      if (areaId) {
        this.searchInfo.areaId = areaId
      }
      this.getList(this.searchInfo)
    },
    resert () {
      this.searchInfo = {}
      this.params.pageNo = 1
      this.searchInfo.start_time = new Date().getFullYear() + '-01'
      this.searchInfo.end_time = new Date().getFullYear() + '-12'
      this.searchData()
    },
    getInfo (item) {
      if (item.fid) {
        this.fid = item.fid
      }
      console.log(item, 'dddd')
      this.id = item.event_category_id
      this.params1.event_category_id = item.eventCategoryId
      this.searchInfo1.info = item.eventCategoryId
      this.changeDispute(this.searchInfo1.info)
      this.params1.occurrence_date = item.occurrence_date
      this.modal = true
      this.getInfoList(item.id, null, item.statisticalTime)
      // this.dictData.list1 = []
      // this.dictData.list2 = []
    },
    getInfoList (id, item, month) {
      if (item) {
        this.params1 = Object.assign(this.params1, item)
        if (this.params1.occurrenceDate) {
          this.params1.occurrenceDate = date2str(this.params1.occurrenceDate)
        }
      } else {
        this.params1 = this.params1
      }

      // 添加month参数
      if (month) {
        this.params1.month = month
      }
      // 从 Vuex 获取 company_id 和 company_grade 并添加到 searchInfo1
      this.params1.company_id = this.serverUserInfo.company_id
      this.params1.company_grade = this.serverUserInfo.company_grade
      const { history } = this.$route.query
      let fetch = null
      if (history) {
        this.params1.fid = this.fid
        fetch = fousAreaWarringPageHistoryList
      } else {
        fetch = fousAreaWarringPageList
      }
      fetch(this.params1).then(res => {
        if (res.data.errcode === 0) {
          this.monthFocusList = res.data.data.results
          this.params1.totalRecord = res.data.data.totalRecord
          return
        }
        this.$Message.error(res.data.errmsg)
      })
    },
    size1 (pageSize) {
      this.params1.pageSize = pageSize
      this.changePageNo1(1) // 重置到第一页，month会在changePageNo1中传递
    },
    changePageNo1 (pageNo) {
      this.params1.pageNo = pageNo
      // 确保翻页时month参数也能传递
      const month = this.searchInfo1.occurrenceDate ? this.formatDate(this.searchInfo1.occurrenceDate) : this.params1.month
      this.getInfoList(this.id, null, month)
    },
    searchInfoData () {
      // 检查统计月份是否有效
      if (this.searchInfo1.occurrenceDate) {
        // 这里只有一个日期，不需要比较范围
        if (!(this.searchInfo1.occurrenceDate instanceof Date) && isNaN(new Date(this.searchInfo1.occurrenceDate).getTime())) {
          this.$Message.error('请选择有效的统计月份')
          return
        }
      }

      this.params1.pageNo = 1
      this.params1.pageSize = 10
      this.params1.totalRecord = 0

      // 从搜索条件中获取月份
      const month = this.searchInfo1.occurrenceDate ? this.formatDate(this.searchInfo1.occurrenceDate) : null

      this.getInfoList(this.id, this.searchInfo1, month)
    },
    liftRisk (item) { // 解除风险
      if (confirm('确定解除风险吗？')) {
        updateFocusAreasType({ id: item.id, type: '2' }).then(res => {
          if (res.data.errcode === 0) {
            this.$Message.success('已成功解除风险')
            this.getList()
            return
          }
          this.$Message.error(res.data.errmsg)
        })
      }
    },
    getEventInfo (row) { // 详情页矛盾列表看详情
      this.$router.push({
        name: 'contradictionRegisterAdd',
        params: {
          what: 'edit',
          id: row.id,
          level: '',
          type: '5'
          // isShowInfo: true, // 控制化解过程显隐
          // isInfo: true
        }
      })
    },
    formatDate (date) {
      if (!date) return ''
      // 如果是Date对象，只保留年月部分，格式为yyyy-MM
      if (date instanceof Date) {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        return `${year}-${month}`
      }
      // 如果已经是字符串，确保只保留年月部分
      if (typeof date === 'string') {
        // 尝试将字符串转换为日期对象并格式化
        try {
          const dateObj = new Date(date)
          if (!isNaN(dateObj.getTime())) {
            const year = dateObj.getFullYear()
            const month = String(dateObj.getMonth() + 1).padStart(2, '0')
            return `${year}-${month}`
          }
        } catch (e) {
          console.error('日期格式转换错误:', e)
        }
        // 如果转换失败或者不需要转换，返回原字符串
        return date
      }
      return date
    }
  },
  computed: {
    serverUserInfo () {
      return this.$store.state.user.severUserInfo
    }
  }
}
</script>
<style scoped lang="less">
.contradiction-div {
  padding: 10px;
}
.search-div {
  //float: left;
  width: 100%;
  padding: 15px 30px 15px 15px;
  // min-height: 200px;
  border: 1px solid skyblue;
  border-radius: 5px;;
  background-color: #f6fdfd;
  margin-bottom: 15px;
}
.mb10 {
  margin-bottom: 10px;
}
.mt8 {
  margin-top: 8px;
}
.mr15 {
  margin-right: 15px;
}
.mr5 {
  margin-right: 5px;
}
.page_style {
  margin-top: 10px;
  text-align: right;
}
.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;
}
.text-limit {
  /* 限制最大高度为两行文本高度（根据行高计算） */
  max-height: calc(2 * 1.5em); /* 假设行高为 1.5em，可根据实际调整 */
  /* 隐藏超出容器的内容 */
  overflow: hidden;
  /* 强制文本在一行内显示（配合下面属性实现多行） */
  white-space: normal;
  /* 文本溢出时显示省略号 */
  text-overflow: ellipsis;
  /* 关键属性：限制最多显示的行数 */
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 这里设置为 2 行 */
  -webkit-box-orient: vertical;
}
</style>
