<template>
    <div style="height: 100vh;">
      <a-layout id="components-layout-demo-custom-trigger">
        <a-layout-sider  :trigger="null" collapsible >
          <a-menu
              mode="inline"
              :inlineCollapsed="false"
              multiple
              :selectable="false"
              :openKeys.sync="openMenu"
              style="height: 100%"
          >
            <a-sub-menu v-for="ld in letData" :key="ld.key">
              <span slot="title">{{lang=='CN'?ld.cat_name:ld.cat_ename}}</span>
              <a-menu-item :key="String(chki)" v-for="(chk,chki) in ld.children">
                <a-checkbox :style="radioStyle" v-model="chk.checked" @change="changeChked(ld)">{{lang=='CN'?chk.cat_name:chk.cat_ename}}</a-checkbox>
              </a-menu-item>
            </a-sub-menu>
          </a-menu>
        </a-layout-sider>
        <a-layout style="height: 100%;">
          <a-layout-header style="background: #fff; padding: 0">
            <a-menu @click="getNav" forceSubMenuRender v-model="actNav" theme="light" mode="horizontal" :style="{ lineHeight: '64px' }" >
              <a-menu-item disabled>{{ $t('wu-zhi-lei-bie') }}</a-menu-item>
              <a-menu-item  v-for="n in nav" :key="n.key">
                {{lang=='CN'?n.cat_name:n.cat_ename}}
              </a-menu-item>
            </a-menu>
          </a-layout-header>
          <a-layout-content v-if="parseInt(actNav[0]) == 0" ref="contents"   :style="{ margin: '24px 16px', padding: '24px', background: '#fff',height:'100%', minHeight: '280px',width:'100%' }">
            <div >
              <a-row type="flex" justify="center">
                <a-col>
                  <a-select @change="allChange" v-model="selected" :options="options" style="width: 150px;" />
                </a-col>
                <a-col :flex="1" :offset="1">
                  <a-select @change="allChangeNorm" v-model="norm" :options="norms" style="width: 120px;" />
                </a-col>
              </a-row>
              <div id="comcanvas" :style="{minWidth: '950px',height: '550px'}"></div>
            </div>
          </a-layout-content>
          <a-layout-content ref="contents"  v-if="actNav[0] != 0" :style="{ margin: '24px 16px', padding: '24px', background: '#fff',height:'100%', minHeight: '280px',width:'100%' }">
            <div style="display: flex;flex-direction: row;flex-wrap: wrap;">
              <div v-for="(chats,chati) in chat" style="width: 50%;">
                <a-row type="flex" justify="center">
                  <a-col>
                    <h3>{{ chats.name }}</h3>
                  </a-col>
                  <a-col :flex="1" :offset="1">
                    <a-select v-if="chats.select.length>0" @change="changeChat(chati,chats.select,chats.selected)" :options="chats.select" v-model="chats.selected" style="width: 120px;" />
                  </a-col>
                </a-row>
                <div class="lineChart" :style="{minWidth:'470px',height:'550px'}"></div>
              </div>
            </div>
          </a-layout-content>
          <a-layout-content>
            <STable
                ref="table"
                size="default"
                rowKey="key"
                :lang="lang"
                :columns="columns"
                :data="loadData"
                :alert="false"
                :showPagination="false"
                :scroll="{ x: 'calc(700px + 50%)', y: 500 }"
                bordered
            >
              <template v-for="(obj,obji) in columns">
                              <span :slot="obj.type">
                                  {{ lang=='CN'?obj.titles:obj.etitle }}
                              </span>
                <template v-for="child in obj.children">
                                  <span :slot="child.type">
                                      {{ lang=='CN'?child.titles:child.etitle }}
                                  </span>
                </template>
  
              </template>
              <span slot="action" slot-scope="text, record">
                    <template>
                        <a @click="colFind(record)" v-auth="`colFind`">查看</a>
                        <a-divider type="vertical" />
                        <a @click="colEdit(record)" v-auth="`colEdit`">编辑</a>
                        <a-divider type="vertical" />
                        <a @click="colDel(record)" v-auth="`colDel`">删除</a>
                    </template>
                </span>
            </STable>
          </a-layout-content>
        </a-layout>
      </a-layout>
      <col-form ref="colModal" :lang="lang" :list="colData" :isSave="isSave" :visible="visible" :loading="confirmLoading" :model="mdl" @drawerKo="handleKo" @drawerOk="handleOk" />
      <a-modal v-model="showPie" width="1000px" height="450px">
        <div class="container">
          <div class="data-list">
            <div class="item-header">
              <div>样品名</div>
              <div>数值</div>
              <div>占比</div>
            </div>
            <div class="list">
              <div class="item" v-for="(item,index) in pieChartOption.series[0].data" :key="index">
                <div>
                  <div :style="{ backgroundColor: pieChartOption.color[index] }"></div>
                  <a-tooltip >
                    <template #title>{{item.name}}</template>
                    <div class="name">{{ item.name }}</div>
                  </a-tooltip>
                </div>
                <div>{{ item.value }}</div>
                <div>{{ ((item.value / pieCurrentTotal) * 100).toFixed(2) }}%</div>
              </div>
            </div>
          </div>
          <div class="pieChart" id="pieChart" :style="{width:'550px',minHeight:'450px'}"></div>
        </div>
        <template slot="footer">
          <a-button type="primary" @click.stop="showPie=false">关闭</a-button>
        </template>
      </a-modal>
    </div>
  </template>
  
  <script>
  import {compoundTop,navFind,chartCompound,chartCompoundItem} from '@/services/compound'
  import {compoundList,liquidTop,liquidModel,saveLiquidData,deleteTemp,delLiquidData} from '@/services/liquid'
  import moment from 'moment';
  import {mapState} from 'vuex'
  import STable from '@/components/STable'
  import ColForm from './modules/ColForm'
  export default {
    name: 'Compound',
    components: {
      STable,ColForm
    },
    data() {
      this.moment = moment;
      return {
        showPie: false,
        pieCurrentTotal: null,
        pieChartOption: {
          title: {
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          // legend: {
          //   orient: 'vertical',
          //   right: 20,
          //   top: 20,
          //   type: 'scroll',
          // },
          color: [
            '#CCFFFF','#FFCCCC','#99CCCC','#FFCC99','#FF9999','#996699','#CC9999','#FFFFCC','#CCCC99','#FFFF99','#CCCCFF','#0099CC','#CCCCCC','#FF6666','#FF9966','#FFCCCC','#CC9966','#666666','#FF6666','#FFFF66','#99CC66','#CC3333','#CCCCCC','#003366','#663366','#CCCC99','#666666','#FF6666','#FFFF00','#0066CC','#333333','#336633','#990033','#66CC00','#CC99CC','#339933','#993399','#006633',
            '#CC9966','#003300','#FF0033','#333399','#CCCC00','#003399','#99CC00','#CC0033','#999933','#993333','#333300','#CCFF99','#99CCFF','#99CC99','#336699','#CC9933','#FFCC33','#336666','#99CC33','#FFCC00','#CC6699','#FFFF00','#3366CC','#FF6600','#009966','#990033','#CCFF66','#FF9900','#FF9966','#996600','#CC6600','#999999','#CCCC33','#000000','#999966','#663300','#FF9933','#6666CC']
          ,
          series: [
            {
              name: '',
              type: 'pie',
              radius: '50%',
              data: [],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        },
        pieData: [],
        stand:'',
        cat_name:'',
        chkd:[],
        tableField:[],
        visidropdown:false,
        checkedList: [],
        actTabs:1,
        fieldsData:[],
        childData:[],
        columns:[],
        cateList:[],
        isSave:false,
        form: this.$form.createForm(this),
        loading: false,
        visible: false,
        confirmLoading: false,
        mdl: null,
        queryParam: {pid:1},
        tableTobData:[],
        param:[],
        defaultFileList: [],
        loadData: () => {
          return compoundList(this.chkd).then(res => {
            return res.data.data
          })
        },
        headerArr:[],
        colData:[],
        modelId:0,
        tableId:0,
        colId:0,
        current:0,
        chat:[],
        chats:[],
        chat1:[],
        loading:false,
        isload:false,
        radioVal:'',
        radioStyle: {
          display: 'block',
          height: '40px',
          lineHeight: '40px',
          width:'180px',
        },
        actNav:['0'],
        nav:[],
        select:[],
        options:[],
        selected:'0',
        norms:[],
        norm:'0',
        letData:[],
        openMenu:[],
        labelOption:{
          show:false,
          // distance: 20,
          // align: 'center',
          // verticalAlign: 'middle',
          // position:'top',
          // rotate: 0,
          // formatter: '{c}  {name|{a}}',
          // rich: {
          //     name: {}
          // }
        },
        option:{
          color: [
            '#CCFFFF','#FFCCCC','#99CCCC','#FFCC99','#FF9999','#996699','#CC9999','#FFFFCC','#CCCC99','#FFFF99','#CCCCFF','#0099CC','#CCCCCC','#FF6666','#FF9966','#FFCCCC','#CC9966','#666666','#FF6666','#FFFF66','#99CC66','#CC3333','#CCCCCC','#003366','#663366','#CCCC99','#666666','#FF6666','#FFFF00','#0066CC','#333333','#336633','#990033','#66CC00','#CC99CC','#339933','#993399','#006633',
            '#CC9966','#003300','#FF0033','#333399','#CCCC00','#003399','#99CC00','#CC0033','#999933','#993333','#333300','#CCFF99','#99CCFF','#99CC99','#336699','#CC9933','#FFCC33','#336666','#99CC33','#FFCC00','#CC6699','#FFFF00','#3366CC','#FF6600','#009966','#990033','#CCFF66','#FF9900','#FF9966','#996600','#CC6600','#999999','#CCCC33','#000000','#999966','#663300','#FF9933','#6666CC'],
          tooltip: {trigger: 'axis',axisPointer: {type: 'shadow'}},
          legend: {data: []},
          toolbox: {
            show: true,
            orient: 'vertical',
            left: 'right',
            top: 'center',
            feature: {
              mark: { show: true },
              dataView: { show: true, sreadOnly: false },
              magicType: { show: true, type: ['stack'] },
              restore: { show: true },
              saveAsImage: { show: true }
            }
          },
          yAxis: [{type: 'value'}],
          xAxis:null,
          dataZoom: [
            {
              type: 'slider',
              realtime: true,
              start: 0,
              end: 5,
              height: 5,
              left: 5,
              right: 5,
              bottom: 10,
              show: true,
              fillerColor: "rgba(17, 100, 210, 0.42)",
              borderColor: "rgba(17, 100, 210, 0.12)",
              handleSize: 0,
              showDetail: false,
              zoomLock: true,
              moveOnMouseMove: false,
  
              startValue: 0,
              endValue: 6,
              minValueSpan: 6,
              maxValueSpan: 6,
            },
            {
              type: "inside",
              start: 0,
              end: 5,
              zoomOnMouseWheel: false,
              moveOnMouseWheel: true,
              moveOnMouseMove: true
            }
          ],
          series: []
        },
        dataZoom: [
          {
            type: 'slider',
            realtime: true,
            start: 0,
            end: 5,
            height: 5,
            left: 5,
            right: 5,
            bottom: 10,
            show: true,
            fillerColor: "rgba(17, 100, 210, 0.42)",
            borderColor: "rgba(17, 100, 210, 0.12)",
            handleSize: 0,
            showDetail: false,
            zoomLock: true,
            moveOnMouseMove: false,
  
            startValue: 0,
            endValue: 6,
            minValueSpan: 6,
            maxValueSpan: 6,
          },
          {
            type: "inside",
            start: 0,
            end: 5,
            zoomOnMouseWheel: false,
            moveOnMouseWheel: true,
            moveOnMouseMove: true
          }
        ],
      }
    },
    mounted() {
      this.$nextTick(()=>{
        compoundTop().then(res => {
          this.nav = res.data.data
          this.getNavFind()
          setTimeout(() => {
            this.getChart()
          }, 500);
        })
      })
    },
    created (){
      this.getLiquidTop()
    },
    computed: {
      ...mapState({
        lang: state => state.setting.lang,
      }),
    },
    methods: {
      getLiquidTop(pid=1) {
        liquidTop({pid}).then(res => {
          var searchObj = {}
          let columns = [ ...res.data.data];
          let title = []
          columns.forEach(arr => {
            Object.assign(searchObj,arr.children)
            let arrs = Object.values(arr.children);
            title = title.concat(arrs)
            arr.children = [ ...arrs]
          });
          const top = {type: 'serial',etitle: 'serial',titles: '序号',dataIndex: 'index',fixed: 'left',align:'center',width:100,slots:{title:'serial'}}
          columns.unshift(top)
          const last = {type: 'operate',etitle: 'operate',titles: '操作',dataIndex: 'action',width: 200,fixed: 'right',align:'center',slots:{title:'operate'},scopedSlots: {customRender: 'action'}};
          columns.push(last)
          this.columns = JSON.parse(JSON.stringify(columns))
        });
      },
      //行删除
      colDel(record) {
        let {id}={ ...record};
        let _this = this;
        _this.$confirm({
          title: '确定要删除吗？',
          okType: 'danger',
          onOk() {
            delLiquidData({list:[id]}).then( res => {
              _this.$message.info('删除成功')
              _this.$refs.table.refresh()
            })
          },
        });
      },
      //行查看
      colFind(record) {
        this.isSave=false
        this.visible = true
        let obj={ ...record}
        let {id}=obj;
        this.colId=id
        this.getModel(id)
      },
      getModel(id){
        this.confirmLoading=true;
        liquidModel({id,pid:this.actTabs}).then(res=>{
          let data=res.data.data;
          this.mdl=data.info;
          this.modelId=id
          setTimeout(() => {
            this.colData=data.list
            this.confirmLoading=false;
          }, 300);
        })
  
      },
      //行修改
      colEdit(record) {
        let {id}={ ...record};
        this.colId=id
        this.isSave=true
        this.visible = true
        this.getModel(id)
  
      },
      // 弹窗修改确认
      handleOk() {
        const form = this.$refs.colModal.form
        form.validateFields((errors, values) => {
          if (!errors) {
            this.confirmLoading = true
            let obj=Object.assign(values,{id:this.colId})
            saveLiquidData(obj).then(res=>{
              this.$message.info(res.data.data)
              this.visible = false
              this.confirmLoading = false
              form.resetFields()
              this.$refs.table.refresh()
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleKo(){
        this.visible = false
      },
      allChange(index){
        this.cat_name=this.select[index].cat_name
        this.getChart({cat_name:this.cat_name,list:this.chkd})
        this.getChild(index)
      },
      allChangeNorm(stand) {
        console.log('yes is here')
        let obj = JSON.parse(JSON.stringify(this.chart1));
        if (this.cat_name=='臭气浓度') {
          this.stand=this.norms[stand].label
          this.getChart({cat_name:'臭气浓度',stand:this.stand,list:this.chkd})
        }else{
          this.chartInv(obj.data,false,stand,this.selected)
          // console.log(obj.data,false,stand,this.selected);
        }
  
      },
      // 多个图表切换单位事件
      changeChat(i,data,chk) {
        console.log(i, data, chk, 'changeChat')
        if ( i == 3 ) {
          this.getChartItem({pid:this.actNav[0],stand:data[chk].label,list:this.chkd})
        }else {
          this.reChat(i,chk,data[chk].label)
        }
      },
      // 多个图表切换单位事件2
      /**
       *
       * @param i  图表索引值
       * @param chk
       */
      reChat(i,chk){
        console.log(i,chk, 'reChat');
        var lineCharts = document.getElementsByClassName('lineChart');
        var myChart = this.$echarts.init(lineCharts[i])
        let chats = JSON.parse(JSON.stringify(this.chat));
        let obj = chats[i];
        let { series } = obj;
        let total = [];
        let dataItem = [];
        let pieData = [];
        // this.pieData = [];
        console.log(series, 'here')
        if ( i !== 0 && chk == 1 ) {
          series = series.map(lst => {
            lst.data = lst.data.map(el => {
              return el * 1000
            });
            dataItem.push(lst.data)
            return lst
          })
        }else if (i == 0 && chk == 1) {
          // console.log('reChart: series', series)
          series = series.map(lst => {
            lst.data = lst.data.map(el => {
              return (el / 1000).toFixed(4)
            });
            dataItem.push(lst.data)
            return lst
          })
        }else {
          for (const series1 of series) {
            dataItem.push(series1.data)
          }
        }
        // console.log('reChart: dataItem', dataItem)
        for (let j = 0;j < dataItem[0].length; j++) {
          total[j] = 0;
          pieData[j] = {
            values: []
          }
        }
        for (let i = 0;i < dataItem.length; i++) {
          for (let j = 0;j < dataItem[i].length; j++) {
            total[j] += Number(dataItem[i][j])
          }
        }

        series.forEach((item) => {
          item.data.forEach((item2,index2) => {
            let val = {
              name: item.name,
              value: item2
            }
            pieData[index2].values.push(val);
          })
        })
        this.pieData.push(pieData);
        // total 保留四位小数
        total = total.map(item => {
          return Number(item.toFixed(4))
        })
        // console.log('reCahrt: total', total)
        series.push({
          name: '总和',
          type: 'bar',
          stack: 'y',
          // id: JSON.stringify(pieData),  //用ID存放数据
          data: total,
          itemStyle: {
            normal: {
              color: 'rgba(128, 128, 128, 0)'
            },
          },
          label:{
            normal:{
              show:true,
              position:'top',
              color:'#000'
            }
          },
          barGap:'-100%',  //与堆叠柱条重合
        })
        console.log('reCahrt: series', series)
        var option = {
          tooltip: { trigger: 'axis',axisPointer: {type: 'shadow'} },
          xAxis: { data: obj.xAxis },
          legend: {
            data: obj.legend,
            width: 500,
            type: 'scroll',
          },
          yAxis: {},
          color: [
            '#CCFFFF','#FFCCCC','#99CCCC','#FFCC99','#FF9999','#996699','#CC9999','#FFFFCC','#CCCC99','#FFFF99','#CCCCFF','#0099CC','#CCCCCC','#FF6666','#FF9966','#FFCCCC','#CC9966','#666666','#FF6666','#FFFF66','#99CC66','#CC3333','#CCCCCC','#003366','#663366','#CCCC99','#666666','#FF6666','#FFFF00','#0066CC','#333333','#336633','#990033','#66CC00','#CC99CC','#339933','#993399','#006633',
            '#CC9966','#003300','#FF0033','#333399','#CCCC00','#003399','#99CC00','#CC0033','#999933','#993333','#333300','#CCFF99','#99CCFF','#99CC99','#336699','#CC9933','#FFCC33','#336666','#99CC33','#FFCC00','#CC6699','#FFFF00','#3366CC','#FF6600','#009966','#990033','#CCFF66','#FF9900','#FF9966','#996600','#CC6600','#999999','#CCCC33','#000000','#999966','#663300','#FF9933','#6666CC'
          ],
          dataZoom: this.dataZoom,
          label: this.labelOption,
          series: series
        };
        myChart.setOption(option,true);
      },

      // 切换分类渲染数据
      getChartItem(param={pid:0}) {
        chartCompoundItem(param).then(res => {
          var chat = res.data.data;
          this.pieData = []
          this.chats = JSON.parse(JSON.stringify(chat));
          this.chat = JSON.parse(JSON.stringify(chat));
          this.$nextTick(() => {
            var lineCharts = document.getElementsByClassName('lineChart');
            // console.log('getChartItem: chat', chat)
            chat.forEach((obj,obji) => {
              // console.log('getChartItem： chat-index', obji);
              let total = [];
              let dataItem = [];
              let pieData = [];
              var myChart = this.$echarts.init(lineCharts[obji])
              // console.log('getChartItem: ', obj)
              obj.series.forEach((item) => {
                dataItem.push(item.data)
              })
              // console.log('getChartItem: dataItem', dataItem)
  
              for (let j = 0;j < dataItem[0].length; j++) {
                total[j] = 0;
                pieData[j] = {
                  values: []
                }
              }
              for (let i = 0;i < dataItem.length; i++) {
                for (let j = 0;j < dataItem[i].length; j++) {
                  total[j] += Number(dataItem[i][j])
                }
              }

              obj.series.forEach((item) => {
                item.data.forEach((item2,index2) => {
                  let val = {
                    name: item.name,
                    value: item2
                  }
                  pieData[index2].values.push(val);
                })
              })
              total = total.map(item => {
                return Number(item.toFixed(2))
              })
              console.log('getChartItem: total', total)
              var option = {
                tooltip: {trigger: 'axis',axisPointer: {type: 'shadow'}},
                xAxis: {data: obj.xAxis},
                legend: {
                  data: obj.legend
                },
                yAxis: {},
                color: [
                  '#CCFFFF','#FFCCCC','#99CCCC','#FFCC99','#FF9999','#996699','#CC9999','#FFFFCC','#CCCC99','#FFFF99','#CCCCFF','#0099CC','#CCCCCC','#FF6666','#FF9966','#FFCCCC','#CC9966','#666666','#FF6666','#FFFF66','#99CC66','#CC3333','#CCCCCC','#003366','#663366','#CCCC99','#666666','#FF6666','#FFFF00','#0066CC','#333333','#336633','#990033','#66CC00','#CC99CC','#339933','#993399','#006633',
                  '#CC9966','#003300','#FF0033','#333399','#CCCC00','#003399','#99CC00','#CC0033','#999933','#993333','#333300','#CCFF99','#99CCFF','#99CC99','#336699','#CC9933','#FFCC33','#336666','#99CC33','#FFCC00','#CC6699','#FFFF00','#3366CC','#FF6600','#009966','#990033','#CCFF66','#FF9900','#FF9966','#996600','#CC6600','#999999','#CCCC33','#000000','#999966','#663300','#FF9933','#6666CC'],
                dataZoom: this.dataZoom,
                series: obj.series,
                label: this.labelOption
              };

              this.pieData.push(pieData)
              option.series.push({
                name: '总和',
                type: 'bar',
                stack: 'y',
                // id: JSON.stringify(pieData),  //用ID存放数据
                data: total,
                itemStyle: {
                  normal: {
                    color: 'rgba(128, 128, 128, 0)'
                  },
                },
                label:{
                  normal:{
                    show:true,
                    position:'top',
                    color:'#000'
                  }
                },
                barGap:'-100%',  //与堆叠柱条重合
              })
              option.legend.type = 'scroll'
              option.legend.width = 500
              myChart.setOption(option,true);
              myChart.on('click', (e) => {
                this.showPie = true;
                // console.log('getChartItem: click', this.pieData)
                // let data = JSON.parse(e.seriesId)
                this.pieChartOption.series[0].data = this.pieData[obji][e.dataIndex].values;
                this.pieChartOption.series[0].name = chat[obji].xAxis[e.dataIndex]
                this.pieChartOption.title.text = chat[obji].name
                this.pieChartOption.title.subtext = chat[obji].xAxis[e.dataIndex]
                this.pieCurrentTotal = option.series.at(-1).data[e.dataIndex];
                console.log('getChartItem: pieCurrentTotal', this.pieCurrentTotal)
                setTimeout(() => {
                  this.$nextTick(() => {
                    let pieChart = this.$echarts.init(document.getElementById('pieChart'))
                    pieChart.setOption(this.pieChartOption)
                  })
                },500)
              })
              window.addEventListener("resize", () => {
                if(myChart){
                  myChart.resize();
                }
              });
            });
          })
        })
      },
      getChild(str=0) {
        let arr = this.select
        let norms = []
        arr[str].children.forEach((el,i) => {
          norms.push({label:el.cat_name,value:i})
        });
        this.norms = norms
        this.norm = norms[0].value
      },

      /**
       * @author Wang Kang
       * @description: 第一次初始化数据
       * @param data
       * @param isbad
       * @param index
       * @param pindex
       * @param load
       */
      chartInv(data=[], isbad = false, index = 0,pindex = 0, load = false) {
        console.log(data);
        
        // console.log(data, isbad,'index:', index,'pindex:', pindex, load)
        // console.log(this.option.series,'option.series')
        let myChart = this.$echarts.init(document.getElementById("comcanvas"))
        if (Object.keys(data).length==0) {
          this.option={}
          myChart.setOption(this.option);
          return
        }
        if (pindex !== 0 && index == 1) {
          this.option.series=[]
          data.forEach((lst,lsti)=>{
            if (lsti==0) {
              lst.barGap=0
            }
            lst.type='bar'
            lst.label=this.labelOption
            lst.emphasis={focus: 'series'}
            lst.data=lst.data.map(el => {
              let val=(el*1000).toFixed(2)
              return val
            });
            console.log(lst)
            this.option.series.push(lst)
          })
        }
        else if(pindex == 0 && index == 1) {
          console.log('two')
          this.option.series = [];
          console.log(this.option.series,'option.series')
          let total = [];
          let dataItem = [];
          let pieData = [];
          data.forEach((lst,lsti) => {
            if (lsti == 0) {
              lst.barGap = 0
            }
            lst.type = 'bar'
            lst.label = this.labelOption
            lst.emphasis = { focus: 'series' }
            lst.data = lst.data.map(el => {
              let val = (el/1000).toFixed(4)
              return val
            });
            dataItem.push(lst.data)
            this.option.series.push(lst)
          })
          // 获取数据total和饼状图数据
          for (let j = 0;j < dataItem[0].length; j++) {
            total[j] = 0;
            pieData[j] = {
              values: []
            }
          }
          for (let i = 0;i < dataItem.length; i++) {
            for (let j = 0;j < dataItem[i].length; j++) {
              total[j] += Number(dataItem[i][j])
            }
          }
          // console.log(this.option, 'series')
          // 处理饼状图数据
          data.forEach((item,index) => {
            item.data.forEach((item2,index2) => {
              // console.log('',item2, item.name, index2)
              let val = {
                name: item.name,
                value: item2
              }
              pieData[index2].values.push(val);
            })
          })
          // console.log(pieData, 'pieData')
          // 处理数据格式
          total = total.map(item => Number(item.toFixed(4)))
          console.log(total, 'totalData')
          this.pieData = pieData
          this.option.series.push({
            name: '总和',
            // id: JSON.stringify(pieData),
            type: 'bar',
            stack: 'y',
            data: total,
            itemStyle: {
              normal: {
                color: 'rgba(128, 128, 128, 0)'
              },
            },
            label:{
              normal:{
                show:true,
                position:'top',
                color:'#000'
              }
            },
            barGap:'-100%',  //与堆叠柱条重合
          })
        }
        else if(pindex==3&&index==1) {
          this.option.series=[]
          data.forEach((lst,lsti) => {
            if (lsti == 0) {
              lst.barGap = 0
            }
            lst.type = 'bar'
            lst.label = this.labelOption
            lst.emphasis = { focus: 'series' }
            lst.data=lst.data.map(el => {
              let val=(el/1000).toFixed(4)
              return val
            });
            this.option.series.push(lst)
          })
        }
        else {
          console.log('one')
          this.option.series = [];
          let total = [];
          let dataItem = [];
          let pieData = [];
          data.forEach((lst,lsti) => {
            if (lsti == 0) {
              lst.barGap = 0
            }
            // console.log(lst)
            dataItem.push(lst.data)
            lst.type = 'bar'
            lst.label = this.labelOption
            lst.stack = 'x'
            lst.emphasis = {focus: 'series'}
            this.option.series.push(lst)
          })
          // console.log(dataItem)
          for (let j = 0;j < dataItem[0].length; j++) {
            total[j] = 0;
            pieData[j] = {
              values: []
            }
          }
          for (let i = 0;i < dataItem.length; i++) {
            for (let j = 0;j < dataItem[i].length; j++) {
              total[j] += Number(dataItem[i][j])
            }
          }
          // console.log(this.option, 'series')
          data.forEach((item,index) => {
            item.data.forEach((item2,index2) => {
              // console.log('',item2, item.name, index2)
              let val = {
                name: item.name,
                value: item2
              }
              pieData[index2].values.push(val);
            })
          })
          // console.log(total, 'totalData');
          // console.log(pieData, 'pieData')
          total = total.map(item => Number(item.toFixed(2)))
          this.pieData = pieData
          this.option.series.push({
            name: '总和',
            // id: JSON.stringify(pieData),
            type: 'bar',
            stack: 'y',
            data: total,
            itemStyle: {
              normal: {
                color: 'rgba(128, 128, 255, 0)'
              },
            },
            label:{
              normal:{
                show:true,
                position:'top',
                color:'#000'
              }
            },
            barGap:'-100%',  //与堆叠柱条重合
          })

        }

        // console.log('option',this.option.series)
        myChart.setOption(this.option);
        myChart.on('click', (e) => {
          console.log(e)
          this.showPie = true;
          // let data = JSON.parse(e.seriesId)
          this.pieChartOption.series[0].data = this.pieData[e.dataIndex].values;
          this.pieChartOption.series[0].name = this.option.xAxis[0].data[e.dataIndex];
          this.pieChartOption.title.text = this.option.xAxis[0].data[e.dataIndex];
          this.pieChartOption.title.subtext = '';
          this.pieCurrentTotal = this.option.series.at(-1).data[e.dataIndex];
          console.log(this.pieCurrentTotal, 'pieChartOption')
          setTimeout(() => {
            this.$nextTick(() => {
              let pieChart = this.$echarts.init(document.getElementById('pieChart'))
              pieChart.setOption(this.pieChartOption)
            })
          },500)
        })
      },
      async getChart(param={}) {
        await chartCompound(param).then(res => {
          let obj = res.data.data
          this.chart1 = JSON.parse(JSON.stringify(obj));
          let { data,norm,selected,select,xAxis,legend } = obj
          if (this.isload == false) {
            this.select = select
            this.selected = 0
            let options = JSON.parse(JSON.stringify(select));
            options.forEach((el,i) => {
              this.options.push({label:el.cat_name,value:i})
            });
            // console.log(this.options)
            this.isload = true
            this.getChild()
          }
          if (this.isload) {
            console.log('getChart',obj);
            if (Object.keys(obj).length==0) {
              let myChart = this.$echarts.init(document.getElementById("comcanvas"))
              // this.option={}
              let option = {
                legend:{},
                xAxis: {
                  type: 'category',
                  data: []
                },
                yAxis: {
                  type: 'value'
                },
                series: [
                  {
                    data: [],
                    type: 'bar'
                  }
                ]
              };
              myChart.setOption(option);
              return
            }
            this.option.xAxis = [{type: 'category',axisTick: { show: false },data: xAxis}]
            console.log(legend);
            this.option.legend.data = legend
            this.option.legend.type = 'scroll'
            this.option.legend.width = 500
            this.option.series = []
          }
          if (obj.selected == '臭气浓度') {
            this.chartInv(data,true)
          }else {
            this.chartInv(data,false)
          }
  
        })
  
  
      },
      getChkSearch(){
        let chkd = []
        let good = this.letData.map((lst) => {
          return lst.children.filter(obj => {
            if (obj.checked) {
              return obj
            }
          })
        })
        good.forEach(el => {
          let val = Array.from(el,({cat_name})=>cat_name);
          chkd = chkd.concat(val)
        });
        return chkd
      },
      changeChked() {
        let chkd=this.getChkSearch()
        this.chkd = chkd;
        let pid = this.actNav[0];
        // console.log(this.chkd, 'chkd here')
        this.$refs.table.refresh()
        // this.loadData()
        if (chkd.length > 0) {
          if (pid > 0) {
            this.getChartItem({pid,list:chkd})
          }else{
            this.getChart({list:chkd,cat_name:this.cat_name,stand:this.stand})
          }
        }else {
          var option = {
            xAxis: {
              type: 'category',
              data: []
            },
            yAxis: {
              type: 'value'
            },
            series: [
              {
                data: [],
                type: 'bar'
              }
            ]
          };
          if (pid>0) {
            let chat = JSON.parse(JSON.stringify(this.chat));
            var lineCharts = document.getElementsByClassName('lineChart');
            this.$nextTick(() => {
              chat.forEach((obj,obji) => {
                var myChart = this.$echarts.init(lineCharts[obji])
                myChart.setOption(option,true);
              });
            })
          }else{
            let myChart = this.$echarts.init(document.getElementById("comcanvas"))
            myChart.setOption(option);
          }
        }
      },
      getNav(e){
        let { keyPath } = e
        this.actNav = keyPath
        this.chkd=this.getChkSearch()
        console.log('getNav-chk',this.chkd);
        if (this.chkd.length == 0) {
          var option = {
            xAxis: {
              type: 'category',
              data: []
            },
            yAxis: {
              type: 'value'
            },
            series: [
              {
                data: [],
                type: 'bar',
              }
            ]
          };
          if (keyPath[0]==0) {
            let myChart=this.$echarts.init(document.getElementById("comcanvas"))
            myChart.setOption(option);
          } else {
            var lineCharts = document.getElementsByClassName('lineChart');
            this.$nextTick(() => {
              setTimeout(() => {
                [1,2,3,4].forEach((obj,obji) => {
                  console.log(obji);
                  var myChart = this.$echarts.init(lineCharts[obji])
                  var option = {
                    tooltip: {trigger: 'axis',axisPointer: {type: 'shadow'}},
                    xAxis: {data: []},
                    legend: {data: []},
                    yAxis: {},dataZoom:[],
                    series: [],
                    label:[]
                  };
                  myChart.setOption(option,true);
                  window.addEventListener("resize", () => {
                    if(myChart){
                      myChart.resize();
                    }
                  });
                });
              }, 1000);
            })
          }
        }else {
          if (keyPath[0] == 0) {
            this.$nextTick(() => {
              this.getChart({list:this.chkd})
            })
          }else{
            this.$nextTick(() => {
              setTimeout(() => {
                this.getChartItem({pid:keyPath[0],list:this.chkd})
              }, 500);
            })
          }
        }
  
  
      },
      getNavFind(id=0) {
        navFind({id}).then(res=>{
          this.letData=res.data.data
          this.openMenu=this.letData.map(lst=>lst.key)
        })
      },
    }
  };
  </script>
  
  <style lang="less">
  .container {
    //border: 1px solid red;
    display: flex;
    //align-items: center;
    .data-list {
      max-height: 450px;
      margin: 25px 0 0 35px;
      width: 330px;
      ::-webkit-scrollbar {
        width: 7px;
        background-color: #f1f1f1;
        border-radius: 20px;
      }
      ::-webkit-scrollbar-thumb {
        background-color: #ccc;
        border-radius: 20px;
      }
      .item-header {
        display: grid;
        grid-template-columns: 35% 30% 30%;
        height: 45px;
        line-height: 45px;
        border-radius: 5px 5px 0 0;
        font-size: 16px;
        color: #333;
        background-color: #f0f2f5;
        >div {
          text-align: center;
          justify-content: center;
        }
      }
      .list {
        height: 405px;
        overflow-y: scroll;
        .item {
          height: 30px;
          line-height: 30px;
          border: 1px solid #f0f2f5;
          display: grid;
          grid-template-columns: 35% 30% 30%;
          >div:first-child {
            display: flex;
            align-items: center;
            padding-left: 10px;
            >div:first-child {
              margin-right: 5px;
              width: 12px;
              height: 12px;
              border-radius: 50%;
            }
            .name {
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 1;
              overflow: hidden;
              text-overflow: ellipsis;
              width: 96px;
            }
          }
          >div:not(:first-child) {
            text-align: center;
          }
        }
      }
    }
    .pieChart {
      //border: 1px solid red;
      margin-top: 25px;
      //margin-left: -80px;
    }
  }
  .ant-menu-item-selected {
  
  }
  </style>
      