<template>
  <div class="contradiction-div">
    <div class="head-title">重点领域</div>
    <div class="search-div">
      <div style="width:90%;float: left;">
        <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>
        </Row>
        <Row class="">
          <Alert type="warning">
            依据系统数据统计，各类矛盾纠纷事件数量与上一年同期相比增长50%以上、与上一月相比增长30%以上，符合上述条件之一的，确定为“重点领域”，系统自动触发预警
          </Alert>
        </Row>
      </div>
      <div style="width:10%;float: left;">
        <Row>
          <Col span="12">
            <Button type="primary" @click="searchData">搜索</Button>
          </Col>
          <Col span="12">
            <Button type="primary" @click="revert">重置</Button>
          </Col>
        </Row>
      </div>
    </div>
    <div style="margin-top: 150px">
      <Tabs value="0" @on-click="tabChange">
        <!--        <TabPane label="按年统计" name="1"></TabPane>-->
        <TabPane label="按月统计" name="0"></TabPane>
      </Tabs>
    </div>
    <Table stripe :columns="columns" :data="dataList">
      <template slot-scope="{row, index}" slot="growth_rate">
        <div>{{ row.growth_rate }}%</div>
      </template>
      <template slot-scope="{row, index}" slot="type">
        <div v-if="row.type === '2'">已解除</div>
        <div v-if="row.type === '1'">未解除</div>
      </template>
      <template slot-scope="{row, action}" slot="action">
        <Button type="primary" class="mr5" @click="getInfo(row)">详情</Button>
        <!--        <Button type="primary" v-if="row.type === '1'" @click="liftRisk(row)">解除风险</Button>-->
      </template>
    </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%">
              <Option v-for="item in dictData.list1" :value="JSON.stringify(item)" :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)"
                    @on-clear="clearArea('city')" :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)"
                    @on-clear="clearArea('area')" :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)"
                    @on-clear="clearArea('street')" :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" @on-clear="clearArea('community')" 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-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,
  getFocusAreaPage,
  getAreaEventaPageList
} 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: {},
      data_type: '0',
      searchInfo1: {},
      monthFocusList: [],
      columns1: [
        { type: 'index', title: '序号', align: 'center', width: '80px' },
        { title: '风险等级', slot: 'riskLevel', align: 'center' },
        { title: '纠纷大类', key: 'eventCategoryId', align: 'center' },
        { title: '纠纷小类', key: 'eventTypeId', align: 'center' },
        { title: '纠纷发生地', key: 'address', align: 'center' },
        { title: '纠纷描述', key: 'disputeDescription', align: 'center' },
        { title: '纠纷发生时间', key: 'occurrenceTime', align: 'center' },
        // { title: '是否化解', slot: 'isResolve', align: 'center' },
        { title: '操作', fixed: 'right', slot: 'action', align: 'center' }
      ],
      columns: [],
      columns_year: [
        { type: 'index', title: '序号', align: 'center', width: '80px' },
        { title: '纠纷大类', key: 'event_category_id_dict', align: 'center' },
        { title: '纠纷发生地', key: 'area_code_dict', align: 'center' },
        { title: '统计年份', key: 'year', align: 'center' },
        { title: '当期发生数量（年初以来）', key: 'event_count', align: 'center' },
        { title: '去年同比', slot: 'growth_rate', align: 'center' },
        // { title: '风险状态', slot: 'type', align: 'center' },
        { title: '操作', slot: 'action', align: 'center' }
      ],
      columns_month: [
        { type: 'index', title: '序号', align: 'center', width: '80px' },
        { title: '纠纷大类', key: 'event_category_id_dict', align: 'center' },
        { title: '纠纷发生地', key: 'area_code_dict', align: 'center' },
        { title: '统计年份', key: 'year', align: 'center' },
        { title: '统计月份', key: 'month', align: 'center' },
        { title: '当期发生数量', key: 'event_count', align: 'center' },
        { title: '上月环比', slot: 'growth_rate', align: 'center' },
        // { title: '风险状态', slot: 'type', align: 'center' },
        { title: '操作', slot: 'action', align: 'center' }
      ],
      dataList: [],
      infoList: {},
      params: {
        pageNo: 1,
        pageSize: 10,
        totalRecord: 0
      },
      params1: {
        pageNo: 1,
        pageSize: 10,
        totalRecord: 0,
        event_category_id: ''
      },
      id: ''
    }
  },
  mounted () {
    this.columns = this.columns_year
    this.getDictList('1')
    this.getCityData('1')
    this.getList()
    this.tabChange('0')
  },
  methods: {
    revert () {
      this.searchInfo.event_category_id = ''
      this.searchInfo.month_s = ''
      this.searchInfo.month_e = ''
      this.params.pageNo = 1
      this.params.pageSize = 10
      this.searchData()
    },
    tabChange (e) {
      this.data_type = e
      if (e === '1') {
        this.columns = this.columns_year
      } else if (e === '0') {
        this.columns = this.columns_month
      }
      this.getList()
      console.log(e, 'e')
    },
    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) { // 清空纠纷大类
      console.log(res, 'dddddd')
      this.$nextTick(() => {
        // clearable后会直接把searchInfo里的该字段删除掉
        this.$set(this.searchInfo1, 'event_category_id', '')
        this.$set(this.searchInfo1, res, res === 'info' ? '{}' : '')
      })
    },
    changeDispute (item) {
      this.searchInfo1.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) {
      // 如果清空了上级选择，需要清空所有下级选择
      if (level > 1 && !parent_id) {
        this.clearAreaData(level)
        return
      }
      this.getCityData(level, parent_id)
    },

    // 清空区域数据
    clearAreaData (level) {
      // 清空当前级别及以下的所有数据列表
      const clearLevels = ['', 'list1', 'list2', 'list3', 'list4']
      for (let i = level; i < clearLevels.length; i++) {
        if (clearLevels[i]) {
          this.areaData[clearLevels[i]] = []
        }
      }

      // 清空对应的选择值
      const clearFields = ['', 'cityId', 'areaId', 'streetId', 'communityId']
      for (let i = level; i < clearFields.length; i++) {
        if (clearFields[i]) {
          this.$set(this.searchInfo1, clearFields[i], '')
          console.log(`清空选择值: ${clearFields[i]}`)
        }
      }
    },

    // 处理清空事件
    clearArea (type) {
      let level = 1
      switch (type) {
        case 'city':
          level = 2
          break
        case 'area':
          level = 3
          break
        case 'street':
          level = 4
          break
        case 'community':
          level = 5
          break
      }
      this.clearAreaData(level)
    },

    // 处理区域选择变化
    handleAreaChange (values) {
      console.log('区域选择变化:', values)
      // 可以在这里添加其他逻辑，比如自动搜索等
    },
    getList (item) {
      if (item) {
        this.params = Object.assign(this.params, item)
      }
      let ms = date2str(new Date())
      this.params.month_s = ms.substring(0, ms.length - 3)
      let me = date2str(new Date())
      this.params.month_e = me.substring(0, me.length - 3)
      this.params.data_type = this.data_type
      getFocusAreaPage(this.params).then(res => {
        if (res.data.errcode === 0) {
          this.dataList = res.data.data.results
          this.params.totalRecord = res.data.data.totalRecord
          return
        }
        this.$Message.error(res.data.errmsg)
      })
    },
    size (pageSize) {
      this.params.pageSize = pageSize
      this.changePageNo()
    },
    changePageNo (pageNo) {
      this.params.pageNo = pageNo
      this.getList(this.params)
    },
    searchData () { // 搜索
      this.getList(this.searchInfo)
    },
    getInfo (item) {
      console.log(item, 'dddd')
      this.infoList = item
      // 重置分页参数
      this.params1.pageNo = 1
      this.params1.pageSize = 10
      this.params1.totalRecord = 0
      this.getInfoList(item.id)
      this.id = item.event_category_id
      this.params1.event_category_id = item.event_category_id
      this.params1.occurrence_date = item.occurrence_date
      this.modal = true
      // this.dictData.list1 = []
      // this.dictData.list2 = []
    },
    getInfoList (id, item) {
      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
      }
      console.log(this.infoList, 'this.infoList')
      this.params1.data_type = this.data_type
      this.params1.eventCategoryId = this.infoList.event_category_id
      this.params1.year = this.infoList.year
      this.params1.month = this.infoList.month
      this.params1.area_code = this.infoList.area_code
      getAreaEventaPageList(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()
    },
    changePageNo1 (pageNo) {
      this.params1.pageNo = pageNo
      this.getInfoList(this.params1)
    },
    searchInfoData () {
      this.params1.pageNo = 1
      this.params1.pageSize = 10
      this.params1.totalRecord = 0
      this.getInfoList(this.id, this.searchInfo1)
    },
    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: '',
          isShowInfo: true, // 控制化解过程显隐
          isInfo: true,
          type: this.type
        }
      })
    }
  },
  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;
}
</style>
