<template>
  <div class="g-main">
    <div>
      <div class="m-search">
        <el-form :inline="true" :model="formData" ref="ref_searchform" :label-width="'100px'">
          <el-form-item label="统计时间">
            <el-date-picker v-model.trim="formData.queryDateStart" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="开始时间" style="width: 202px" clearable>
            </el-date-picker>
            至
            <el-date-picker v-model.trim="formData.queryDateEnd" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="结束时间" style="width: 202px" clearable>
            </el-date-picker>
          </el-form-item>
          <el-button style="margin-left: 30px" size="small" type="primary " @click="handleSearch">查询</el-button>
          <el-button style="margin-left: 10px" is-plain class="diy-button--white el-button--default" size="small"
            @click="exportReport">导出</el-button>
        </el-form>

      </div>
      <div class="m-table">
        <div style="display: flex;justify-content: space-between;flex-direction:row;">
          <h1 style="font-size: 24px; font-weight: bold;"> 事件统计 </h1>
        </div>
        <div class="dashboard">
        <div class="card">
            <div class="card-icon ">
              <img style="width: 40px;height: 40px;" src="./img/eventSumNum.png">
            </div>
            <div class="card-content">
                <p class="card-title">{{analysisList.total}}</p>
                <p class="card-text">事件总数</p>
            </div>
        </div>
        <div class="card1">
          <div class="card-icon ">
              <img style="width: 40px;height: 40px;" src="./img/eventNum.png">
            </div>
            <div class="card-content1">
              <div  style="display: flex;flex-direction: column;justify-content: center;">
                <div style="display: flex;flex-direction: row;">
                  <p class="card-title">{{analysisList.resolveTotal}}</p>
                  <span class="percentage">{{analysisList.resolveRate}}%</span>
                </div>
                <p class="card-text">已办结事件数</p>
              </div>
              <div  style="padding-left: 20px; display: flex;flex-direction: column;justify-content: center;">
                <div style="display: flex;flex-direction: row;">
                  <p class="card-title">{{analysisList.unresolveTotal}}</p>
                  <span class="percentage">{{analysisList.unresolveRate}}%</span>
                </div>
                <p class="card-text">未办结事件数</p>
              </div>

            </div>
        </div>
        <div class="card">
          <div class="card-icon ">
              <img style="width: 40px;height: 40px;" src="./img/perp.png">
            </div>
            <div class="card-content">
                <p class="card-title">{{analysisList.illegalConnectTotal}} <span class="percentage">{{analysisList.illegalConnectRate}}%</span></p>
                <p class="card-text">联系当事人超期事件数</p>
            </div>
        </div>
        <div class="card">
          <div class="card-icon ">
              <img style="width: 40px;height: 40px;" src="./img/overdue.png">
            </div>
            <div class="card-content">
                <p class="card-title">{{analysisList.illegalResolveTotal}} <span class="percentage">{{analysisList.illegalResolveRate}}%</span></p>
                <p class="card-text">办理超期事件数</p>
            </div>
        </div>
    </div>
        <div style="display: flex;justify-content: space-between;flex-direction:row;">
          <h1 style="font-size: 24px; font-weight: bold;"> 事件类型统计 </h1>
        </div>
        <!-- <table >
      <thead>
        <tr>
          <th>一级分类</th>
          <th>二级分类</th>
          <th>三级分类</th>
          <th>四级分类</th>
          <th>事件数量</th>
          <th>同级占比</th>
        </tr>
        <tr v-for="item in tableList" :key="item.id" :item="item" :level=1>
          <td v-if="level === 1" :rowspan="calculateRowspan(item)">{{ item.categoryName }}</td>
          <td v-else></td>
          <td v-if="level === 2" :rowspan="calculateRowspan(item)">{{ item.categoryName }}</td>
          <td v-else></td>
          <td v-if="level === 3" :rowspan="calculateRowspan(item)">{{ item.categoryName }}</td>
         <td v-else></td>
         <td v-if="level === 4">{{ item.categoryName }}</td>
        <td v-if="level === 4">{{ item.eventCount }}</td>
        <td v-if="level === 4">{{ item.proportion }}</td>
        <td v-else></td>
        <td >{{ item.eventCount }}</td>
        <td >{{item.proportion}}</td>
        </tr>
        <TableRow v-for="item in tableList" :key="item.id" :item="item" :level="1" />
      </thead>

    </table> -->
        <el-table
        :data="tableList"
        style="width: 100%;margin-bottom: 20px;"
        row-key="id"
        border
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column
          prop="level1"
          label="一级分类"
          sortable
          width="150">
        </el-table-column>
        <el-table-column
          prop="level2"
          label="二级分类"
          sortable
          width="150">
        </el-table-column>
        <el-table-column
          prop="level3"
          label="三级分类"
          sortable
          width="150">
        </el-table-column>     
        <el-table-column
          prop="level4"
          label="四级分类"
          sortable
          width="150">
        </el-table-column>
        <el-table-column
          prop="eventCount"
          label="事件数量"
          sortable
          width="150">
        </el-table-column>
        <el-table-column
          prop="proportion"
          label="同级占比"
          sortable
         >
         <template slot-scope="scope">
        {{ scope.row.proportion }}%
      </template>

        </el-table-column>
      </el-table>

        <div style="display: flex;justify-content: space-between;flex-direction:row; height:500px">
          <div style="display: flex;justify-content: space-between;flex-direction:column;">
            <h1 style="font-size: 24px; font-weight: bold;"> 部门科室工单量统计 </h1>
            <el-table :data="departmentList"  height="250" border class="m-table-item" style="width: 100%">
          <!-- <el-table-column label="序号" fixed="left" type="index" align="center" width="50" /> -->
          <!-- <el-table-column prop="address" align="center" label="地点" :show-overflow-tooltip="true"></el-table-column> -->
          <el-table-column prop="assignOrgName" align="center" label="部门科室"
            :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="total" align="center" label="事件数" :show-overflow-tooltip="true">
            <!-- <template slot-scope="{row}">
              <el-button style="width: 100%" type="text" @click="clickAddressData(row)">{{row.amount}}</el-button>
            </template> -->
          </el-table-column>
          <el-table-column prop="totalRate" align="center" label="占比" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="unresolveRate" align="center" label="未办结数" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="illegalConnectRate" align="center" label="联系当事人超期数" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="cillegalResolveRateontent" align="center" label="办理超期数" :show-overflow-tooltip="true"></el-table-column>
        </el-table>
        </div>
          
        <div style="display: flex;justify-content: space-between;flex-direction:column;">
                <h1 style="font-size: 24px; font-weight: bold; margin-right: 600px;"> 社区工单量统计 </h1>
          <el-table :data="communityList"   height="300" border class="m-table-item" style="width: 100%">
          <!-- <el-table-column label="序号" fixed="left" type="index" align="center" width="50" /> -->
          <!-- <el-table-column prop="address" align="center" label="地点" :show-overflow-tooltip="true"></el-table-column> -->
          <el-table-column prop="assignOrgName" align="center" label="社区"
            :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="total" align="center" label="事件数" :show-overflow-tooltip="true">
            <!-- <template slot-scope="{row}">
              <el-button style="width: 100%" type="text" @click="clickAddressData(row)">{{row.amount}}</el-button>
            </template> -->
          </el-table-column>
          <el-table-column prop="totalRate" align="center" label="占比" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="unresolveRate" align="center" label="未办结数" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="illegalConnectRate" align="center" label="联系当事人超期数" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="cillegalResolveRateontent" align="center" label="办理超期数" :show-overflow-tooltip="true"></el-table-column>
        </el-table>
        </div>
       
        </div>


        <div>
          <h1 style="font-size: 24px; font-weight: bold;"> 存在主要问题 </h1>
          <h2 style="font-size: 20px; font-weight: bold;"> ➤ 同地点同类型事件重复投诉 </h2>
        </div>

        <el-table :data="addressData" border class="m-table-item" style="width: 100%">
          <el-table-column label="序号" fixed="left" type="index" align="center" width="50" />
          <el-table-column prop="address" align="center" label="地点" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="categoryName" align="center" label="类型"
            :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="amount" align="center" label="投诉次数" :show-overflow-tooltip="true">
            <template slot-scope="{row}">
              <el-button style="width: 100%" type="text" @click="clickAddressData(row)">{{row.amount}}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="content" align="center" label="投诉内容" :show-overflow-tooltip="true"></el-table-column>
        </el-table>

        <el-button @click="handelMoreAddressData" type="text" size="small">查看更多</el-button>

        <div>
          <h2 style="font-size: 20px; font-weight: bold;"> ➤ 同一人员重复投诉</h2>
        </div>
      <el-table>
          <el-table-column label="序号" fixed="left" type="index" align="center" width="50" />
          <el-table-column prop="mobile" align="center" label="联系方式" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-button v-if="scope.row.resiId !== null && scope.row.resiId !== ''" @click="handleLook(scope.row)"
                type="text" size="small">
                {{ scope.row.mobile }}
              </el-button>
              <span v-else>
                {{ scope.row.mobile }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="amount" align="center" label="投诉次数" :show-overflow-tooltip="true">
            <template slot-scope="{row}">
              <el-button style="width: 100%" type="text" @click="clickMobileData(row)">{{row.amount}}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="content" align="center" label="投诉内容" :show-overflow-tooltip="true"></el-table-column>
        </el-table>

        <el-button @click="handelMoreMobileData" type="text" size="small">查看更多</el-button>

        <div>
          <h2 style="font-size: 20px; font-weight: bold;"> ➤ 同一区域不同类型投诉</h2>
        </div>

        <el-table :data="addressMobileData" border class="m-table-item" style="width: 100%"
          :span-method="objectSpanMethod">
          <el-table-column label="序号" fixed="left" type="index" align="center" width="50" />
          <el-table-column prop="address" align="center" label="地点" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="categoryName" align="center" label="类型"
            :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="amount" align="center" label="投诉次数" :show-overflow-tooltip="true">
            <template slot-scope="{row}">
              <el-button style="width: 100%" type="text" @click="clickAddressMobileData(row)">{{row.amount}}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="content" align="center" label="投诉内容" :show-overflow-tooltip="true"></el-table-column>
        </el-table>

        <el-button @click="handelMoreAddressMobileData" type="text" size="small">查看更多</el-button>

        <div>
          <h2 style="font-size: 20px; font-weight: bold;"> ➤ 同一工单追加内容投诉</h2>
        </div>

        <el-table :data="addComplainData" border class="m-table-item" style="width: 100%">
          <el-table-column label="序号" fixed="left" type="index" align="center" width="50" />
          <el-table-column prop="categoryName" align="center" label="类型"
            :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="awoNum" align="center" label="追加内容次数" :show-overflow-tooltip="true">
            <template slot-scope="{row}">
              <el-button style="width: 100%" type="text" @click="clickAwoFlagData(row)">{{row.awoNum}}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="content" align="center" label="投诉内容" :show-overflow-tooltip="true"></el-table-column>
        </el-table>

        <el-button @click="handelMoreAddComplainData" type="text" size="small">查看更多</el-button>

      </div>


    </div>

    <el-dialog v-if="showFormList" :visible.sync="showFormList" :close-on-click-modal="false"
      :close-on-press-escape="false" title="12345问题列表" :modal-append-to-body="false" width="60%" top="5vh"
      class="dialog-h" @closed="showFormList = false">
      <form-list ref="ref_form_list" @handleClose="handleClose" :recId="recId" :communityId="communityId"
        :departId="departId" :address="address" :mobile="mobile" :awo_flag="awo_flag"
        @handelClickDetail="handelClickDetail"></form-list>
      <el-dialog width="60%" class="dialog-h" title="12345事件详情" :close-on-click-modal="false" v-if="showFormDetail"
        :visible.sync="showFormDetail" append-to-body>
        <event-info ref="eleEditForm" :pageType="pageType" :eventId="eventId" :eventDetailData="eventDetailData"
          @handleClose="handleClose" @handleOk="handleOk" @dialogOk="handleEditSuccess" />
      </el-dialog>
    </el-dialog>

    <el-dialog v-if="showAreaSameEventList" :visible.sync="showAreaSameEventList" :close-on-click-modal="false"
      :close-on-press-escape="false" title="同地点同类型事件重复投诉" :modal-append-to-body="false" width="60%" top="5vh"
      class="dialog-h" @closed="showAreaSameEventList = false">
      <area-same-list ref="ref_area_same_list" @handleClose="handleClose"
        @clickAddressData="clickAddressData"></area-same-list>
    </el-dialog>

    <el-dialog v-if="showMobileEventList" :visible.sync="showMobileEventList" :close-on-click-modal="false"
      :close-on-press-escape="false" title="同一人员重复投诉" :modal-append-to-body="false" width="60%" top="5vh"
      class="dialog-h" @closed="showMobileEventList = false">
      <mobile-list ref="ref_mobile_list" @handleClose="handleClose" @clickMobileData="clickMobileData"></mobile-list>
    </el-dialog>

    <el-dialog v-if="showAreaNoSameEventList" :visible.sync="showAreaNoSameEventList" :close-on-click-modal="false"
      :close-on-press-escape="false" title="同一区域不同类型投诉" :modal-append-to-body="false" width="60%" top="5vh"
      class="dialog-h" @closed="showAreaNoSameEventList = false">
      <area-no-same-list ref="ref_area_no_same_list" @handleClose="handleClose"
        @clickAddressMobileData="clickAddressMobileData"></area-no-same-list>
    </el-dialog>

    <el-dialog v-if="showAddEventList" :visible.sync="showAddEventList" :close-on-click-modal="false"
      :close-on-press-escape="false" title="同一工单追加内容投诉" :modal-append-to-body="false" width="60%" top="5vh"
      class="dialog-h" @closed="showAddEventList = false">
      <add-complain-list ref="ref_area_no_same_list" @clickAwoFlagData="clickAwoFlagData"></add-complain-list>
    </el-dialog>
    <!-- <awoList ref="awoList" /> -->
  </div>
</template>
<script>
import { requestPost, requestGet } from "@/js/dai/request";
import nextTick from "dai-js/tools/nextTick";
import { mapGetters } from "vuex";
import axios from "axios";
import * as echarts from "echarts";
import util from "@js/util.js";
import TableRow from './TableRow.vue';
export default {
  components: {TableRow},
  data() {
      return {
        starttime:"",
        endtime:"",
        level:1,
        tableList:[],
        communityList:[],
        departmentList:[],
          searchH: 20,
          formData: {
            queryDateStart: "",
            queryDateEnd: "",
          },
        
          agencyLevel:'',

          orgData: {
            id: "",
            level: "agency",
          },
          analysisList:{},

          // 内容字段
          report:{
            streetName:"",
            overallOperation:"",
            geoStatis:"",
            departHotline:"",
            hotDemand:"",
          },

          addressData:[],
          mobileData:[],
          addressMobileData:[],
          addComplainData:[],

          eventCategorys:[],

          categoryPie: {},
          communityChart: {},
          departChart: {},
          hotlineChart: {},

          categoryCountShow:false,
          communityCountShow:false,
          departCountShow:false,
          subCategoryCountShow:false,

          showFormList: false,
          showFormDetail: false,
          showAreaSameEventList: false,
          showMobileEventList: false,
          showAreaNoSameEventList: false,
          showAddEventList: false,

          recId: "",
          departId:"",
          communityId:"",

          eventId: "",
          eventDetailData: {},
          pageType: "info",

          mergeObj: {},
          mergeArr: ['address'],




          categoryPieOption:{
            tooltip: {
              trigger: 'item'
            },
            legend: {
              type: 'scroll',
              bottom: 0,
            },
            series: [
              {
                name: '数量',
                type: 'pie',
                radius: '80%',
                data: [

                ],
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          },

          communityOption : {
            color: ['#5470C6', '#91CC75'],
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'cross'
              }
            },
            grid: {
              right: '20%'
            },
            toolbox: {
              feature: {
                dataView: { show: true, readOnly: false },
                restore: { show: true },
                saveAsImage: { show: true }
              }
            },
            legend: {
              data: ['数量', '占比']
            },
            xAxis: [
              {
                type: 'category',
                axisTick: {
                  alignWithLabel: true
                },
                data: [],
              }
            ],
            yAxis: [
              {
                type: 'value',
                name: '数量',
                position: 'right',
                alignTicks: true,
                axisLine: {
                  show: true,
                  lineStyle: {
                    color: '#91CC75'
                  }
                },
                axisLabel: {
                  formatter: '{value} 件'
                }
              },
              {
                type: 'value',
                name: '占比',
                position: 'left',
                alignTicks: true,
                axisLine: {
                  show: true,
                  lineStyle: {
                    color: '#5470C6'
                  }
                },
                axisLabel: {
                  formatter: '{value} %'
                }
              }
            ],
            series: [
              {
                name: '数量',
                type: 'bar',
                barWidth: 36, // 设置柱子宽度
                data: [

                ]
              },
              {
                name: '占比',
                type: 'line',
                yAxisIndex: 1,
                data: [

                ]
              }
            ]
          },

          departOption : {
            color: ['#5470C6', '#91CC75'],
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'cross'
              }
            },
            grid: {
              right: '20%'
            },
            toolbox: {
              feature: {
                dataView: { show: true, readOnly: false },
                restore: { show: true },
                saveAsImage: { show: true }
              }
            },
            legend: {
              data: ['数量', '占比']
            },
            xAxis: [
              {
                type: 'category',
                axisTick: {
                  alignWithLabel: true
                },
                data: [],
              }
            ],
            yAxis: [
              {
                type: 'value',
                name: '占比',
                position: 'right',
                alignTicks: true,
                axisLine: {
                  show: true,
                  lineStyle: {
                    color: '#5470C6'
                  }
                },
                axisLabel: {
                  formatter: '{value} %'
                }
              },
              {
                type: 'value',
                name: '数量',
                position: 'left',
                alignTicks: true,
                axisLine: {
                  show: true,
                  lineStyle: {
                    color: '#00264D'
                  }
                },
                axisLabel: {
                  formatter: '{value} 件'
                }
              }
            ],
            series: [
              {
                name: '数量',
                type: 'bar',
                barWidth: 36, // 设置柱子宽度
                itemStyle: {
                    normal: {
                        // 定制显示（按顺序）
                        color: function(params) {
                            var colorList = ['#00BFFF', '#800080', '#008080', '#FF8C00', '#FF3333', '#6600CC', '#00FF00', '#4682B4', '#282828', '#FF4500'];
                            return colorList[params.dataIndex]
                        }
                    },
                },
                data: [

                ]
              },
              {
                name: '占比',
                type: 'line',
                yAxisIndex: 1,
                data: [

                ]
              }
            ]
          },

          hotlineChartOption: {
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['工单数量'],
                    bottom: '10%',
                    icon: 'rect',
                    itemWidth: 20,
                    itemHeight: 5,
                    itemGap: 20,
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '25%',
                    containLabel: true
                },
                toolbox: {},


                xAxis: {
                    type: 'category',
                    boundaryGap: true,
                    data: [],
                },
                yAxis: {
                    type: 'value',
                    name: '单位(个)',
                    min: 0,
                },
                series: [
                    {
                        name: '工单数量',
                        type: 'bar',
                        data: [],
                        barWidth: 36, // 设置柱子宽度
                        barCategoryGap: 0, // 设置柱子间的间隔为0
                        itemStyle: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1,
                                [
                                    { offset: 0, color: '#2c7cf2' }, // 从顶部开始
                                    { offset: 1, color: '#80b3ff' } // 到底部结束
                                ]
                            )
                        },
                        showBackground: true,
                        backgroundStyle: {
                            color: '#fafbfc',
                            opacity: "0.5"
                        }
                    },
                ]
            },
    };
  },

  computed: {
      maxTableHeight() {
          const h = this.clientHeight - this.searchH - 330 + this.iframeHeight;
          const _h = this.clientHeight - 330 - this.searchH;
          return this.$store.state.inIframe ? h : _h;
      },
      ...mapGetters(["clientHeight", "iframeHeight"]),
  },
  watch: {},
  async mounted() {
      this.user = this.$store.state.user;
      this.agencyId = this.user.agencyId;
      await this.getOrgData();
      this.agencyLevel = localStorage.getItem("level", this.orgData.level);
      await this.getTableData();
      await this.initEcharts();
      await this.EventCategoryAnalysis();
      await this.EventCate();
      await this.getCategoryTree()
  },
  methods: {
    calculateRowspan(item) {
      
      if (!item.children || !item.children.length) {
        return 1;
      }
 
    },
      initEcharts() {

          if(this.categoryCountShow){
            this.categoryPie= echarts.init(document.getElementById("categoryPie"));
            this.categoryPie.setOption(this.categoryPieOption);
            let than = this;
            this.categoryPie.on("click", function (params) {
              than.handelClickChart(params);
            });
          }

          if(this.communityCountShow && this.agencyLevel!='community'){
            this.communityChart= echarts.init(document.getElementById("communityChart"));
            this.communityChart.setOption(this.communityOption);
            let than = this;
            this.communityChart.on("click", function (params) {
              than.handelClickCommunityChart(params);
            });
          }

          if(this.departCountShow && this.agencyLevel!='community'){
            this.departChart= echarts.init(document.getElementById("departChart"));
            this.departChart.setOption(this.departOption);
            let than = this;
            this.departChart.on("click", function (params) {
              than.handelClickDepartChart(params);
          });
          }

          if(this.subCategoryCountShow){
            this.hotlineChart= echarts.init(document.getElementById("hotlineChart"));
            this.hotlineChart.setOption(this.hotlineChartOption);
            let than = this;
            this.hotlineChart.on("click", function (params) {
                than.handelClickChart(params);
            });
          }

          window.addEventListener("resize", this.handleWindowResize);

          console.log("图表加载")
      },
      handleWindowResize() {
          if (this.categoryPie) {
              this.categoryPie.resize();
          }
      },
      handelClickChart(params) {
        this.hiddenAllDialog();
          this.showFormList = true;
          this.cleanSearchForm();
          this.recId = params.data.id;
      },


      handelClickCommunityChart(params) {
        this.hiddenAllDialog();
          this.showFormList = true;
          this.cleanSearchForm();
          this.communityId = params.data.id;
      },

      handelClickDepartChart(params) {
        this.hiddenAllDialog();
          this.showFormList = true;
          this.cleanSearchForm();
          this.departId = params.data.id;
      },
      handleClose() {
          this.showFormList = false;
      },

      async handelClickDetail(row) {
          this.eventId = row.icEventId;
            const url = "/governance/icEvent/detail";
            const { data, code, msg } = await requestPost(url, {
                icEventId: this.eventId,
            });
            if (code != 0) {
                this.$message.error(msg);
            } else {
                this.eventDetailData = { ...data };
                this.pageType = "info";
                this.showFormList = true;
                this.showFormDetail = true;
            }
      },
      

      // 查看
      async handleLook(row) {

        let { name,resiId } = row
        this.$store.dispatch('saveData', { name,resiId });
        this.$router.push({ name: 'jumin-huaxiang' });
        this.$store.state.contentTabs = this.$store.state.contentTabs.map(item => {
            if (item.name === "jumin-huaxiang") {
            return {...item, title: name };
            }
            return item;
        });
      },

      handleClose() {
            this.hiddenAllDialog();
            this.pageType = "list";
            this.cleanSearchForm();
            this.getTableData();
        },
        handleOk() {
          this.hiddenAllDialog();
            this.pageType = "list";
            this.cleanSearchForm();
            this.pageNo = 1;
            this.getTableData();
        },

        handleEditSuccess() {
            this.handleClose();
            this.getTableData();
        },


      //加载组织数据
      async getOrgData() {
        const url = "/gov/org/agency/maporg";
        let params = {
          orgId: "",
          level: "",
        };

        const { data, code, msg } = await requestPost(url, params);

        if (code === 0) {
          this.orgData = data;
        } else {
          this.$message.error(msg);
        }
      },

      // 搜索事件
      async handleSearch(val) {
          console.log(this.formData);
          // 清空数据
          this.cleanReportData();
          await this.getTableData();
          await this.initEcharts();
          await this.EventCategoryAnalysis();
          await this.EventCate();
          await this.getCategoryTree()
      },
      //事件类型统计
      async getCategoryTree(){
        if(this.formData.queryDateStart&&this.formData.queryDateEnd){
          this.starttime=this.formData.queryDateStart,
          this.endtime=this.formData.queryDateEnd
        }else{{
          this.getLastMonthRange()
        }
        }
         const url = "/governance/icEvent/getCategoryTree";
        let param = {
          startDate:this.starttime,
          endDate:this.endtime,
          usableFlag:true   
          }
        const { data, code, msg } = await requestPost(url, param);
        if (code === 0) {
          this.tableList=this.flattenTree(data);
          console.log(this.tableList);
//     // {
//     //     "id": "1",
//     //     "pid": "0",
//     //     "customerId": null,
//     //     "pids": "0",
//     //     "pidList": null,
//     //     "parentCategoryCode": null,
//     //     "categoryName": "城市综合",
//     //     "categoryCode": "A1",
//     //     "categoryType": "0",
//     //     "sort": 0,
//     //     "color": null,
//     //     "isDisable": 1,
//     //     "infoCode": "A",
//     //     "eventCount": 4,
//     //     "proportion": 100,
//     //     "level1": "城市综合",
//     //     "level2": null,
//     //     "level3": null,
//     //     "level4": null,
//     //     "level5": null
//     // },
//     // {
//     //     "id": "11",
//     //     "pid": "1",
//     //     "customerId": null,
//     //     "pids": "1",
//     //     "pidList": null,
//     //     "parentCategoryCode": null,
//     //     "categoryName": "城市管理",
//     //     "categoryCode": "A102",
//     //     "categoryType": "1",
//     //     "sort": 0,
//     //     "color": null,
//     //     "isDisable": 1,
//     //     "infoCode": "A",
//     //     "eventCount": 2,
//     //     "proportion": 50,
//     //     "level1": null,
//     //     "level2":  "城市综合",
//     //     "level3": null,
//     //     "level4": null,
//     //     "level5": null
//     // },
//     // {
//     //     "id": "98",
//     //     "pid": "11",
//     //     "customerId": null,
//     //     "pids": "1,11",
//     //     "pidList": null,
//     //     "parentCategoryCode": null,
//     //     "categoryName": "市容环境",
//     //     "categoryCode": "A10201",
//     //     "categoryType": "2",
//     //     "sort": 0,
//     //     "color": null,
//     //     "isDisable": 1,
//     //     "infoCode": "A",
//     //     "eventCount": 2,
//     //     "proportion": 100,
//     //     "level1":null ,
//     //     "level2": null,
//     //     "level3": "城市综合",
//     //     "level4": null,
//     //     "level5": null
//     // },
//     // {
//     //     "id": "14",
//     //     "pid": "1",
//     //     "customerId": null,
//     //     "pids": "1",
//     //     "pidList": null,
//     //     "parentCategoryCode": null,
//     //     "categoryName": "居民生活",
//     //     "categoryCode": "A105",
//     //     "categoryType": "1",
//     //     "sort": 0,
//     //     "color": null,
//     //     "isDisable": 1,
//     //     "infoCode": "A",
//     //     "eventCount": 2,
//     //     "proportion": 50,
//     //     "level1": null,
//     //     "level2": null,
//     //     "level3": null,
//     //     "level4":"城市综合" ,
//     //     "level5": null
//     // },
//     // {
//     //     "id": "125",
//     //     "pid": "14",
//     //     "customerId": null,
//     //     "pids": "1,14",
//     //     "pidList": null,
//     //     "parentCategoryCode": null,
//     //     "categoryName": "污水",
//     //     "categoryCode": "A10507",
//     //     "categoryType": "2",
//     //     "sort": 0,
//     //     "color": null,
//     //     "isDisable": 1,
//     //     "infoCode": "A",
//     //     "eventCount": 2,
//     //     "proportion": 100,
//     //     "level1": null,
//     //     "level2": null,
//     //     "level3": null,
//     //     "level4": null,
//     //     "level5": "城市综合"
//     // }
// ]
          console.log(this.tableList,"lksdjfklj s");
        } else {
          this.$message.error(msg);
        }
        },
  formatDate1(date) {
  // 获取年份、月份和日期
  const year = date.getFullYear();
  const month = date.getMonth() + 1; // 月份从0开始
  const day = date.getDate();

  // 返回格式化的字符串
  return `${year}-${month}-${day} 00:00:00`;
},
   //获取前一个月的日期
   getLastMonthRange() {
    const now = new Date();
    const firstDayOfCurrentMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
    const lastDayOfLastMonth = new Date(firstDayOfCurrentMonth - 1);
    const firstDayOfLastMonth = new Date(Date.UTC(lastDayOfLastMonth.getUTCFullYear(), lastDayOfLastMonth.getUTCMonth(), 1));
    firstDayOfLastMonth.setUTCHours(0, 0, 0, 0);
    lastDayOfLastMonth.setUTCHours(0, 0, 0, 0);
    this.starttime=this.formatDate1(firstDayOfLastMonth),
    this.endtime=this.formatDate1(lastDayOfLastMonth)
},
      //对部门进行统计
      async EventCate(){
         const url = "/governance/icEvent/EventCategoryAnalysis";
          // 对社区，部门进行更改
          if(this.formData.queryDateStart&&this.formData.queryDateEnd){
          this.starttime=this.formData.queryDateStart,
          this.endtime=this.formData.queryDateEnd
        }else{{
          this.getLastMonthRange()
        }
        }
          let param = {
          startDate: this.starttime,
          endDate:this.endtime,
          usableFlag:true   
        }
        const { data, code, msg } = await requestPost(url, param);
        if (code === 0) {
          console.log(data);
          data.map(item=>{
            if(item.assignOrgType=="duty"){
              this.departmentList.push(item)
            }else{
              this.communityList.push(item)
            }
          })
          console.log(this.departmentList,"564534");
          console.log(this.communityList,"sd ads ");
        } else {
          this.$message.error(msg);
        }
        },
  flattenTree(tree, levelKeys = []) {
  let result = [];
  console.log(tree,"tree");
  tree.forEach(node => {
    console.log(levelKeys);
    let newLevelKeys = [...levelKeys];
    newLevelKeys.push(node.categoryName);
    console.log(newLevelKeys,"newLevelKeys");
    let level1 = newLevelKeys[0] || null;
    let level2 = newLevelKeys[1] || null;
    let level3 = newLevelKeys[2] || null;
    let level4 = newLevelKeys[3] || null;
    let level5 = newLevelKeys[4] || null;

    if (level2) level1 = null;
    if (level3) level2 = null;
    if (level4) level3 = null;
    if (level5) level4 = null;

    let flattenedNode = {
      ...node,
      level1: level1,
      level2: level2,
      level3: level3,
      level4: level4,
      level5: level5
    };
    
    delete flattenedNode.children;
    result.push(flattenedNode);
    
    if (node.children && node.children.length > 0) {
      console.log(node,"node");
      result = result.concat(this.flattenTree(node.children, newLevelKeys));
    }
  });
  console.log( result);
  return result;
},
      // 对总数做出统计
      async  EventCategoryAnalysis(){
        const url = "/governance/icEvent/EventCategoryAnalysis";
        if(this.formData.queryDateStart&&this.formData.queryDateEnd){
          this.starttime=this.formData.queryDateStart,
          this.endtime=this.formData.queryDateEnd
        }else{{
          this.getLastMonthRange()
        }
        }
          let params = {
          startDate: this.starttime,
          endDate:this.endtime,
          usableFlag:true   
        }
        const { data, code, msg } = await requestPost(url, params);
        if (code === 0) {
          console.log(data);
          this.analysisList = data[0];
          console.log(this.analysisList);
        } else {
          this.$message.error(msg);
        } 
      },
      cleanReportData(){
          console.log("刷新数据");
          this.report={}
          this.addressData=[]
          this.mobileData=[]
          this.addressMobileData=[]
          this.addComplainData=[]
          this.eventCategorys=[]


          this.categoryPieOption.series[0].data=[];

          this.communityOption.xAxis[0].data=[];
          this.communityOption.series[0].data=[];
          this.communityOption.series[1].data=[];

          this.departOption.xAxis[0].data=[];
          this.departOption.series[0].data=[];
          this.departOption.series[1].data=[];

          this.hotlineChartOption.xAxis.data=[];
          this.hotlineChartOption.series[0].data=[];
      },

      //   导出
      exportReport() {
        this.$message.info('功能即将开通，敬请期待')
      },

      //   获取分类
      async getTableData() {
            const url = '/governance/dwdEvent/report';
            const {formData } = this;
            const { data, code, internalMsg } = await requestPost(url, {
              ...formData
            });
            if (code != 0) {
              this.$message.info(internalMsg);
              return;
            }
            if (!data) {
                return;
            }

            this.report = data;

            this.tableLoading = true;

            //获取分类
            Object.keys(this.report.categoryCount).forEach((key) => {
              const category = this.report.categoryCount[key];

              const jsonObject = {
                  id: category.id,
                  name: category.name,
                  value: category.count
              };
              this.categoryPieOption.series[0].data.push(jsonObject);

            });

            // 获取社区
            Object.keys(this.report.communityCount).forEach((key) => {
              const community = this.report.communityCount[key];

              this.communityOption.xAxis[0].data.push(community.name);

              const recObject = {
                  id: community.id,
                  value: community.count
              };
              this.communityOption.series[0].data.push(recObject);

              this.communityOption.series[1].data.push(community.count/this.report.totalEvent*100);

            });

            // 获取科室
            Object.keys(this.report.departCount).forEach((key) => {
              const depart = this.report.departCount[key];

              this.departOption.xAxis[0].data.push(depart.name);
              const recObject = {
                  id: depart.id,
                  value: depart.count/this.report.totalEvent*100
              };
              this.departOption.series[0].data.push(recObject);


              this.departOption.series[1].data.push(depart.count);

            });

            // 获取热点诉求及区域分析
            Object.keys(this.report.subCategoryCount).forEach((key) => {
              const subcategory = this.report.subCategoryCount[key];
              this.hotlineChartOption.xAxis.data.push(subcategory.name);

              const recObject = {
                  id: subcategory.id,
                  value: subcategory.count
              };
              this.hotlineChartOption.series[0].data.push(recObject);
            });

            this.addressData = this.report.addressEvent
              ? this.report.addressEvent.map(item => {
                  return item;
                })
              : [];

              this.mobileData = this.report.mobileEvent
              ? this.report.mobileEvent.map(item => {
                  return item;
                })
              : [];

              this.addressMobileData = this.report.addressMobileEvents
              ? this.report.addressMobileEvents.map(item => {
                  return item;
                })
              : [];
              this.addComplainData = this.report.awoEvents
              ? this.report.awoEvents.map(item => {
                  return item;
                })
              : [];

              this.eventCategorys = this.report.eventCategorys
              ? this.report.eventCategorys.map(item => {
                  return item;
                })
              : [];

              // 合并行
              this.getSpanArr(this.addressMobileData);

              if (this.report && this.report.categoryCount && Object.keys(this.report.categoryCount).length > 0) {
                this.categoryCountShow = true;
              }

              if (this.report && this.report.communityCount && Object.keys(this.report.communityCount).length > 0) {
                this.communityCountShow = true;
              }

              if (this.report && this.report.departCount && Object.keys(this.report.departCount).length > 0) {
                this.departCountShow = true;
              }

              if (this.report && this.report.subCategoryCount && Object.keys(this.report.subCategoryCount).length > 0) {
                this.subCategoryCountShow = true;
              }
        },

        clickEventCategorys(row, column){
          this.hiddenAllDialog();
          this.showFormList = true;
          this.recId = row.categoryId;
        },

        clickAddressData(row, column){
          this.hiddenAllDialog();
          this.showFormList = true;
          this.recId = row.categoryId;
          this.address = row.address;
        },

        handelMoreAddressData(){
          this.hiddenAllDialog();
          this.cleanSearchForm();
          this.showAreaSameEventList = true;
        },
        handelMoreMobileData(){
          this.hiddenAllDialog();
          this.cleanSearchForm();
          this.showMobileEventList = true;
        },
        handelMoreAddressMobileData(){
          this.hiddenAllDialog();
          this.cleanSearchForm();
          this.showAreaNoSameEventList = true;
        },
        handelMoreAddComplainData(){
          this.hiddenAllDialog();
          this.cleanSearchForm();
          this.showAddEventList = true;
        },

        clickMobileData(row, column){
          this.hiddenAllDialog();
          this.showFormList = true;
          this.cleanSearchForm();
          this.mobile = row.mobile;
        },

        clickAddressMobileData(row, column){
          this.hiddenAllDialog();
          this.showFormList = true;
          this.cleanSearchForm();
          this.address = row.address;
        },
        clickAwoFlagData(row, column){
          this.hiddenAllDialog();
          this.$refs.awoList.open(row)
        },

        cleanSearchForm(){
          this.departId ='';
          this.eventId = "";
          this.recId ='';
          this.address ='';
          this.mobile ='';
          this.awo_flag ='';
        },

        hiddenAllDialog(){
          this.showFormList = false;
          this.showFormDetail = false;
          this.showAreaSameEventList = false;
          this.showMobileEventList = false;
          this.showAreaNoSameEventList = false;
          this.showAddEventList = false;
        },

        getSpanArr(data) {
            this.mergeArr.forEach((key, index1) => {
                let count = 0; // 用来记录需要合并行的起始位置
                this.mergeObj[key] = []; // 记录每一列的合并信息
                data.forEach((item, index) => {
                    // index == 0表示数据为第一行，直接 push 一个 1
                    if(index === 0) {
                        this.mergeObj[key].push(1);
                    } else {
                        // 判断当前行是否与上一行其值相等 如果相等 在 count 记录的位置其值 +1 表示当前行需要合并 并push 一个 0 作为占位
                        if(item[key] === data[index - 1][key]) {
                            this.mergeObj[key][count] += 1;
                            this.mergeObj[key].push(0);
                        } else {
                            // 如果当前行和上一行其值不相等
                            count = index; // 记录当前位置
                            this.mergeObj[key].push(1); // 重新push 一个 1
                        }
                    }
                })
            })
        },
        // 默认接受四个值 { 当前行的值, 当前列的值, 行的下标, 列的下标 }
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            // 判断列的属性
            if(this.mergeArr.indexOf(column.property) !== -1) {
                // 判断其值是不是为0
                if(this.mergeObj[column.property][rowIndex]) {
                    return [this.mergeObj[column.property][rowIndex], 1]
                } else {
                    // 如果为0则为需要合并的行
                    return [0, 0];
                }
            }
        }
  },

  props: {},
};
</script>
<style lang="scss" scoped>
@import "@/assets/scss/buttonstyle.scss";
@import "@/assets/scss/modules/management/list-main.scss";
@import "@/assets/scss/modules/shequzhili/event-info.scss";
@import "./css/index.scss";
table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  width: 40px;
  height: 20px;
  border: 1px solid #ccc;
  padding: 8px;
  text-align: center;
}

thead {
  background-color: #f9f9f9;
}

.div_btn_left>* {
  margin-right: 10px;
}

.m-table-item {
  display: flex;
  flex-direction: column;
}


#categoryPie {
    width: 100%;
    flex: 1;
}

#communityChart {
    width: 100%;
    flex: 1;
}

#departChart {
    width: 100%;
    flex: 1;
}

#hotlineChart {
    width: 100%;
    flex: 1;
}

.centered-title {
  text-align: center; /* 将文本水平居中对齐 */
  font-size: 28px; /* 设置标题字体大小 */
  font-weight: bold; /* 设置标题加粗 */
  color: #333; /* 设置标题颜色 */
  margin-bottom: 20px; /* 设置标题与下方内容的间距 */
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px; /* 调整高度以适应你的需要 */
  color: #888; /* 灰色字体颜色 */
  font-size: 20px; /* 字体大小 */
}


.arrow-container {
  position: relative;
  width: 100px; /* 调整箭头容器的宽度 */
  height: 100px; /* 调整箭头容器的高度 */
}

.arrow {
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 20px 0 20px 34.6px; /* 通过调整这里的数值可以改变箭头的大小 */
  border-color: transparent transparent transparent #007bff; /* 改变箭头颜色 */
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

</style>
  
  