<template>
  <div :style="{display:'inline-block',height:'500px',width:'680px'}" ref="chartsRef" >
  </div>
</template>
<script setup>
import {reactive, onMounted, ref,watch} from "vue";
import {getXAxis,getNongDataTotal,getSeries,getYAxisParams,getTwoMonthDateStr,getNSData} from "./common";
import * as echarts from "echarts";
let myChart = null;
let props = defineProps({
  title: {//标题，物候期
    type: String,
    default: "",
  },
  targetField:{//物候期指标字段
    type: String,
    default: "",
  },
  targetName:{//物候期指标名称
    type: String,
    default: "",
  },
  last:{
    type:Boolean,
    default:false
  },
  bgColor:{
    type:String,
    default:'#F5F5F5'
  },
  treeId:{
    type:Number,
    default:null
  },
  currentPeriod:{
    type: Object,
    default: new Object()
  },
})
const chartsRef = ref(null);
const treeGrowData = ref(null);
let intFields = ['flowerLength','yield'];
let percent = true;
let nzNames = [];
let numberInterval = null;
const nzv = ref([]);
const treeNSData = ref([]);

const option = reactive({
  backgroundColor:props.bgColor,
  "title": {
    "text": "",
    show:true,
  },
  animation: true,
  "tooltip": [{
    "trigger": "item",
    formatter:function(data){
      if(data.data.value < 0){
        return data.seriesName;
      }
      if(percent){
        return data.name+"<br/>"+data.seriesName+" : "+(data.data.value * 100).toFixed(0) + "%";
      }else{
        return data.name+"<br/>"+data.seriesName+" : "+(data.data.value).toFixed(2);
      }
      
    }
  }],
  "grid": {
    "left": "3%",
    "right": "3%",
    show: true,
    z: 0,
    containLabel: true,
    backgroundColor: "rgba(0,0,0,0)",
    borderWidth: 1,
    borderColor: "#ccc"
  },
  "xAxis": {
    "type": "category",
    "boundaryGap": true,
    "data": [],
    axisLabel: {
      formatter: function (value, index) {
        // 返回自定义格式的标签
        return value.substr(5,10);
      }
    },
    minorTick: {
      show: false
    },
    minorSplitLine: {
      show: true
    },
    splitLine: {
      show: true
    }
  },
  "yAxis": {
    "type": "value",
    interval:0.1,
    min: -1, // 自定义最小值
    max: 1, // 自定义最大值
    axisLabel: {
      show: true,
      interval: 'auto',
      formatter: function(value,index){
        if(value < 0){
          for(let i=0;i< nzNames.length;i++){
            if((value * 100).toFixed(0) == (nzv.value[i] * 100).toFixed(0)){
              return nzNames[i];
            }
          }
          return  "";
        }else{
          if(percent){
            value = (value * 100).toFixed(0)
            if(value % 20 == 0){
              return value + "%";
            }
          }else{
            if(numberInterval != null && Math.ceil(value) % numberInterval == 0){
              return Math.ceil(value);
            }else{
              return "";
            }
          }
        }
      }
    }
  },
  "series": [
  ]
});
watch(() => props.currentPeriod, (newVal, oldVal) => {
  getGrowData(props.treeId,function(){
    //不是整数的指标，最小值为0
    getTreeNSData(function(){
      refreshChart();
    });
  });
})
function changeType(){
  getTreeNSData(function(){
    refreshChart();
  });
}

function refreshChart(){
  //y轴
  //不是整数的指标，最小值为0
  if(intFields.indexOf(props.targetField) != -1){
      percent = false;
    }else{
      percent = true;
    }
    let [min1,max1,interval1,nzNames1,nzv1] = getYAxisParams(props.targetField,props.currentPeriod,treeGrowData.value,percent)
    option.title.text = props.title;
    nzNames = nzNames1;
    nzv.value = nzv1;
    option.yAxis.interval = interval1;
    option.yAxis.min = min1;
    option.yAxis.max = max1;

    numberInterval = interval1*3;
    //x轴
    option.xAxis.data = getXAxis();
    //series
    let series = getSeries(props.currentPeriod,props.targetName,props.targetField,treeGrowData.value);
    // option.series = series;
    console.log(series);
    //农事活动
    let nsSeries = getNSData(treeNSData.value,props.currentPeriod,nzv.value);
    option.series = series.concat(nsSeries);
    console.log(JSON.stringify(option));
    if(myChart){
      myChart.clear();
      myChart.setOption(option);
    }
}
async function getTreeNSData(callback){
  if(treeNSData.value  && treeNSData.value.length != 0){
    callback();
    return;
  }
  let forms2 = {treeId:props.treeId,dateRange:getTwoMonthDateStr(),direction:0,sortField:['startDate'],page:1,limit:10000}
  let {code,data} = await VE_API.tree.siteList(forms2);
  if(code == 0){
    treeNSData.value = getNongDataTotal(data);
    callback();
  }
}
async function getGrowData(treeId,callback){
  if(treeGrowData.value !=  null){
    callback();
  }
  let forms = new FormData();
  forms.append("treeId",treeId);
  let list = [];
  //生长数据列表
  let {code,data} = await VE_API.tree.treeGrowData(forms);
  if(code == 0){
    list = data;
  }
  treeGrowData.value = list;
  callback();
}
const autoWidth = ref(option.xAxis.data.length * 60)

onMounted(async ()=>{
  myChart = echarts.init(chartsRef.value,{width:"90%"});
})
defineExpose({
  changeType
})
</script>
