<template>
  <div class="status-timegraph-container" style="background: #f2f4f9; flex: 1; display: flex; flex-direction: column">
    <el-row class="" style="
				margin-bottom: 12px;
				background: #fff;
				padding: 16px 16px 0;
				border-radius: 8px;
			">
      <!-- <div class="blue-title">生产节拍时序图</div> -->
      <SearchBar :formConfigs="searchBarFormConfig" ref="search-bar" @headBtnClick="handleSearchBarBtnClick" />

      <!-- 列表 -->
      <base-table :table-props="tableProps" :page="1" :limit="10" :table-data="list">
      </base-table>
    </el-row>

    <el-row class="" style="
				height: 1px;
				flex: 1;
				margin-bottom: 12px;
				background: #fff;
				padding: 16px 16px 32px;
				border-radius: 8px;
				display: flex;
				flex-direction: column;
			">
      <el-row :gutter="20">
        <el-col :span="24">
          <div class="blue-title">
            <!-- <span > -->
            图表时间维度
            <!-- </span> -->
            <el-tabs style="margin-top: 10px;" v-model="activeName" type="card" @tab-click="handleClick">
              <el-tab-pane label="天" name="day">
                <div id="mapDayMain" style="margin-bottom: 30px;height: 500px;width: 1000px;"></div>
                <div id="listDayMain" style="height: 500px;width: 1000px;"></div>
              </el-tab-pane>
              <el-tab-pane label="周" name="week">
                <div id="mapWeekMain" style="height: 500px;width: 1000px;"></div>
                <div id="listWeekMain" style="height: 500px;width: 1000px;"></div>
              </el-tab-pane>
              <el-tab-pane label="月" name="month">
                <div id="mapMonthMain" style="height: 500px;width: 1000px;"></div>
                <div id="listMonthMain" style="height: 500px;width: 1000px;"></div>
              </el-tab-pane>
              <!-- <el-tab-pane label="定时任务补偿" name="fourth">定时任务补偿</el-tab-pane> -->
            </el-tabs>
          </div>
        </el-col>
        <!-- <el-col :span="18" class="legend-row">
          <div class="legend">
            <div class="icon running"></div>
            <div>运行中</div>
          </div>
          <div class="legend">
            <div class="icon fault"></div>
            <div>故障</div>
          </div>
          <div class="legend">
            <div class="icon stop"></div>
            <div>计划停机</div>
          </div>
        </el-col> -->
      </el-row>
      <!-- <div class="main-area" style="flex: 1; display: flex; flex-direction: column">
        <div class="graphs" v-show="graphList.length" id="status-chart" style="height: 1px; flex: 1"></div>
        <h2 v-if="!graphList || graphList.length == 0" class="no-data-bg"></h2>
      </div> -->
    </el-row>

  </div>
</template>

<script>
import {
  getQualityIsraPage,
  getQualityIsraDayMap,
  getQualityIsraWeekMap,
  getQualityIsraMonthMap,
  getQualityIsraDayList,
  getQualityIsraWeekList,
  getQualityIsraMonthList,
} from '@/api/monitoring/qualityIsra';
// import Editor from '@/components/Editor';
import moment from 'moment';
// import DialogForm from './dialogForm.vue';
import * as echarts from 'echarts';

// import basicPageMixin from '@/mixins/lb/basicPageMixin';
export default {
  name: 'statisticalData',
	// components: {
	// 	DialogForm,
	// },
	// mixins: [basicPageMixin],
	data() {
    return {
      list: [],
      dynamicProps: [],
      activeName: 'day',
      dayMapUrl: '/base/quality-isra-statistics/dayMap',
      weekMapUrl: '/base/quality-isra-statistics/weekMap',
      monthMapUrl: '/base/quality-isra-statistics/monthMap',
      dayListUrl: '/base/quality-isra-statistics/dayList',
      weekListUrl: '/base/quality-isra-statistics/weekList',
      monthListUrl: '/base/quality-isra-statistics/monthList',
      searchBarFormConfig: [
        {
          type: 'select',
          label: '缺陷类型',
          placeholder: '请选择缺陷类型',
          param: 'checkType',
          selectOptions: [],
          labelField: 'name',
          valueField: 'name',
          defaultSelect: []
        },
				{
					type: 'datePicker',
					label: '时间段',
          dateType: 'datetimerange', // datetimerange
					// format: 'yyyy-MM-dd HH:mm:ss',
          format: 'yyyy-MM-dd HH:mm:ss',
          valueFormat: 'yyyy-MM-dd HH:mm:ss',
					rangeSeparator: '-',
					startPlaceholder: '开始日期',
					endPlaceholder: '结束日期',
					defaultTime: ['00:00:00', '23:59:59'],
					param: 'checkTime',
					// width: 350,
				},
				{
					type: 'button',
					btnName: '查询',
					name: 'search',
					color: 'primary',
				},
			],
			// 查询参数
			queryParams: {
        checkType:undefined,
        // productionId: undefined,
        startTime: undefined,
        endTime: undefined,
				// productionLineId: null,
			},
		};
  },
	created() {
		// this.getProductLineList();
  },
  computed: {
    tableProps() {
      return [
        {
          // width: 128,
          prop: 'checkType',
          label: '缺陷类型',
        },
        {
          // width: 128,
          prop: 'sumNum',
          label: '缺陷总数',
        },
        ...this.dynamicProps,
      ];
    },
  },
  mounted() {
    // if (this.$route.query.woIdString) {
    //   console.log(this.$route.query.woIdString)
    //   this.queryParams.workOrderIdList = this.$route.query.woIdString.split(',')
    //   // this.queryParams.workOrderIdList = [this.$route.query.woIdString]
    //   // let arr =[]
    //   this.searchBarFormConfig[0].defaultSelect = this.$route.query.woIdString.split(',')
    //   console.log(this.searchBarFormConfig[0].defaultSelect);
    // }
    // if (this.$route.params.startTime && this.$route.params.endTime) {
    //   this.searchBarFormConfig[0].defaultSelect = [
    //     this.$route.params.startTime,
    //     this.$route.params.endTime,
    //   ];
    //   this.queryParams.param = {};
    //   this.$set(
    //     this.queryParams.param,
    //     'startTime',
    //     this.$route.params.startTime
    //   );
    //   this.$set(this.queryParams.param, 'endTime', this.$route.params.endTime);
    // } else {
    //   this.searchBarFormConfig[0].defaultSelect = [];
    // }
    this.getList()
    this.getData()
    this.getDict()
  },
  methods: {
    handleClick() {
      this.getData()
     },
    getData() {
      this.$axios({
        url: this.activeName === 'day' ? this.dayMapUrl : this.activeName === 'week' ? this.weekMapUrl : this.monthMapUrl,
          method: 'get',
          params: this.queryParams
      }).then((res) => {
        let mapArr= []
        let mapLegendData = []
        // let mapXAxisData = []
        for (let i in res.data) {
          let obj = {
            name: '',
            type: 'line',
            // stack: 'Total',
            data: [],
            mapXAxisData:[],
          }
          // console.log(i)
          let dataArr = []
          res.data[i].forEach(ele => {
            dataArr.push(ele.num)
            obj.mapXAxisData.push(ele.checkTime)
          })
          obj.name = i
          obj.data = dataArr
          mapLegendData.push(i)
          mapArr.push(obj)
        }
        // console.log(res.data[res]);
        var chartDom = this.activeName === 'day' ? document.getElementById('mapDayMain') : this.activeName === 'week' ? document.getElementById('mapWeekMain') : document.getElementById('mapMonthMain')
        var myChart = echarts.init(chartDom);
        var option;
        option = {
          title: {
            text: '各类型缺陷对比图',
            // top:'5px'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: mapLegendData,
            top: "10%",
            y: 'top',
            x:'left'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top:'20%',
            containLabel: true
          },
          // toolbox: {
          //   feature: {
          //     saveAsImage: {}
          //   }
          // },
          xAxis: {
            type: 'category',
            // boundaryGap: false,
            data: mapArr[0].mapXAxisData
          },
          yAxis: {
            type: 'value'
          },
          series: mapArr
        }
        option && myChart.setOption(option);
      })
      this.$axios({
        url: this.activeName === 'day' ? this.dayListUrl : this.activeName === 'week' ? this.weekListUrl : this.monthListUrl,
        method: 'get',
        params: this.queryParams
      }).then((res) => {
        // console.log(res);
        let listNumArr = []
        let listRatioArr = []
        // let listLegendData = []
        let listXAxisData = []
        // for (let i in res.data) {
          // console.log(i)
          // let dataArr = []
        res.data.forEach(ele => {;
            listNumArr.push(ele.num)
            listRatioArr.push(ele.ratio)
            listXAxisData.push(ele.checkTime)
        })
        console.log(listNumArr);
          // obj.name = i
          // obj.data = dataArr
          // listLegendData.push(i)
          // listArr.push(obj)
        // }
        // console.log(res.data[res]);
        var chartDom = this.activeName === 'day' ? document.getElementById('listDayMain') : this.activeName === 'week' ? document.getElementById('listWeekMain') : document.getElementById('listMonthMain')
        var myChart = echarts.init(chartDom);
        var option;
        option = {
          title: {
            text: '缺陷率趋势图'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['缺陷数量', '缺陷率'],
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          // toolbox: {
          //   feature: {
          //     saveAsImage: {}
          //   }
          // },
          xAxis: {
            type: 'category',
            // boundaryGap: false,
            data: listXAxisData
          },
          yAxis: [
            {
              type: 'value',
              name: '缺陷数量',
              // min: 0,
              // max: 250,
              // interval: 50,
              // axisLabel: {
              //   formatter: '{value} ml'
              // }
            },
            {
              type: 'value',
              name: '缺陷率',
              // min: 0,
              // max: 25,
              // interval: 5,
              axisLabel: {
                formatter: '{value} %'
              }
            }
          ],
          series: [
            {
              name: '缺陷数量',
              type: 'bar',
              barWidth: '3%',
              data: listNumArr,
              // label: {
              //   show: true, //开启显示
              //   position: 'top', //在上方显示
              //   // formatter: '{c}%',//显示百分号
              //   textStyle: { //数值样式
              //     color: 'black',//字体颜色
              //     fontSize: 12//字体大小
              //   }
              // }
            },
            {
              name: '缺陷率',
              type: 'line',
              yAxisIndex: 1,
              tooltip: {
                valueFormatter: function (value) {
                  return value + '%';
                }
              },
              data: listRatioArr
            }
          ]
        }
        option && myChart.setOption(option);
      })
    },
    /** 获取搜索栏的产线列表 */
    async getDict() {
      // const res = await getProductList()
      // const result = await getWorkOrderList()
      const res = await this.$axios({
        url: '/base/quality-isra-standards/page',
        method: 'get',
        params: {
          pageSize: 100,
          pageNo:1
        }
      });
      console.log(res)
      this.searchBarFormConfig[0].selectOptions = res.data.list
      // this.searchBarFormConfig[1].selectOptions = res.data.map((item) => {
      //   return {
      //     name: item.name,
      //     id:item.id
      //   }
      // })
      // this.searchBarFormConfig[0].selectOptions = result.data.map((item) => {
      //   return {
      //     name: item.name,
      //     id: item.id
      //   }
      // })
    },
		// getProductLineList() {
		// 	this.$axios('/base/production-line/listAll').then((response) => {
		// 		this.searchBarFormConfig[0].selectOptions = response.data.map(
		// 			(item) => {
		// 				return {
		// 					name: item.name,
		// 					id: item.id,
		// 				};
		// 			}
		// 		);
		// 	});
    // },
    getList() {
      this.getDataList()
    },
		/** 查询列表 */
    async getDataList() {
      console.log(this.queryParams);
			this.loading = true;
			// 执行查询
      const {
        data: { data, otherList, otherMap, nameData },
      } = await getQualityIsraPage(this.queryParams)
      console.log(this.queryParams);
      this.dynamicProps = this.filterNameData(nameData)
      this.list = this.filterData(data);
    },
    filterNameData(nameData) {
      const ndSet = new Set();
      nameData.forEach((nd) => {
        ndSet.add(nd.name);
      });
      return Array.from(ndSet.values())
        .sort()
        .map((name) => ({
          prop: name,
          label: name,
        }));
    },
    filterData(data) {
      return data.map((item) => {
        const { data: innerData } = item;
        const keyValuePairs = {};
        innerData.map((d) => {
          keyValuePairs[d.dynamicName] = d.dynamicValue;
        });
        return {
          // inspectionContent: item.inspectionContent,
          ...keyValuePairs,
          sumNum: item.sumNum,
          // sumInput: item.sumInput,
          // productionName: item.productionName,
          checkType: item.checkType,
          // scrapRatio: item.scrapRatio,
        };
      });
    },
		/** 取消按钮 */
    handleSearchBarBtnClick(val) {
      if (val.btnName === 'search') {
        this.queryParams.checkType = val.checkType ? val.checkType : undefined
        // this.queryParams.productionId = val.productionId ? val.productionId : undefined
        this.queryParams.startTime = val.checkTime ? val.checkTime[0] : undefined
        this.queryParams.endTime = val.checkTime ? val.checkTime[1] : undefined

        this.getList()
        this.getData()
      }
     console.log(val);
    }
	},
};
</script>
<style  lang="scss">
.blue-title {
  position: relative;
  padding: 4px 0;
  padding-left: 12px;
  font-size: 14px;
  color: #606266;
  font-weight: 700;
  margin-bottom: 12px;

  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 6px;
    height: 16px;
    width: 4px;
    border-radius: 1px;
    background: #0b58ff;
  }
}
</style>
