<template>
  <div>
    <border6 ref="refborder3">
      <template v-slot>
        <div ref="pipe" class="pipebox"></div>
      </template>
    </border6>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, nextTick, onMounted, reactive, ref } from "vue";
import { EDataPerson, EDataPersonItem } from "@/type/realtimeSecurity";
// import border3 from "@/components/borderBox/border3.vue";
import border6 from "@/components/borderBox/border6.vue";
import { useI18n } from 'vue-i18n'
let {t} = useI18n();
const { proxy } = getCurrentInstance() as any;
let props = defineProps<{
  title: string;
}>();
let pipe = ref();

let refborder3 = ref();

const echartsData = reactive<EDataPerson>({
  pipe: {
    div: null,
    data: null,
    title: "",
    box: null,
  },
});

const setData = (value: any, type: number) => {
  
  let x = [];
  let y = [];
  let sumx = [];
  value.listData.forEach((res) => {
    x.push(res.name);
  });
  let newx = [...new Set(x)];
  newx.forEach((ele) => {
    let count = 0;
    value.listData.forEach((res) => {
      if (ele == res.name) {
        count++;
      }
    });
    sumx.push({ name: ele, val: 1, sum: count });
    count = 0;
  });

  sumx.forEach((ele) => {
    value.listData.forEach((res) => {
      let color1 = rgb();
      if (ele.name == res.name)
        y.push({
          name: res.devName,
          value: [
            newx.map((item) => item).indexOf(res.name),
            0,
            res.value,
            ele.val++,
            ele.sum,
          ],
        });
    });
  });

  //   let x = []
  //   let y =[]
  //   value.listData.forEach((res) => {
  //     x.push(res.name);
  //     y.push(res.devName);
  //   });
  //     let newx=[...new Set(x)]
  //     x=newx
  // let nseries=[]
  //   value.listData.forEach((res) => {
  //     y.forEach(ele=>{
  //       let ydata=[]
  //       x.forEach(ele2=>{
  //         if(res.name==ele2&&res.devName==ele){
  //           ydata.push(res.value)
  //         }else{
  //           ydata.push(0)
  //         }
  //       })
  //       if(!ydata.every(e=>e==0)){
  //         nseries.push({
  //       name: ele,
  //       type: 'custom',
  //       data: ydata,
  //       barWidth:function (params){
  //         console.log(params);

  //       },
  //       renderItem:renderItem1
  //     },)
  //       }

  //     })
  //   });
  // console.log(nseries);

  // let x = ['product'];
  // let y = [];
  // let server =[]
  // value.listData.forEach((res) => {
  //   x.push(res.devName);
  //   y.push(res.name)
  // });
  // let newy=[...new Set(y)]
  // y=[]
  // newy.forEach((res)=>{
  //     y.push({'product':res})
  //   })
  // value.listData.forEach((res) => {
  //   y.forEach(ele=>{
  //     if(res.name==ele.product){
  //       ele[res.devName]=res.value
  //     }
  //   })

  // });
  // x.forEach(res=>{

  //   y.forEach(ele=>{
  //     for(let key in ele){
  //       if(key==res&&key!='product'){
  //         server.push({type:'bar',renderItem:renderItem1})
  //       }
  //     }
  //   })

  // })

  echartsData.pipe!.div = pipe.value;
  echartsData.pipe!.title = props.title;
  echartsData.pipe!.data = {
    title: {
      text: echartsData.pipe!.title,
      show: true,
      textStyle: {
        color: "#fff",
        fontSize: 20,
      },
      top:'1%'
    },
    grid: {
      top: "15%",
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    tooltip: {
      trigger: "item",
      axisPointer: {
        type: "shadow",
      },
    },
    legend: {
      top: "5%",
    },
    xAxis: {
      type: "category",
      data: newx,
    },
    yAxis: {
      type: "value",
      // axisLabel: {
      //   formatter: "{value} mpa",
      // },
    },
    //   dataset:{
    //   dimensions: x,
    //   source: y
    // },
    // series:server
    series: [
      {
        type: "custom",
        renderItem: renderItem1,
        itemStyle:{
          color:function (params) {
              var index_color = params.value[2];              
              if (index_color >= value.top.value) {
                return "#FF6E76";
              } else {
                return "#4992FF";
              }
            },

        } ,
        label: {
          show: true,
          normal: {
            formatter: function (params) {
              return params.value[2]
            },
            show: true,
            position: "top",
            textStyle: {
              color: "rgb(255,255,255,0.9)",
            },
          },
        },
        tooltip: {
          trigger: "item",
          axisPointer: {
            type: "shadow",
          },
          formatter: function (params) {
              return !(params.value[2] == "0.0") ? params.name+":"+params.value[2] + "Mpa" : "";
            },
        },
        // labelLayout: (params, api) => {
        //   console.log(params, api);

        //   return {
        //     x: params.rect.x ,
        //     y: params.rect.y + params.rect.height / 2,
        //     verticalAlign: "middle",
        //     align: "left",
        //     text:'1'
        //   };
        // },
        // itemStyle: { normal: { opacity: 0.8 } },
        encode: {
          y: 2,
          x: 0,
          tooltip: [0, 1, 2], //映射到提示框中的维度
          itemName: 3,
        },
        data: y,
      },
      {
        type: "bar",
        name:`${t('messages.normal_Tip')}(0mpa - `+value.top.value+"mpa)",
        color:'#4992FF'
      },
      {
        type: "bar",
        name:`${t('messages.abnormal_Tip')}(${value.top.value}mpa ${t('messages.abnormal_Tip_yishang')})`,
        color:'#FF6E76'
      },
    ],
  };
    change(echartsData.pipe);
};

let renderItem1 = (params, api) => {
  // console.log(params,"?????????????????");

  let categoryIndex = api.value(0);
  let start = api.coord([categoryIndex, api.value(1)]);
  let end = api.coord([categoryIndex, api.value(2)]);
  let width = api.size([0, api.value(4)])[0] * 0.6;

  const num = api.value(4); // 每个系列柱子数
  const currentIndex = api.value(3);
  const isOdd = num % 2 === 0;
  const midN = isOdd ? num / 2 : (num + 1) / 2;

  var rect = null;

  width = width / num;

  let rectX = start[0] - width / 2;

  const FIXED_WIDTH = 2; // 柱子间距

  // 数据处理，结构为 { itemStyle: { normal: { color: 'lightgreen' } }, name: '2011', value: [0, 0, 150, 2, 5] }
  // 其中value 分为五个维度，分别为{系列项}（从0开始）、y轴起始值(均为0)、实际值、同系列中索引值（从1开始）、同系列数据项总数

  if (num > 1) {
    if (isOdd) {
      if (currentIndex <= midN) {
        // 中位数左侧
        rectX =
          start[0] -
          width / 2 -
          width / 2 +
          (currentIndex - midN) * width -
          FIXED_WIDTH * (midN + 1 - currentIndex);
      } else {
        // 中位数右侧
        rectX =
          start[0] -
          width / 2 +
          width / 2 +
          (currentIndex - midN - 1) * width +
          FIXED_WIDTH * (currentIndex - midN);
      }
    } else {
      rectX =
        start[0] - width / 2 + (currentIndex - midN) * (width + FIXED_WIDTH);
    }
  }

  rect = {
    type: "rect",
    shape: proxy.$echarts.graphic.clipRectByRect(
      { x: rectX, y: end[1], width: width, height: start[1] - end[1] },
      {
        x: params.coordSys.x,
        y: params.coordSys.y,
        width: params.coordSys.width,
        height: params.coordSys.height,
      }
    ),
    style: api.style(),
  };

  return rect;
};
let toltip = (params) => {
};
function rgb() {
  //rgb颜色随机
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  return `rgb(${r},${g},${b})`;
}

const change = (item: EDataPersonItem) => {
  let Ebox;
  if (!item.box) {
    Ebox = proxy.$echarts.init(item.div, "dark");
  } else {
    Ebox = item.box;
  }
  Ebox.setOption(item.data);
  console.log(echartsData.pipe.box,"我拿到了数据");
  item.box = Ebox;
  
  
};
const updata = (item: EDataPersonItem) => {
  item.box.setOption(item.data);
};
function setchartWH(width: any, height: any) {
  pipe.value.style.height = height + "px";
  pipe.value.style.width = width + "px";
  console.log(echartsData.pipe.box,"我执行了");
  
  refborder3.value.resetWH();
  if (echartsData.pipe.box) {
    console.log(width,"我执行了2");
    nextTick(()=>{
      echartsData.pipe.box.resize();
    })
  }
}
onMounted(() => {});

// return{setchartWH}
defineExpose({
  setchartWH,
  setData,
});
</script>

<style scoped>
.pipebox{
  margin-top: 5px;
}
</style>
