<script lang="ts">
import { Component, Emit, Vue } from "vue-property-decorator";
import template from "./centerSide.component.html";
import TitleComponent from "@/components/title.component.vue";

// import("@/assets/style/pageCommon.component.scss");
// import("./centerSide.component.scss");
import RiskService from "@/service/risk.service";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import SystemService from "hbt-common/service/system.service";
import moment from "moment";

Component.registerHooks(["beforeRouteLeave"]);
@Component({
  template,
  components: {
    TitleComponent,
    Treeselect,
  },
})
export default class CenterSideComponent extends Vue {
  public tableService = new RiskService();
  public systemService = new SystemService();
  //标题图片
  imgSrc = require("@/assets/icons/png/env/env-title-icon.png");
  imgDangerSrc = require("@/assets/prevention/danger.png");
  imgDeptSrc = require("@/assets/prevention/dept.png");
  imgUserSrc = require("@/assets/prevention/user.png");

  //重大危险源包保责任制履职情况数据
  public resumptionData = {
    name: [],
    value: [],
  } as any;
  //重大危险源 查询参数
  public resumptionParams = {
    type: null,
    startTime: null,
    endTime: null,
    time: null,
  } as any;
  public endPickerOptions = {} as any;
  public worktaskchart: any;
  public hiddentaskchart: any;
  public personaltaskchart: any;
  public timer: any;
  public type = [
    {
      value: "0",
      label: "全部",
    },
    {
      value: "1",
      label: "主要负责人",
    },
    {
      value: "2",
      label: "技术负责人",
    },
    {
      value: "3",
      label: "操作负责人",
    },
  ];

  //部门隐患任务执行情况
  public taskExecutionData = {
    time: [],
    taskNumber: [],
    completeNumber: [],
  } as any;
  public taskExecutionOption = {} as any;
  //部门隐患任务排查情况
  public taskExecutionparams = {
    deptId: null,
  } as any;
  public tmpTaskExecutionData = [
    {
      department: "气化部门",
      timer: 15,
      execute: 12,
    },
    {
      department: "净化部门",
      timer: 25,
      execute: 17,
    },
    {
      department: "热电部门",
      timer: 18,
      execute: 11,
    },
    {
      department: "合成部门",
      timer: 22,
      execute: 12,
    },
    {
      department: "原料部门",
      timer: 19,
      execute: 16,
    },
    {
      department: "水务部门",
      timer: 25,
      execute: 14,
    },
  ] as any;

  //个人隐患任务执行情况
  public personalTasksData = [] as any;
  //个人隐患执行情况
  public personalParams = {
    userId: "",
  } as any;
  //成员列表
  public member = [] as any;
  //部门列表
  public department = [] as any;

  public resumptionOption = {} as any;

  public personalTaskOption = {} as any;

  created() {
    //获取部门和成员
    this.getDeptTreeAndPersonal();
  }
  mounted() {
    //重大危险源包保责任制履职情况
    this.statisticalResumption();
    //部门隐患任务执行情况
    this.statisticalTaskExecution();
    //个人排查任务执行情况
    this.statisticalPresonalTask();
  }
  /**
   * 获取部门
   */
  public getDeptTreeAndPersonal() {
    Promise.all([
      this.systemService.getDeptTree(),
      this.systemService.getUserList({ pageSize: 0 }),
    ]).then((results: any) => {
      this.department = results[0].data;
      this.member = results[1].data.datas.map((item) => {
        return {
          label: item.nickName,
          value: item.userId,
        };
      });
    });
  }
  /**
   * 重大危险源包保责任制履职情况
   */
  public statisticalResumption(params?) {
    this.tableService.getWorkTask(params ? params : {}).then((res: any) => {
      const resumptionData = {
        name: [],
        completeNumber: [] as any,
        taskNumber: [],
        percent: [],
      } as any;
      const sortData = res.data.sort(this.compareData("taskNumber"));
      sortData.forEach((item: any) => {
        resumptionData.name.push(item.taskChargeUserName);
        resumptionData.completeNumber.push(item.completeNumber);
        resumptionData.taskNumber.push(item.taskNumber);
        const percent = (item.completeNumber / item.taskNumber) * 100;
        resumptionData.percent.push(percent.toFixed(2));
      });
      const resumptionOption = this.statisticalResumptionChart(resumptionData);
      if (this.worktaskchart) {
        this.worktaskchart.clear();
        this.worktaskchart.setOption(resumptionOption);
      }
    });
  }

  public compareData(property) {
    return function (a, b) {
      const val1 = a[property];
      const val2 = b[property];
      return val1 - val2;
    };
  }
  /**
   * 重大危险源包保责任制履职情况  图表
   * @returns
   */
  public statisticalResumptionChart(resumptionData) {
    const tmpResumptionData = resumptionData;
    const dataZoomMove = {
      start: 0,
      end: 8,
    };
    // 设置等长的背景柱状图
    const maxData = new Array(tmpResumptionData.name.length).fill(100);
    return {
      dataZoom: [
        {
          show: true, // 为true 滚动条出现
          realtime: true,
          type: "slider", // 有type这个属性，滚动条在最下面，也可以不行，写y：36，这表示距离顶端36px，一般就是在图上面。
          height: "80%", // 表示滚动条的高度，也就是粗细
          startValue: dataZoomMove.start, // 表示默认展示20%～80%这一段。
          endValue: dataZoomMove.end,
          width: 5,
          right: "0",
          top: "20%", //位置和grid配置注意下
          //   height: "56%",
          yAxisIndex: [0, 1], //关联多个y轴
          textStyle: {
            color: "rgba(255,255,255,0)",
          },
          backgroundColor: "rgba(255,255,255,.1)",
          borderColor: "rgba(255,255,255,0)",
          fillerColor: "rgba(0,0,0,0)",
          handleSize: "5",
          handleStyle: {
            color: "rgba(255,255,255,0)",
          },
          brushStyle: {
            color: "rgba(129, 243, 253)",
          },
        },
        {
          //没有下面这块的话，只能拖动滚动条，鼠标滚轮在区域内不能控制外部滚动条
          type: "inside",
          yAxisIndex: 0,
          zoomOnMouseWheel: false, //滚轮是否触发缩放
          moveOnMouseMove: true, //鼠标滚轮触发滚动
          moveOnMouseWheel: true,
        },
      ],
      grid: {
        containLabel: true,
        // 边距自行修改
        bottom: "10px",
        left: "0",
        // top: "20%",
        right: "25px",
      },
      xAxis: [
        {
          show: true,
        },
        {
          show: false,
          splitLine: {
            show: false,
          },
        },
      ],
      yAxis: [
        {
          show: true,
          data: tmpResumptionData.name,
          position: "left",
          axisLabel: {
            lineHeight: 0,
            verticalAlign: "bottom",
            fontSize: 12,
            color: "#fff",
            formatter: "{value}",
          },
          axisLine: {
            show: false,
          },
          splitLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
        },
        {
          show: true,
          data: tmpResumptionData.taskNumber,
          offset: 5,
          position: "right",
          axisLabel: {
            lineHeight: 0,
            verticalAlign: "bottom",
            fontSize: 12,
            color: "#fff",
            formatter: "{value}",
          },
          axisLine: {
            show: false,
          },
          splitLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
        },
      ],
      series: [
        {
          name: "进度",
          show: true,
          type: "bar",
          barGap: "-100%",
          xAxisIndex: 1,
          barWidth: 8,
          itemStyle: {
            borderRadius: 10,
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 1,
              y2: 0,
              colorStops: [
                {
                  offset: 0,
                  color: "#7DAEFF", // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: "#7DAEFF", // 0% 处的颜色
                },
              ],
              global: false, // 缺省为 false
            },
          },
          label: {
            show: true,
            distance: -20,
            position: "insideRight",
            formatter: function (value) {
              const k = tmpResumptionData.name.indexOf(value.name);
              const index = k;
              return `${tmpResumptionData.completeNumber[k]}`;
            },
            offset: [-10, 2],
            color: "#fff",
          },
          labelLine: {
            show: false,
          },
          z: 2,
          data: tmpResumptionData.percent,
          animationDelay: 1000,
          animationDuration: 1000,
        },
        {
          name: "百分比",
          z: 1,
          show: true,
          type: "bar",
          xAxisIndex: 1,
          barGap: "-100%",
          barWidth: 8,
          itemStyle: {
            borderRadius: 4,
            color: "rgba(13, 55, 78, 1)",
          },
          label: {
            show: false,
          },
          data: maxData,
        },
      ],
    };
  }
  public dataChange(data, type) {
    if (this.resumptionParams.time && this.resumptionParams.time.length > 0) {
      this.resumptionParams.startTime =
        this.resumptionParams.time[0] + " " + "00:00:00";
      this.resumptionParams.endTime =
        this.resumptionParams.time[1] + " " + "23:59:59";
    } else {
      this.resumptionParams.startTime = null;
      this.resumptionParams.endTime = null;
    }
    this.statisticalResumption(
      JSON.parse(JSON.stringify(this.resumptionParams))
    );
  }
  /**
   * 部门隐患任务执行情况
   */
  public statisticalTaskExecution(params?) {
    this.tableService.getDeptRiskTask(params ? params : {}).then((res: any) => {
      const taskExecutionData = {
        time: [],
        taskNumber: [],
        completeNumber: [],
      } as any;
      res.data.forEach((item: any) => {
        taskExecutionData.time.push(item.time);
        taskExecutionData.completeNumber.push(item.completeNumber);
        taskExecutionData.taskNumber.push(item.taskNumber);
      });

      const taskExecutionOption =
        this.statisticalTaskExecutionChart(taskExecutionData);
      if (this.hiddentaskchart) {
        this.hiddentaskchart.clear();
        this.hiddentaskchart.setOption(taskExecutionOption);
      }
    });
  }
  /**
   * 部门隐患任务执行情况  面积堆叠图
   * @returns
   */
  public statisticalTaskExecutionChart(taskExecutionData: any) {
    return {
      tooltip: {},
      color: ["rgba(125, 174, 255, 0.6)", "rgba(122, 106, 191, 0.6)"],
      grid: {
        left: 24,
        right: 24,
        bottom: 24,
        containLabel: true,
      },
      legend: {
        top: 25,
        left: "center",
        textStyle: {
          color: "#fff",
          fontSize: "10px",
        },
      },
      yAxis: [
        {
          type: "value",
          name: "单位：个",
          axisLabel: {
            color: "rgba(255,255,255,0.8)",
            fontSize: "7px",
            fontWeight: 400,
          },
          splitLine: {
            show: true, //让网格显示
            lineStyle: {
              //网格样式
              color: ["#999999"], //网格的颜色
              width: 1, //网格的宽度
              type: "solid", //网格是实实线，可以修改成虚线以及其他的类型
            },
          },
        },
      ],
      xAxis: [
        {
          type: "category",
          boundaryGap: false,
          axisTick: { show: false },
          data: taskExecutionData.time,
          axisLabel: {
            color: "rgba(255,255,255,0.8)",
            fontSize: "7px",
            fontWeight: 400,
          },
          splitLine: {
            show: true, //让网格显示
            lineStyle: {
              //网格样式
              color: ["#999999"], //网格的颜色
              width: 1, //网格的宽度
              type: "solid", //网格是实实线，可以修改成虚线以及其他的类型
            },
          },
        },
      ],
      series: [
        {
          name: "排查任务执行",
          type: "line",
          smooth: true,
          stack: "Total",
          areaStyle: {},
          symbol: "circle",
          emphasis: {
            focus: "series",
          },
          data: taskExecutionData.completeNumber,
        },
        {
          name: "定时排查任务",
          type: "line",
          smooth: true,
          stack: "Total",
          areaStyle: {},
          symbol: "circle",
          emphasis: {
            focus: "series",
          },
          data: taskExecutionData.taskNumber,
        },
      ],
    };
  }
  public dataDeptChange() {
    this.statisticalTaskExecution(this.taskExecutionparams);
  }
  /**
   * 个人排查任务执行情况
   */
  public statisticalPresonalTask(params?) {
    this.tableService.getUserRiskTask(params ? params : {}).then((res: any) => {
      this.personalTasksData = [];
      const personalTasksData = [
        { value: res.data.completeNumber, name: "已完成数" },
        { value: res.data.taskNumber, name: "未完成" },
      ];
      const  personalTaskOption = this.statisticalPresonalTaskChart(personalTasksData)
      if (this.personaltaskchart) {
        this.personaltaskchart.clear();
        this.personaltaskchart.setOption(personalTaskOption);
      }
    });
  }
  /**
   * 个人排查任务执行情况  环形图
   * @returns
   */
  public statisticalPresonalTaskChart(personalTasksData:any) {
    return {
      tooltip: {},
      color: ["#C9FFD7 ", "#FADFA4"],

      legend: {
        right: 5,
        y: "center",
        orient: "vertical",
        textStyle: {
          color: "#fff",
          fontSize: "10px",
        },
      },
      toolbox: {
        show: true,
        feature: {
          mark: { show: true },
          dataView: { show: true, readOnly: false },
          restore: { show: true },
          saveAsImage: { show: true },
        },
      },
      series: [
        {
          type: "pie",
          radius: ["40%", "70%"],
          label: {
            show: true,
            fontStyle: "normal",
            alignTo: "labelLine",
            normal: {
              formatter: "{b}\n{c}",
              position: "inner", //文字显示在内部，如果在外边把这个去掉就好
              color: "#fff",
            },
          },
          data: personalTasksData,
        },
      ],
    };
  }

  public dataUserChange() {
    this.statisticalPresonalTask(this.personalParams);
  }

  public getWorkTaskChart(echart, isBar?) {
    this.worktaskchart = echart;
  }
  public getHiddenTaskChart(echart, isBar?) {
    // echart.resize();
    this.hiddentaskchart = echart;
  }
  public getPersonalTaskChart(echart, isBar?) {
    // echart.resize();
    this.personaltaskchart = echart;

    setTimeout(() => {
      this.chartResize();
    }, 1000);
  }
  public chartResize() {
    // this.worktaskchart.resize();
    // this.hiddentaskchart.resize();
    // this.personaltaskchart.resize();
    this.timer = setInterval(() => {
      this.changePieChange();
    }, 5000);
  }

  public changePieChange() {
    // if (!this.hiddentaskchart || !this.personaltaskchart || !this.worktaskchart) {
    //   return;
    // }
    // this.worktaskchart.clear();
    this.statisticalResumption(JSON.parse(JSON.stringify(this.resumptionParams)));
    this.statisticalTaskExecution(this.taskExecutionparams);
    this.statisticalPresonalTask(this.personalParams);
  }

  beforeDestroy() {
    window.removeEventListener("resize", this.chartResize);
    clearInterval(this.timer);
    this.timer = null;
  }
}




</script>

<style scoped lang="scss" src="./centerSide.component.scss">

</style>
<style scoped lang="scss" src="../../assets/style/pageCommon.component.scss">

</style>



