<template>
  <div class="label-sta" >
    <div class="top-a">
      <div class="my-blue-title">数据来源统计</div>
      <div class="forms"> <diy-el-form :span="24" :forms="qualityCheckStaUnitFilterForm()" v-model:model-form="unitForm"/></div>
      <div class="echarts" ref="sourceRef"></div>
    </div>
    <div class="bottom">
      <div class="bottom-left">
        <div class="my-blue-title">质检情况统计</div>
        <div class="echarts" ref="qualityCheckStaRef"></div>
      </div>
      <div class="bottom-right">
        <div class="my-blue-title">问题类型统计</div>
        <div class="echarts" ref="qualityCheckQuestionTypeRef"></div>
      </div>
    </div>
  </div>
</template>

<script>
import DiyElForm from "@/components/common/DiyElForm.vue";
import {onBeforeMount, ref, watch} from "vue";
import {qualityCheckStaUnitFilterForm} from "@/data/all-forms";
import {
  getQualityCheckQuestionTypeCheckOptions,
  getQualityCheckStaSituation,
  getQualityStaSourceSta,
  getQualityStaSourceStaUnit
} from "@/service/data-quelity-check/quality-check-sta";
import {isEmptyCheck} from "@/unit/validate";
import {
  setDataQualityStaSourceEcharts,
  setDataQualityStaSourceEchartsUnit,
  setQualityCheckStaEcharts, setQualityQuestionTypeStaEcharts
} from "@/echarts/option";
import {useRootStore} from "@/stores/useStore";
import {addMonths, getDateToString} from "@/unit/time";
import Header from "@/view/home/c-cpns/Header.vue";
import {showMessage} from "@/unit/element-ui/tip";

export default {
  name: "QualityCheckSta",
  components: {Header, DiyElForm},

  setup(props,{emit}){
    const echartsA  =ref(null)
    const sourceRef = ref(null)
    const qualityCheckStaRef = ref(null)
    const qualityCheckQuestionTypeRef = ref(null)
    const unitForm = ref({

    })
    watch(() => unitForm.value.UNIT_CODE,(val) => {
      getSourceData()
      getQualitySta()
    })
    function getQuestionTypeSta() {
      getQualityCheckQuestionTypeCheckOptions().then(res => {
        let date = res.msg;
        let assingnment_data = []
        let codeData = date[0].Rows;
        let colorList = ['#68B5FB', '#02F2F3','#C0FE5D', '#F3E58D', '#D45A49'];
        for(let i = 0 ; i < codeData.length ; i++){

          let tempJson = {
            "name":codeData[i]["NAME"],
            "value":codeData[i]["ERROR_COUNT"],
          };

          assingnment_data.push(tempJson);
          setQualityQuestionTypeStaEcharts(qualityCheckQuestionTypeRef.value,colorList,assingnment_data)
        }
      })
    }
    function getLastYearMonth() {
      // 1、封装方法 var result = [];
      let result = []
      for (let i = 0; i < 13; i++) {
        let d = new Date();
        d.setDate(1);
        d.setMonth(d.getMonth() - i);
        let m = d.getMonth() + 1;
        m = m < 10 ? "0" + m : m; //在这里可以自定义输出的日期格式
        result.push(d.getFullYear() + "-" + m); //result.push(d.getFullYear() + "年" + m + '月');
      }
      return result.reverse(); // return 创建好的日期数组
    }
    function getQualitySta(){
      getQualityCheckStaSituation(unitForm.value.UNIT_CODE).then(res => {
        let date = res.msg;
        let codeData = date[0].Rows;
        let zjqktjMonth = {}
        let oneYearMonths = getLastYearMonth();
        for(let i=0;i<oneYearMonths.length;i++){
          let obj = {
            ERROR_NUM: 0,
            INSPECTION_NUM: 0,
            MONTH: oneYearMonths[i],
          }
          zjqktjMonth[oneYearMonths[i]] =obj;
        }
        for(let i = 0 ; i < codeData.length ; i++){
          zjqktjMonth[codeData[i]["MONTH"]] = codeData[i];
        }

        let echartData=[];
        for(var key in zjqktjMonth){
          var temp = {};
          if(zjqktjMonth[key].length == 0){
            temp["name"] = key;
            temp["value1"] = 0;
            temp["value2"] = 0;
            echartData.push(temp);
            continue;
          }

          temp["name"] = key;
          temp["value1"] = zjqktjMonth[key]["INSPECTION_NUM"];
          temp["value2"] = zjqktjMonth[key]["ERROR_NUM"];
          echartData.push(temp);
        }
        let bgColor = "#fff";
        let color = [
          "#0373ca",
          "#ff120c",
          "#FFC005",
          "#FF515A",
          "#8B5CFF",
          "#00CA69"
        ];

        let xAxisData = echartData.map(v => v.name);
        let yAxisData1 = echartData.map(v => v.value1);
        let yAxisData2 = echartData.map(v => v.value2);

        const hexToRgba = (hex, opacity) => {
          let rgbaColor = "";
          let reg = /^#[\da-f]{6}$/i;
          if (reg.test(hex)) {
            rgbaColor = `rgba(${parseInt("0x" + hex.slice(1, 3))},${parseInt(
                "0x" + hex.slice(3, 5)
            )},${parseInt("0x" + hex.slice(5, 7))},${opacity})`;
          }
          return rgbaColor;
        }
        setQualityCheckStaEcharts(qualityCheckStaRef.value,xAxisData,bgColor,yAxisData1,yAxisData2)
      })
    }
    function getSourceData() {

      let url = unitForm.value.UNIT_CODE?getQualityStaSourceStaUnit:getQualityStaSourceSta
      let params = {}
      if (unitForm.value.UNIT_CODE){

        let endDate = getDateToString(new Date());
        let startDate = addMonths(new Date(),-12);
        params = {
          "START_DATE":startDate,
          "END_DATE":endDate,
          UNIT_CODE: unitForm.value.UNIT_CODE
        }

      }
      url(params).then(res => {
        if (!res.msg[0].Rows[0]){
          echartsA.value.clear()
          return
        }
        let unitMap = {}
        useRootStore().allSelectUnit.forEach(i=> {
          if (i.value){
            unitMap[i.value] = i.label
          }
        })
        if (!unitForm.value.UNIT_CODE){
          let date = res.msg;
          let codeData = date[0].Rows;
          let sjlytjData = {};
          sjlytjData["CODE"]=[];
          sjlytjData["INSPECTION_NUM"]=[];
          sjlytjData["ERROR_NUM"]=[];
          for (let i = 0 ; i < codeData.length ; i++) {
            if(isEmptyCheck(codeData[i]["CODE"])){
              continue;
            }
            sjlytjData["CODE"].push(codeData[i]["CODE"]);
            sjlytjData["INSPECTION_NUM"].push(codeData[i]["INSPECTION_NUM"]);
            sjlytjData["ERROR_NUM"].push(codeData[i]["ERROR_NUM"]);
            if(sjlytjData["INSPECTION_NUM"].length >= 10){
              break;
            }
          }

          let code = sjlytjData["CODE"];
          let inspection_num = sjlytjData["INSPECTION_NUM"];
          let error_num = sjlytjData["ERROR_NUM"];
          echartsA.value?.clear()
           echartsA.value = setDataQualityStaSourceEcharts(sourceRef.value,code,inspection_num,unitMap,error_num)

          echartsA.value.on('click',function (val){
            if (unitForm.value.UNIT_CODE  === val.name){
              unitForm.value.UNIT_CODE  = ''
            }else {
              unitForm.value.UNIT_CODE = val.name
            }

          })

        }
        else {
          let sjlytjUnitData = {}
          let date = res.msg;
          let codeData = date[0].Rows;
          for (let i = 0 ; i < codeData.length ; i++) {
            sjlytjUnitData[codeData[i]["MONTH"]] = codeData[i];
          }
          let month =[];
          let inspection_num = [];
          let error_num = [];
          for(let key in sjlytjUnitData){
            if(sjlytjUnitData[key].length == 0){
              month.push(key);
              inspection_num.push(0);
              error_num.push(0);
              continue;
            }
            month.push(key);
            inspection_num.push(sjlytjUnitData[key]["INSPECTION_NUM"]);
            error_num.push(sjlytjUnitData[key]["ERROR_NUM"]);
          }
           echartsA.value?.clear()
           echartsA.value =   setDataQualityStaSourceEchartsUnit(sourceRef.value,inspection_num,error_num,month)
          echartsA.value.on('click',function (val){
            unitForm.value.UNIT_CODE  = ''

          })
        }


      }).catch(error => {
        showMessage({
          type:'error',
          message:'数据来源情况数据获取失败'
        })
        return
      })
    }
    onBeforeMount(() => {
      getSourceData()
      getQualitySta()
      getQuestionTypeSta()
    })

    return {
     unitForm,
      qualityCheckStaUnitFilterForm,
      sourceRef,
      qualityCheckStaRef,
      getQuestionTypeSta,
      qualityCheckQuestionTypeRef
    }
  }
}
</script>

<style scoped lang="scss">
.label-sta{

  >div{
    flex: 1;
    overflow: hidden;
  }
  .c{
    padding: 15px;
  }
  .forms{
    position: absolute;
    right: 20px;
    top: 20px;
    max-width: 400px;
  }
  display: flex;
  flex-direction: column;
  height: 100% !important;
  background: #D4E6FF !important;

  .bottom{
    .bottom-left{

      margin-right: 10px;
    }
    .bottom-left,.bottom-right{

      flex: 1;
      display: flex;
      flex-direction: column;
      .echarts{
        flex: 1;
        overflow: hidden;
      }
      flex-shrink: 0;
      background-color: #fff;
      box-shadow: 0 0 10px 1px #e9e9e9;
    }


    display: flex;
    justify-content: space-between;
  }
  .top-a{
    position: relative;
    display: flex;
    flex-direction: column;
    .echarts{
      margin: 15px;
      flex: 1;
      overflow: hidden;
    }
    background-color: #fff;
    margin-bottom: 30px;
    height: 500px;
    box-shadow: 0 0 10px 1px #e9e9e9;
  }
}

</style>
