<template>
  <div class="warning-box">
    <cpt-card>
      <div class="card-title">
        <img class="title-icon" src="../../../../assets/img/shuju/title-tip.png" />
        <div class="title-label">
          <el-cascader 
            v-model="selectAgency"
            :options="propTree" 
            :props="{ checkStrictly: true }" 
            :show-all-levels="false"
            clearable 
            @change="handleCascader">
          </el-cascader>
        </div>
        <div class="title-time">
          <div class="title-time-label">选择时间</div>
          <div class="second-select">
            <!-- <el-date-picker
              v-model="value2"
              type="month"
              placeholder="选择月">
            </el-date-picker> -->
            <el-date-picker v-model="timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              prefix-icon="el-icon-caret-bottom"
              value-format="yyyy-MM-dd"
              >
            </el-date-picker>
          </div>
        </div>
      </div>

      <!-- <div class="card-echart">
        <div class="card-left">
          <div class="echart-wr">
            <div class="echart-cicle"></div>
            <div id="echartOrg" class="echart-org"></div>
          </div>
          <div class="echarts-tips">
            <div class="tips-list">
              <div class="tips-item">
                <div class="tips-item-icon"></div>
                <div class="tips-item-text">为民服务</div>
              </div>
              <div class="tips-item">
                <div class="tips-item-icon"></div>
                <div class="tips-item-text">社会治安综合</div>
              </div>
              <div class="tips-item">
                <div class="tips-item-icon"></div>
                <div class="tips-item-text">社会治安综合</div>
              </div>
              <div class="tips-item">
                <div class="tips-item-icon"></div>
                <div class="tips-item-text">卫生计生监管执法</div>
              </div>
              <div class="tips-item">
                <div class="tips-item-icon"></div>
                <div class="tips-item-text">卫生计生监管执法</div>
              </div>
              <div class="tips-item">
                <div class="tips-item-icon"></div>
                <div class="tips-item-text">建设管理</div>
              </div>
              
              <div class="tips-item">
                <div class="tips-item-icon"></div>
                <div class="tips-item-text">为民服务</div>
              </div>
            </div>
          </div>
        </div>
        <div class="card-left">
          <div class="echart-wr">
            <div class="echart-cicle"></div>
            <div id="echartType" class="echart-org"></div>
          </div>
          <div class="echarts-tips echarts-tips-wd50">
            <div class="tips-lists">
              <div class="tips-items">
                <div class="tips-items-title">
                  <div>志愿者</div>
                </div>
                <div class="tips-items-num">
                  <div class="tips-item-count">17513</div>
                  <div class="tips-item-has">（服务次数：2430）</div>
                </div>
              </div>
              <div class="tips-items">
                <div class="tips-items-title">
                  <div>志愿者</div>
                </div>
                <div class="tips-items-num">
                  <div class="tips-item-count">17</div>
                  <div class="tips-item-has">（服务次数：2430）</div>
                </div>
              </div>
              <div class="tips-items">
                <div class="tips-items-title">
                  <div>志愿者</div>
                </div>
                <div class="tips-items-num">
                  <div class="tips-item-count">175</div>
                  <div class="tips-item-has">（服务次数：2430）</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div> -->

      <div class="echarts-container">
        <div id="echartsBox" class="echarts-boxs"></div>
      </div>

      <div class="warning-box-bottom">
        <screen-table
          :headerList="headerList"
          :tableData="tableData"
          :visibleLoading="visibleLoading"
          @look="handleLook"
        ></screen-table>
        <div class="pagination">
          <el-pagination
            :current-page="pageNo"
            :page-size="pageSize"
            background
            layout="prev, pager, next"
            @size-change="pageSizeChangeHandleNew"
            @current-change="pageCurrentChangeHandleNew"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </cpt-card>
    <dialog-info 
      v-if="showedMoreInfo" 
      :demandId="detailInfo.demandRecId"
      :query-origin="'demand-analysis'"
      @close="showedMoreInfo = false"
     />
  </div>
</template>

<script>
import { requestPost } from "@/js/dai/request";
import screenTable from "../components/screen-table/index";
import cptCard from "@/views/modules/visual/cpts/card";
import nextTick from "dai-js/tools/nextTick";
import dialogInfo from './dialogInfo'

import * as echarts from 'echarts';
export default {
  name: "warning-box",
  components: {
    cptCard,
    screenTable,
    dialogInfo
  },
  data() {
    return {
      showedMoreInfo: false,
      warningList: [],
      headerList: [
        { title: "序号", coulmn: 'index' },
        { title: "状态", coulmn: 'statusName' },
        { title: "所属网格", coulmn: 'gridName' },
        { title: "需求类型", coulmn: 'categoryName' },
        { title: "需求内容", coulmn: 'content' },
        { title: "上报类型", coulmn: 'reportTypeName' },
        { title: "上报人", coulmn: 'reportUserName' },
        { title: "上报时间", coulmn: 'reportTime' },
        { title: "需求人", coulmn: 'gridName' },
        { title: "服务方", coulmn: 'serviceName' },
        { title: "服务时间", coulmn: 'wantServiceTime' },
      ],
      categoryList: {},
      timeRange: '',
      tableData: [
        // [1,'商丘路社区第一网格','商丘路小区','2号楼','杨颖、王平、刘佳敏、丁辉、杨萍'],
      ],
      reportDict: [],
      selectAgency: '',
      propTree: [],
      value2: '',
      visibleLoading: true,
      pageNo: 1,
      pageSize: 10,
      total: 0,
      detailInfo: {}
    };
  },
  watch: {
    timeRange(val) {
      console.log('val-www', val)
      if (!val) return false
      this.handleCascader(this.selectAgency)
    }
  },
  async mounted() {
    this.initTime()
    await nextTick(100);
    await this.getAgencyList()
    await this.getDict()
    this.getServicePie(this.$store.state.user.agencyId, 'agency')
    // this.initCharts()
    // this.initChartType()
    // this.getServiceList(this.$store.state.user.agencyId, 'agency');
  },
  methods: {
    initCharts(xData, yData) {
      const eId = document.getElementById('echartsBox')
      let _charts = echarts.init(eId)

      let option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            // Use axis to trigger tooltip
            type: 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
          },
          backgroundColor: 'transprant',
          borderColor: 'transprant',
          textStyle: {
            color: '#fff'
          },
          formatter: params => {
              let res;
              let arr = []
              let total = 0
              const xName = params[0].axisValue
              this.categoryList.forEach(item => {
                if (item.categoryName === xName) {
                  arr = item.detail
                  total = item.total
                }
              })
              let title = `<div style='margin-bottom: 10px;'><span>${xName}分类需求</span>${total}个</div>`
              let desc = ''
              let unit = '个'
              arr.forEach(item => {
                if (item.legendCode == 'volunteer') unit = '名'
                else unit = '个'
                if (item.legendCode == 'unfinished') {
                  desc += `<div><span>尚有 ${item.serviceDemandTotal} 个需求未完成</span></div>`
                }else {
                  desc += `<div><span>共 ${item.totalService} ${unit} ${item.legendName} 完成需求 ${item.serviceDemandTotal} 个</span></div>`
                }
                
              })
              res= title + desc
              return res
          }
        },
        legend: {
          top: 'bottom',
          bottom: 'bottom',
          textStyle: {
            color: '#fff'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          axisLabel: {
            color: '#fff',
            interval: 0
          },
          axisTick: {
            interval: 0
          },
          data: xData
        },
        yAxis: {
          type: 'value',
          splitLine: {
            show: false
          },
          axisLabel: {
            color: '#fff'
          },
          // axisLine: false
        },
        series: yData
        
      };

      option && _charts.setOption(option);
      _charts.on('click', params => {
        this.clickBar(params)
      })

    },
    async getServicePie(orgId, orgType) {
      const url = "/heart/userdemand/category-analysis";
      let params = {
        orgId,
        orgType,
        startDateId: this.timeRange && this.timeRange[0] || '',
        endDateId: this.timeRange && this.timeRange[1] || ''
      };
      const { data, code, msg } = await requestPost(url, params);
      if (code === 0) {
        console.log('pie-data', data)
        const { categoryList, legend } = data
        this.categoryList = categoryList
        let xData = categoryList.map(item => item.categoryName)
        let yData = []
        yData = legend.map(item => {
          return {
            name: item.legendName,
            type: 'bar',
            stack: 'total',
            // barWidth: 20,
            label: {
              show: true
            },
            emphasis: {
              focus: 'series'
            },
            data: categoryList.map(n => n.total)
          }
        })
        
        this.initCharts(xData, yData)
        this.getServiceList(orgId, orgType, data.categoryList[0].categoryCode)
      } else {
      }
      this.visibleLoading = false;
    },
    async getServiceList(orgId, orgType, _code) {
      const url = "/heart/userdemand/pagelist-analysis";
      let params = {
        orgId,
        orgType,
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        categoryCode: _code || '',
        startDateId: this.timeRange && this.timeRange[0] || '',
        endDateId: this.timeRange && this.timeRange[1] || ''
      };
      const { data, code, msg } = await requestPost(url, params);
      if (code === 0) {
        const status = {
          pending: '待处理',
          canceled: '已取消',
          assigned: '已派单',
          have_order: '已接单',
          finished: '已完成',
        }
        // const type = {
        //   volunteer: '志愿者',
        //   social_org: '社会组织',
        //   community_org: '社区自组织',
        //   party_unit: '区域党建单位',
        // }
        this.tableData = data.list.map((item, index) => {
          return {
            ...item,
            statusName: status[item.status],
            reportTypeName: this.reportDict.filter(n => n.value === item.reportType)[0].label,
            index: index + 1
          }
        })
        this.total = data.total
        
      } else {
      }
      this.visibleLoading = false;
    },
    async getAgencyList() {
      // const url = "/gov/org/customeragency/staffinagencylist";
      const url = '/gov/org/customeragency/agencygridtree'
      // let params = {
      //   agencyId: this.$store.state.user.agencyId,
      // };
      const { data, code, msg } = await requestPost(url);
      if (code === 0) {
        console.log('data-org----o', data)
        this.selectAgency = [`${data.agencyId}-${data.level}`]
        let arr = []
        arr.push(data)
        this.propTree = arr && this.getTreeData(arr)

      } else {
        this.$message.error(msg)
      }
    },
    async getDict() {
      // const url = "/gov/org/customeragency/staffinagencylist";
      const url = '/sys/dict/data/dictlist'
      let params = {
        dictType: 'user_demand_report_type',
      };
      const { data, code, msg } = await requestPost(url, params);
      if (code === 0) {
        console.log('data-org----dict', data)
        this.reportDict = data

      } else {
        this.$message.error(msg)
      }
    },
    getTreeData(data){
      if (!Array.isArray(data)) return []
      let arr = data.map(item => {
        let _item = {}
        if (item.subAgencyList) {
          if (item.subAgencyList.length === 0) {
            _item = { 
              label: item.agencyName,
              value: item.agencyId + '-' + item.level,
              level: item.level,
              children: undefined 
            }
          } else _item = { 
            label: item.agencyName,
            value: item.agencyId + '-' + item.level,
            level: item.level,
            children: this.getTreeData(item.subAgencyList)}
        } else {
          _item = { 
            label: item.agencyName,
            value: item.agencyId + '-' + item.level,
            level: item.level,
          }
        }
        return _item
      })
      return arr
    },
    initTime() {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      console.log('time-rtt', this.timeFormat(start), this.timeFormat(end))
      this.timeRange = [this.timeFormat(start), this.timeFormat(end)]
    },
    timeFormat(date) {
      if (!date || typeof date === 'string') {
        return false
      }
      var y = date.getFullYear() //年
      var m = date.getMonth() + 1 //月
      if (m < 10) m = '0' + m
      var d = date.getDate() //日
      if (d < 10) d = '0' + d

      return y + '-' + m + '-' + d
    },
    clickBar(params) {
      console.log('params---p', params)
      let code = ''
      this.categoryList.forEach(item => {
        if (item.categoryName == params.name) code = item.categoryCode
      })
      if (code) {
        const _arr = this.selectAgency[this.selectAgency.length - 1].split('-')
        const orgType = _arr[1] !== 'grid' ? 'agency': 'grid'
        this.getServiceList(_arr[0], orgType, code)
      }
    },
    async handleLook(val) {
      
      // this.detailId = val.id
      this.detailInfo = val
      // await this.getDetail(val.id)
      this.showedMoreInfo = true
    },
    handleCascader(val) {
      console.log('val-vvv', val)
      if (val.length > 0) {
        const _arr = val[val.length - 1].split('-')
        const orgType = _arr[1] !== 'grid' ? 'agency': 'grid'
        this.getServicePie(_arr[0], orgType)
      }
      
    },
    pageSizeChangeHandleNew(val) {
      this.pageNo = 1;
      this.pageSize = val;
      this.handleCascader(this.selectAgency)
    },
    pageCurrentChangeHandleNew(val) {
      this.pageNo = val;
      this.handleCascader(this.selectAgency)
    },
  },
};
</script>

<style
  lang="scss"
  src="@/assets/scss/modules/visual/warning.scss"
  scoped
></style>
<style lang="scss" scoped>
.card-title {
  display: flex;
  align-items: center;
  cursor: pointer;
  .title-icon {
    display: block;
    width: 46px;
    height: 34px;
    box-sizing: border-box;
    margin-right: 6px;
  }
  ::v-deep .el-dropdown {
    font-size: 16px;
    color: #fff;
    font-weight: 800;
  }
  .title-time {
    display: flex;
    align-items: center;
    box-sizing: border-box;
    margin-left: 30px;
    font-size: 14px;
    color: #fff;
    .title-time-label {
      margin-right: 10px;
    }
    ::v-deep .el-date-editor--month {
      width: 100px;
      .el-input__inner {
        width: 100px;
        height: 24px;
        box-sizing: border-box;
        padding: 0;
        font-size: 14px;
        color: #fff;
        line-height: 24px;
        text-align: center;
        background: #06186D;
        border: 1px solid #1A64CC;
        border-radius: 2px;
      }
      .el-input__prefix {
        display: none;
      }
      .el-input__suffix {
        right: 0;
        .el-input__icon {
          line-height: 24px;
        }
      }
      
    }
  }

  .title-label {
    ::v-deep .el-input {
      width: 180px;
      .el-input__inner {
        font-size: 20px;
        font-weight: 800;
        color: #fff;
        background: transparent;
        border: 0;
      }
      .el-icon-arrow-down::before {
          content: "\e790";
      }
    }
  }
}
.second-select {
    margin: 0 10px 0 0;
    ::v-deep .el-input {
      width: 180px;
      height: 36px;
      .el-input__inner {
        height: 100%;
        padding: 0 10px;
        color: #fff;
        line-height: 36px;
        background: #06186d;
        border: 1px solid #1a64cc;
      }

      .el-icon-arrow-up:before {
        content: "\e78f";
      }
      // .el-select__caret:before {
      //   content: '\E790'
      // }
    }
    ::v-deep .el-date-editor {
      width: 360px;
      position: relative;
      background: #06186d;
      border: 1px solid #1a64cc;
      .el-range-input {
        color: #fff;
        background: #06186d;
      }
      .el-range-separator {
        color: #fff;
      }
      .el-range__icon {
        position: absolute;
        right: 5px;
        // float: right;
      }
      .el-input__prefix {
        left: unset;
        right: 5px;
      }
    }
  }
.card-echart {
  display: flex;
  margin-top: 40px;
  .card-left {
    position: relative;
    flex: 1;
    display: flex;
    
  }
}
.echart-wr {
  position: relative;
  flex-shrink: 0;
  width: 50%;
  height: 320px;
  box-sizing: border-box;
  .echart-org {
    width: 100%;
    height: 100%;
  }
  .echart-cicle {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 240px;
    height: 240px;
    box-sizing: border-box;
    margin-top: -120px;
    margin-left: -120px;
    border: 1px dashed rgba(0, 96, 240, 1);
    border-radius: 50%;
  }
}

.echarts-tips {
  width: 40%;
  // flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}
.echarts-tips-wd50 {
  width: 50%;
}
.tips-list, .tips-item, .tips-lists, .tips-items-num {
  display: flex;
  align-items: center;
}
.tips-list {
  // width: 100%;
  // height: 100%;
  flex-wrap: wrap;
  // justify-content: center;
  .tips-item {
    // flex: 1;
    width: 50%;
    margin-top: 20px;
    // margin-right: 40px;
    cursor: pointer;
    .tips-item-icon {
      width: 20px;
      height: 10px;
      box-sizing: border-box;
      margin-right: 8px;
      background: #1B51FF;
      border-radius: 2px;
    }
    .tips-item-text {
      font-size: 16px;
      color: #D2E7FF;
    }
  }
}
.tips-lists {
  width: 100%;
  flex-wrap: wrap;
  .tips-items {
    margin-bottom: 30px;
    width: 50%;
    .tips-items-title {
      font-size: 16px;
    }
    .tips-items-num {
      justify-content: space-between;
      box-sizing: border-box;
      margin-top: 20px;
      padding-right: 30px;
      font-size: 20px;
      .tips-item-has {
        font-size: 14px;
      }
    }
  }
}


.echarts-boxs {
  width: 100%;
  height: 400px;
}


</style>
