import * as echarts from '../../ec-canvas/echarts';
import {
  getMonthStartEnd,
  formatTime
} from '../../utils/util'
let chart = null;
const app = getApp()

/**
 * 获取像素比
 */
const getPixelRatio = () => {
  let pixelRatio = 0
  wx.getSystemInfo({
    success: function (res) {
      pixelRatio = res.pixelRatio
    },
    fail: function () {
      pixelRatio = 0
    }
  })
  return pixelRatio
}

/**
 * 设置echarts
 */
function initChart(data) {
  if (chart == null) return
  chart.init((canvas, width, height) => {
    var dpr = getPixelRatio();
    const chart = echarts.init(canvas, null, {
      width: width,
      height: height,
      devicePixelRatio: dpr
    });
    canvas.setChart(chart);

    var colorList = ["#FF9C00", "#FF4E00", "#2678FF"]
    var dataList = [data.resolving || 1, data.unresolved || 1, data.resolved || 1];
    var totalNum = data.dangerTotal || -1;
    var seriesList = []
    dataList.forEach((item, index) => {
      var obj = {
        value: Math.floor(item / totalNum * 100),
      }
      seriesList.push({
        type: 'bar',
        data: [obj],
        stack: 'one',
        roundCap: true,
        coordinateSystem: 'polar',
        itemStyle: {
          normal: {
            color: colorList[index],
            borderWidth: 2,
            borderColor: colorList[index]
          }
        },
      })
    })
    const option = {
      title: [{
        text: '{num|' + (totalNum < 0 ? 0 : totalNum) + '}',
        x: '48%',
        y: '35%',
        textAlign: 'center',
        textStyle: {
          rich: {
            num: {
              fontSize: 28,
              fontWeight: 'bold',
              lineHeight: 40,
              color: '#000000'
            },

          }
        },
      }],
      grid: {
        bottom: '0%'
      },
      angleAxis: {
        max: 100,
        clockwise: true, // 逆时针
        show: false
      },
      radiusAxis: {
        type: 'category',
        show: true,
        axisLabel: {
          show: false,
        },
        axisLine: {
          show: false,

        },
        axisTick: {
          show: false
        },
      },
      polar: {
        center: ['50%', '50%'],
        radius: ['70%', '90%'],
      },
      series: seriesList
    };

    chart.clear();
    chart.setOption(option);
    return chart;
  })
}

Page({
  data: {
    baseImgUrl: app.FILE_SERVER_URL,
    nineType: 0,
    ec: {
      lazyLoad: true
    },
    filterIndex: 0,
    itemList: [{
        icon: "icon_tab1",
        name: "履职清单",
        href: "/pages/duty/index/index"
      },
      // {
      //   icon: "icon_tab2",
      //   name: "专项任务",
      //   href: "/pages/task/index/index"
      // },
      {
        icon: "icon_tab3",
        name: "一企一档",
        href: "/pages/ent-obj/index/index"
      },
      {
        icon: "icon_tab4",
        name: "隐患核查",
        href: "/pages/danger/list/index"
      },
      // {
      //   icon: "icon_tab5",
      //   name: "群防群治",
      //   href: "/pages/people/index/index",
      // },
      // {
      //   icon: "icon-emergency",
      //   name: "应急管理",
      //   href: "/pages/emergency/index/index",
      // },
      // {
      //   icon: "icon_tab6",
      //   name: "发布通知",
      //   href: "/pages/msg/push-index/index",
      // },
    ],
    filter: [{
      lab: '今日数据',
      val: 0
    }, {
      lab: '本月数据',
      val: 1
    }],
    dLegend: [{
      name: '已整改',
      num: 0,
      color: '#2678FF'
    }, {
      name: '整改中',
      num: 0,
      color: '#FF9C00'
    }, {
      name: '未整改',
      num: 0,
      color: '#FF4E00'
    }],

    // 数据统计
    tab1: [{
      icon: "icon_tab1",
      name: "工作日志",
      href: "/pages/t-j/g-z-r-z/index/index"
    }, {
      icon: "icon_tab1",
      name: "工作统计",
      href: "/pages/t-j/g-z-t-j/index/index"
    }, {
      icon: "icon_tab1",
      name: "应急统计",
      href: "/pages/t-j/y-j/index/index"
    }, {
      icon: "icon_tab1",
      name: "基本信息",
      href: "/pages/t-j/j-b-x-x/index/index"
    }],
    // 工作台
    tab2: [{
        icon: "icon_tab6",
        name: "上报动态",
        href: "/pages/g-z-t/s-b/index/index",
      },
      {
        icon: "icon_tab2",
        name: "待办事项",
        href: "/pages/g-z-t/d-b-s-x/index/index?id=0"
      },
      {
        icon: "icon_tab4",
        name: "已办事项",
        href: "/pages/g-z-t/d-b-s-x/index/index?id=1"
      },
    ],
    // 应急指挥
    tab3: [{
        icon: "icon_tab5",
        name: "应急预案",
        href: "/pages/y-j/y-a/index/index",
      },
      {
        icon: "icon_tab5",
        name: "事件上报",
        href: "/pages/y-j/z-h/index/index"
      },
      {
        icon: "icon_tab5",
        name: "应急通讯录",
        href: "/pages/y-j/t-x/index/index"
      },
    ],

    // 公告
    notice: [
      'https://mmbiz.qpic.cn/mmbiz_jpg/QFxgibMOdV09EdiaTK8M4z7EWPD0kor6RkRibJ9Zfte1GtdQyeTY7zMCeXnMd8LPeGHOX1icWcSB4C9BmdSia5Tjxpw/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1&wx_co=1',
      'https://mmbiz.qpic.cn/mmbiz_png/QFxgibMOdV09NttuUu5jDN3YSKC2vRS8A3Yr35STiaibKwzGPAmvZr9dcqtqrSVFCph7jA0HL7T4JXhfOwMqRWI7A/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1',
      'https://mmbiz.qpic.cn/mmbiz_png/QFxgibMOdV09enRGm9zrUxjTib9ibyfjY87diafrU5AljEONticxlcdzgS4ebQhQpNxeeHWTC9PjkjR0srSFvYria1Tw/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1',
      'https://mmbiz.qpic.cn/mmbiz_png/QFxgibMOdV0icADgOhoofBPu01aYr9SrF1oHicDlckKibzKoEMneNibcNgsNXmmEX4jlTmVbSYMFuz4zYfVfNK20e8w/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1'
    ],

    showPop: false,
    msgData: null,
    checkInfo: {},

    userInfo: {}
  },

  /**
   * 跳转
   */
  toSkip: function (params) {
    const item = params.currentTarget.dataset.item;
    const url = params.currentTarget.dataset.url;
    if (url || item?.href) {
      wx.navigateTo({
        url: url || item.href,
      })
    }
  },

  /**
   * 跳转学习专栏
   */
  studyMore: function (prams) {
    wx.navigateTo({
      url: '/pages/study/index/index',
    })
  },

  /**
   * 统计数据类型筛选
   */
  changeType: function (params) {
    const type = params.currentTarget.dataset.type;
    this.data.nineType = type;
    this.setData(this.data)
    this.getStatic();
  },

  /**
   * 获取消息列表
   */
  getMsgList: function () {
    const params = {
      userId: app.globalData.userInfo.userId,
      page: 1,
      pageSize: 1
    }
    app.axios('GET', 'app', '/notice/getGovNoticeUserPage', params, false).then(res => {
      if (res.code == 1) {
        const list = res.data.rows;
        if (list.length > 0) {
          const item = list[0];
          if (item.isRead == 0) {
            this.data.msgData = item;
            this.data.showPop = true;
            this.handleRead();
          }
        }
        this.setData(this.data)
      }
    })
  },

  /**
   * 获取通知详情
   */
  handleRead: function (id) {
    app.axios('GET', 'admin', `/notice/getGovNotice/${id}`, {}, false);
  },


  handldePop: function () {
    this.data.showPop = !this.data.showPop;
    this.data.msgData = null;
    this.setData(this.data)
  },

  /**
   * 获取统计数据
   */
  getStatic: function () {
    setTimeout(() => {
      initChart({
        resolving: 1,
        unresolved: 1,
        resolved: 1,
        dangerTotal: 3
      })
    }, 500);
    this.data.dLegend[0].num = 1;
    this.data.dLegend[1].num = 1;
    this.data.dLegend[2].num = 1;
    return
    const timeDate = getMonthStartEnd(new Date());
    const params = {
      userId: app.globalData.userInfo.userId,
      startTime: this.data.filterIndex == 0 ? formatTime(new Date(), '-') : formatTime(timeDate.startTime, '-'),
      endTime: this.data.filterIndex == 0 ? formatTime(new Date(), '-') : formatTime(timeDate.endTime, '-'),
      smallType: this.data.nineType
    }
    app.axios('GET', 'app', `/Danger/dangerNumber`, params, false).then(res => {
      if (res.code == 1) {
        this.data.checkInfo = res.data;

        this.data.dLegend[0].num = res.data.dangerCount.resolved;
        this.data.dLegend[1].num = res.data.dangerCount.resolving;
        this.data.dLegend[2].num = res.data.dangerCount.unresolved;
        this.setData(this.data)
        initChart(this.data.checkInfo.dangerCount)
      }
    });
  },

  /**
   * 统计数据筛选
   */
  changeFilter: function (params) {
    const index = params.currentTarget.dataset.index;
    this.data.filterIndex = index;
    this.setData(this.data)
    this.getStatic();
  },

  onLoad(option) {
    this.data.userInfo = app.globalData.userInfo;
    this.getMsgList();
    this.getStatic();
  },

  onReady() {
    chart = this.selectComponent('#d-chart')
    this.setData(this.data)
  },
})