<template>

  <div>

    <a-row :gutter="16" style="height: 1622px">
      <a-col :span="5" style="height: 100%;">
        <a-card title="任务选择" :bordered="false" style="height: 100%">
          <a-directory-tree
            style="height: auto"
            v-model:expandedKeys="expandedKeys"
            v-model:selectedKeys="selectedKeys"
            multiple
            :tree-data="treeData"
            @expand="onExpand"
            @select="onTreeNodeSelect"
          ></a-directory-tree>
        </a-card>
      </a-col>

      <!--筛选条件-->
      <a-col :span="19">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :xl="16" :lg="7" :md="8" :sm="24">
              <a-form-item label="稽核工作日期范围">

                <a-range-picker @change="handleChange" v-model:value="taskDate"/>

                <a-radio-group @change="changeReportDate()" style="padding-left: 10px" v-model:value="latestDate" button-style="solid">
                  <a-radio-button value="7">最近7天</a-radio-button>
                  <a-radio-button value="30">最近30天</a-radio-button>
                  <a-radio-button value="180">最近180天</a-radio-button>
                </a-radio-group>

              </a-form-item>
            </a-col>
          </a-row>
        </a-form>


      </a-col>

      <a-col :span="5" style="padding-top: 10px">
        <a-card>
          <a-statistic
            title="未完善客户数量"
            :value="toImproveUser"
            :precision="0"
            suffix="个"
            :value-style="{ color: '#fa073f' }"
            style="margin-right: 50px"
          >
            <template #prefix>
              <arrow-up-outlined/>
            </template>
          </a-statistic>
        </a-card>
      </a-col>

      <a-col :span="5" style="padding-top: 10px">
        <a-card>
          <a-statistic
            title="待整改客户数量"
            :value="tobeRectified"
            :precision="0"
            suffix="个"
            :value-style="{ color: '#810320' }"
            style="margin-right: 50px"
          >
            <template #prefix>
              <arrow-up-outlined/>
            </template>
          </a-statistic>
        </a-card>
      </a-col>

      <a-col :span="5" style="padding-top: 10px">
        <a-card>
          <a-statistic
            title="待稽核客户数量"
            :value="toBeAudited"
            :precision="0"
            suffix="个"
            :value-style="{ color: '#0a0a09' }"
            style="margin-right: 50px"
          >
            <template #prefix>
              <arrow-up-outlined/>
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="4" style="padding-top: 10px">
        <a-card>
          <a-statistic
            title="稽核通过客户数量"
            :value="auditPassed"
            :precision="0"
            suffix="个"
            :value-style="{ color: '#3f8600' }"
            style="margin-right: 50px"
          >
            <template #prefix>
              <arrow-up-outlined/>
            </template>
          </a-statistic>
        </a-card>
      </a-col>

      <a-col :span="19" style="top: 10px">
        <a-card title="稽核概况统计" :bordered="false">
          <div id="statusRefusePie" ref="statusRefusePie" style="width:100%;height:370px"></div>
        </a-card>
      </a-col>

      <a-col :span="19" style="padding-top: 30px">
        <a-card title="稽核历史异常分析" :bordered="false">
          <div id="statusAuditPie" ref="statusAuditPie" style="width:50%;height:370px;float: left"></div>
          <div id="statusAuditHistogram" ref="statusAuditHistogram" style="width:50%;height:370px;left: 50%"></div>
        </a-card>
      </a-col>

      <a-col :span="19" style="top: 10px">
        <a-card title="稽核历史异常时间分布" :bordered="false">
          <div id="abnormalCreateTimeTrend" ref="abnormalCreateTimeTrend" style="width:100%;height:370px"></div>
        </a-card>
      </a-col>

    </a-row>


  </div>

  <!-- 查询区域 -->


</template>

<script>


import moment from 'moment';
import {getAction} from "@api/manage";
import * as echarts from 'echarts';

export default {
  name: 'SmsCheckWorkLogList',
  data() {
    return {
      description: '稽核工作日志管理页面',
      taskDate: '',
      url: {
        "statusRefuse": "/smsCheck/customerInfo/status/refuse",
        "taskList": "/smsCheck/task/list",
        "dateList": "/smsCheck/task/year/list",
        //基本信息 规范信息  附件资料 异常稽核统计
        "checkStateCount": "/smsCheck/workLog/check/state/count",
        "abnormalCreateTime": "/smsCheck/workLog/check/abnormal/count"
      },
      // '1': '未完善',
      statusMap: {
        '0': '未完善',
        '2': '待稽核',
        '4': '待整改',
        "5": '稽核通过',
      },
      abnormalMap: {
        "basicCheckState": "基本信息异常",
        "standardState": "规范信息异常",
        "dataState": "附件资料异常异常"
      },
      $statusRefusePie: "",
      $abnormalCheckPie: "",
      $abnormalCheckHistogram: "",
      $abnormalCreateTimeTrend: "",
      toImproveUser: 0,
      latestDate: '180',
      toBeAudited: 0,
      tobeRectified: 0,
      auditPassed: 0,
      treeData: [],
      expandedKeys: ['2022', '2022-10'],
      selectedKeys: {},
      statusAuditPieData: [],
      canvas: {},
      taskId:null,

    }
  },
  created() {
    const waterMarkText = '智慧运营系统';
    this.canvas = document.createElement('canvas');
    const ctx = this.canvas.getContext('2d');
    this.canvas.width = this.canvas.height = 100;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.globalAlpha = 0.08;
    ctx.font = '20px Microsoft Yahei';
    ctx.translate(50, 50);
    ctx.rotate(-Math.PI / 4);
    ctx.fillText(waterMarkText, 0, 0);

    //初始化日期 默认最近180天
    this.taskDate = [this.getRecentDay(parseInt(this.latestDate)), this.getRecentDay(0)]

    //稽核任务列表（树）
    this.taskList();
    //稽核概况统计
    this.statusRefuse();
    //稽核历史异常分析
    this.checkStateCount(this.url.checkStateCount);
    this.abnormalCreateTime();


  },
  computed: {},

  methods: {

    changeReportDate(a, event){
      //当前 value this.latestDatec
      //console.log(this.latestDate)
      this.taskDate = [this.getRecentDay(parseInt(this.latestDate)), this.getRecentDay(0)]
      this.statusRefuse(this.taskId);
      this.checkStateCount(this.url.checkStateCount, this.taskId);
      this.abnormalCreateTime(this.taskId);
    },

    handleChange(value,model){
      this.taskDate = model
     // model 当前value
      this.statusRefuse(this.taskId);
      this.checkStateCount(this.url.checkStateCount, this.taskId);
      this.abnormalCreateTime(this.taskId);

    },
    abnormalCreateTime(infoId) {
      let taskDate = this.taskDate;
      let queryParam = {
        "startDate": taskDate[0],
        "endDate": taskDate[1],
        "infoId": infoId
      }
      getAction(this.url.abnormalCreateTime, queryParam).then(res => {
        if (res.success) {
          let data = [];
          let resultList = res.resultList;
          for (var i in resultList) {
            let resultListElement = resultList[i];
            let time = resultListElement.createTime;
            let count = parseInt(resultListElement.count);
            data.push([time, count])
          }
          let dateList = data.map(function (item) {
            return item[0];
          });
          let valueList = data.map(function (item) {
            return item[1];
          });
          this.abnormalCreateTimetrend(dateList, valueList)
        }
      }).finally(() => {

      })

    },

    abnormalCreateTimetrend(dateList, valueList) {
      let option = {
        title: {
          text: '稽核异常数量',
          left: 'center',

        },
        lineStyle: {
          color: '#5a6fc0'
        },

        backgroundColor: {
          type: 'pattern',
          image: this.canvas,
          repeat: 'repeat'
        },
        visualMap: [
          {
            show: false,
            type: 'continuous',
            seriesIndex: 0,
            min: 0,
            max: 400
          },
          {
            show: false,
            type: 'continuous',
            seriesIndex: 1,
            dimension: 0,
            min: 0,
            max: dateList.length - 1
          }
        ],
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['稽核异常']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dateList
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '异常数',
            type: 'line',
            stack: 'Total',
            data: valueList
          }
        ]
      };

      this.$abnormalCreateTimeTrend = echarts.init(document.getElementById('abnormalCreateTimeTrend'))
      this.$abnormalCreateTimeTrend.setOption(option)

    },


    checkStateCount(url, taskId) {
      let taskDate = this.taskDate;
      let queryParam = {
        "startDate": taskDate[0],
        "endDate": taskDate[1],
        "infoId": taskId
      }
      getAction(url, queryParam).then(res => {
        if (res.success) {
          let resultList = res.resultList;
          let pieData = [];
          let histogramSource = ['资料驳回分布']
          let dimensions = ['product']

          for (var i in resultList) {
            let resultListElement = resultList[i];
            let name = resultListElement.name;
            let state = resultListElement.state;
            let count = resultListElement.count;
            if (state === "2") {
              var abnormalMapElement = this.abnormalMap[name];
              if (abnormalMapElement != null && abnormalMapElement != undefined) {
                pieData.push({
                  "name": abnormalMapElement,
                  "value": count
                })
                dimensions.push(abnormalMapElement.toString())
                histogramSource.push(parseInt(count));
              }
            }
          }
          this.checkStatePie(pieData);
          this.checkStateHistogram(dimensions, histogramSource)


        }
      }).finally(() => {

      })
    },

    checkStateHistogram(dimensions, source) {

      let option = {
        backgroundColor: {
          type: 'pattern',
          image: this.canvas,
          repeat: 'repeat'
        },
        legend: {},
        tooltip: {},
        dataset: {
          source: [
            dimensions,
            source
          ]
        },
        xAxis: {type: 'category'},
        yAxis: {},
        // Declare several bar series, each will be mapped
        // to a column of dataset.source by default.
        series: [{type: 'bar'}, {type: 'bar'}, {type: 'bar'}]
      };
      this.$abnormalCheckHistogram = echarts.init(document.getElementById('statusAuditHistogram'))
      this.$abnormalCheckHistogram.setOption(option)

    },
    checkStatePie(data) {

      let option = {
        tooltip: {
          trigger: 'item'
        },
        backgroundColor: {
          type: 'pattern',
          image: this.canvas,
          repeat: 'repeat'
        },
        /*title: [
          {
            text: '异常类型占比',
            //subtext: '总计 ' + builderJson.all + " 稽核通过 " + builderJson.charts["稽核通过"],
            left: '25%',
            textAlign: 'center'
          },
        ],*/
        legend: {
          top: '5%',
          left: 'center'
        },
        series: [
          {
            name: '',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '40',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: data
          }
        ]
      };
      this.$abnormalCheckPie = echarts.init(document.getElementById('statusAuditPie'))
      this.$abnormalCheckPie.setOption(option)
    },


    //树点击事件
    onTreeNodeSelect(id) {
      if (id && id.length > 0) {
        if (id == "all") {
          this.statusRefuse();
          this.checkStateCount(this.url.checkStateCount);
          this.abnormalCreateTime();
          this.taskId = null;
          return;
        }
        let split = id[0].split("key-");
        if (split.length == 2) {
          let taskId = split[1];
          this.statusRefuse(taskId);
          this.checkStateCount(this.url.checkStateCount, taskId);
          this.abnormalCreateTime(taskId);
          this.taskId = id;
        }
      }
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
    },

    taskDateList(taskData) {
      getAction(this.url["dateList"]).then(res => {
          if (res.success) {
            let result = res.result;
            let years = result[0];
            let months = result[1];
            let YearLevel = {}
            let monthLevel = {}

            for (var i in years) {
              let year = years[i].yearTime;
              let children = {
                "title": year,
                "key": year,
                "children": []
              }
              YearLevel[year] = children
            }

            for (var j in months) {
              let month = months[j].monthTime;
              let splitElement = month.split("-")[0];
              let children = {
                "title": month,
                "key": month,
                "children": []
              }
              YearLevel[splitElement].children.push(children)
            }

            for (var k in taskData) {
              let taskDatum = taskData[k];
              let taskStartTime = taskDatum.taskStartTime;
              if (taskStartTime != null && taskStartTime != undefined) {
                let children = {
                  "title": taskDatum.taskName + "[" + taskDatum.customerCount + "]",
                  "key": "key" + "-" + taskDatum.id,
                  "isLeaf": true,
                }
                let strings = taskStartTime.split("-");
                let year = strings[0];
                let month = strings[0] + "-" + strings[1];
                for (var z in YearLevel[year].children) {
                  let title = YearLevel[year].children[z].title;
                  if (title == month) {
                    YearLevel[year].children[z].children.push(children);
                    break;
                  }
                }
              }
            }

            let allChildren = {
              "title": "全部任务",
              "key": "all",
              "children": []
            }

            for (var u in YearLevel) {
              this.treeData.push(YearLevel[u])
            }
            this.treeData.push(allChildren)
            this.treeData = this.treeData.reverse();


          }
        }
      )
    },

    //任务列表数据
    taskList() {
      let queryParam = {
        pageNo: 1,
        pageSize: 1000000,
      }
      getAction(this.url["taskList"], queryParam).then(res => {
        if (res.success) {
          let records = res.result.records;
          //稽核任务菜单
          this.taskDateList(records);
        }
      })


    },


    //查询各类型稽核进度
    statusRefuse(taskId) {
      let taskDate = this.taskDate;
      let queryParam = {
        "startDate": taskDate[0],
        "endDate": taskDate[1],
        "taskId": taskId
      }
      if (taskDate.length = 2) {
        getAction(this.url["statusRefuse"], queryParam).then(res => {
          if (res.success) {
            let builderJson = {};
            let columnDate = {};
            let pieDate = {};
            let all = 0;
            let resultList = res.resultList;
            for (var i in resultList) {
              let resultListElement = resultList[i];
              let status = this.statusMap[resultListElement.checkState];
              if (status != undefined && status != null) {
                all = all + resultListElement.count
                columnDate[status] = resultListElement.count
              }
            }
            builderJson = {
              "all": all,
              "charts": columnDate,
              "ie": 9743
            }
            this.statusRefusePie(builderJson)
          }
        })
      }
    },
    statusRefusePie(builderJson) {
      if (builderJson.charts["稽核通过"] == null || builderJson.charts["稽核通过"] == undefined) {
        builderJson.charts["稽核通过"] = 0;
      }
      if (builderJson.charts["未完善"] == null || builderJson.charts["未完善"] == undefined) {
        builderJson.charts["未完善"] = 0;
      }
      if (builderJson.charts["待稽核"] == null || builderJson.charts["待稽核"] == undefined) {
        builderJson.charts["待稽核"] = 0;
      }
      if (builderJson.charts["待整改"] == null || builderJson.charts["待整改"] == undefined) {
        builderJson.charts["待整改"] = 0;
      }

      this.toImproveUser = builderJson.charts["未完善"];
      this.toBeAudited = builderJson.charts["待稽核"];
      this.tobeRectified = builderJson.charts["待整改"];
      this.auditPassed = builderJson.charts["稽核通过"];

      let option = {
        backgroundColor: {
          type: 'pattern',
          image: this.canvas,
          repeat: 'repeat'
        },
        tooltip: {},
        title: [
          {
            text: '稽核完成进度',
            subtext: '总计 ' + builderJson.all + " 稽核通过 " + builderJson.charts["稽核通过"],
            left: '25%',
            textAlign: 'center'
          },
          {
            text: '稽核类型占比',
            subtext: '总计 ' + builderJson.all,
            left: '75%',
            textAlign: 'center'
          }
        ],
        grid: [
          {
            top: 50,
            width: '50%',
            bottom: '5%',
            left: 10,
            containLabel: true
          },
          {
            top: 50,
            width: '50%',
            bottom: '5%',
            left: 10,
            containLabel: true
          }

        ],

        xAxis: [
          {
            type: 'value',
            max: builderJson.all,
            splitLine: {
              show: false
            }
          }
        ],
        yAxis: [
          {
            type: 'category',
            data: Object.keys(builderJson.charts),
            axisLabel: {
              interval: 0,
              rotate: 30
            },
            splitLine: {
              show: false
            }
          }
        ],
        series: [
          {
            type: 'bar',
            stack: 'chart',
            z: 3,
            label: {
              position: 'right',
              show: true
            },
            data: Object.keys(builderJson.charts).map(function (key) {
              return builderJson.charts[key];
            }),
            itemStyle: {
              normal: {
                //这里是颜色
                color: function (params) {
                  //注意，如果颜色太少的话，后面颜色不会自动循环，最好多定义几个颜色
                  var colorList = ['#5c6fc4', '#f0be47', '#d2232c', '#81c463', '#BBFFAA', '#749f83', '#ca8622'];
                  return colorList[params.dataIndex]
                }
              }
            }
          },
          {
            type: 'bar',
            stack: 'chart',
            silent: true,
            itemStyle: {
              color: '#eee'
            },
            data: Object.keys(builderJson.charts).map(function (key) {
              return builderJson.all - builderJson.charts[key];
            }),


          },

          {
            type: 'pie',
            radius: [0, '80%'],
            center: ['75%', '55%'],
            data: Object.keys(builderJson.charts).map(function (key) {
              return {
                name: key,
                value: builderJson.charts[key]
              };
            }),
            itemStyle: {
              normal: {
                //这里是颜色
                color: function (params) {
                  //注意，如果颜色太少的话，后面颜色不会自动循环，最好多定义几个颜色
                  var colorList = ['#5a6fc0', '#f0be47', '#d2232c', '#81c463', '#BBFFAA', '#749f83', '#ca8622'];
                  return colorList[params.dataIndex]
                }
              }
            }
          },


        ]
      };

      this.$statusRefusePie = echarts.init(document.getElementById('statusRefusePie'))
      this.$statusRefusePie.setOption(option)
    },

    getRecentDay: function (n) {
      let day = moment(new Date())
        .subtract(n, "days")
        .format("YYYY-MM-DD");
      return day;
    },

  }
}
</script>
<style scoped>

</style>