<template>
  <div>
    <el-card>
      <span class="show-text">工位:</span>
      <el-select
        v-model="OpName"
        filterable
        placeholder="请选择工位号"
        size="small"
        style="width: 200px"
        @change="getCheckPosition">
        <el-option
          v-for="item in OpNameList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          size="mini"/>
      </el-select>
      <span class="show-text">采集时间:</span>
      <el-date-picker
        v-model="collectionTime"
        :clearable="false"
        :picker-options="pickerOptions"
        end-placeholder="结束时间"
        format="yyyy-MM-dd HH:mm:ss"
        popper-class="virtual-cell-time-picker"
        range-separator="-"
        start-placeholder="开始时间"
        style="width: 380px;margin-right: 16px;vertical-align: top"
        type="datetimerange"
        value-format="yyyy-MM-dd HH:mm:ss"
        @change="getCheckPosition"/>
      <span class="show-text">测量位置:</span>
      <el-select
        v-model="TestPosition"
        filterable
        placeholder="请选择测量位置"
        size="small"
        style="width: 200px"
      >
        <el-option
          v-for="item in checkPositionList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          size="mini"/>
      </el-select>
      <el-button icon="el-icon-search" type="primary" @click="searchTable()">查询</el-button>
      <div style="margin-top: 10px;display: flex">
        <div id="Echarts1" style="width: 1500px; height: 640px;"/>
        <!--        <div id="Echarts" style="width: 1500px; height: 640px;"/>-->
      </div>
    </el-card>
  </div>
</template>

<script>
import { getLine } from '@/api/FactoryCalendar'
import * as echarts from 'echarts'
import axios from 'axios'

export default {
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      OpName: '', // 工位号
      OpNameList: '', // 工位列表
      TestPosition: '', // 测量位置
      collectionTime: [], // 采集时间段
      checkPositionList: [],
      loading: false,
      tableData: [],
      cp: '',
      cpk: '',
      usl: '',
      qu: '',
      sl: '',
      lsl: '',
      ql: '',
      total: 0, // 总条数
      pageSize: 50, // 每页显示条数
      pageList: 1 // 后台获取页,
    }
  },
  created() {
    this.getOpName()
    var now = new Date()
    var start = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate(), 0, 0, 0)
    var end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59)
    this.collectionTime = [start, end]
    this.getCheckPosition()
    setTimeout(() => {
      this.searchTable()
    }, 500)
  },
  methods: {
    // 查询工位号
    getOpName() {
      var param = []
      var Data = this.CreateData('11', '工位与名称_查询', param)
      this.ExecDatabase(Data).then(response => {
        this.OpNameList = []
        for (const item of response.data) {
          this.OpNameList.push({ label: item.工位号, value: item.工位号 })
        }
        this.OpName = this.OpNameList[0].value
      })
    },
    // 查询
    searchTable() {
      if (this.collectionTime.length === 0) {
        this.$message.error('请选择需要查询的时间段！')
        return
      }
      if (this.OpName.length === 0) {
        this.$message.error('请选择工位号！')
        return
      }
      if (this.TestPosition.length === 0) {
        this.$message.error('请选择测量位置！')
        return
      }
      this.loading = true
      this.tableData = []
      var param = []
      param[0] = ['工位号', this.OpName]
      param[1] = ['开始时间', this.collectionTime[0]]
      param[2] = ['结束时间', this.collectionTime[1]]
      param[3] = ['测量位置', this.TestPosition]
      var Data = this.CreateData('11', 'SPC_临时表_增加', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data[0].result == 1) {
          // 再请求表格数据 获取前200条质量数据 拼接为数组后再向后端请求
          var param2 = []
          var Data2 = this.CreateData('11', '质量数据查询_综合查询_数据分组', param2)
          this.ExecDatabase(Data2).then(response => {
            if (response.data.length >= 200) {
              // 遍历拼接出数组
              const dataList = []
              for (const item of response.data) {
                dataList.push(item.测量值)
              }
              // 逐个图表请求数据 并且将返回数据渲染至网页
              // 基本趋势图
              this.setChart1(dataList)
              // 直方图
              // 工序能力分析
              // 排列图
              // 均值图
              // 极差图
              // 标准差图
            } else {
              this.$message.error('需要两百条质量数据统计，当前选择数据数量过少,无法统计')
            }
          })
          // this.initEcharts()
        }
      })
    },
    setChart1(dataList) {
      axios.post(window.dt_Config.spcEchartsAddress + '?type=GetBaseTrendData1', { 'dataList': dataList }).then(response => {
        let cp, cpk, usl, qu, sl, lsl, ql
        const markData = response.data.split(',')
        console.log(markData, 222)
        // cp = markData[6].slice(0, 4)
        // cpk = markData[5].slice(0, 4)
        // usl = parseFloat(markData[0]).toFixed(2)
        // // this.ql = parseFloat(markData[3]).toFixed(2)
        // qu = parseFloat(markData[1]).toFixed(2)
        // sl = parseFloat(markData[2]).toFixed(2)
        // lsl = parseFloat(markData[4]).toFixed(2)
        this.cp = markData[6].slice(0, 4)
        this.cpk = markData[5].slice(0, 4)
        this.usl = parseFloat(markData[0]).toFixed(2)
        // this.ql = parseFloat(markData[3]).toFixed(2)
        this.qu = parseFloat(markData[1]).toFixed(2)
        this.sl = parseFloat(markData[2]).toFixed(2)
        this.lsl = parseFloat(markData[4]).toFixed(2)
        axios.post(window.dt_Config.spcEchartsAddress + '?type=GetBaseTrendData2', { 'dataList': dataList }).then(res => {
          const myChart = echarts.init(document.getElementById('Echarts1'))
          console.log(res)
          const lineData = res.data.split(',')
          const xData = []
          const _this = this
          console.log(this.lsl - this.lsl * 0.2, this.lsl, 'lsl')
          console.log(parseFloat(_this.usl) + parseFloat(_this.usl) * 0.2, this.usl, 'max')
          for (let i = 0; i < lineData.length; i++) {
            xData[i] = i
          }
          myChart.clear()
          myChart.setOption({
            title: {
              left: 'center',
              text: '基本趋势图'
              // subtext: 'Cp=' + this.cp + ' Cpk=' + this.cpk
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: { // 坐标轴指示器，坐标轴触发有效
                type: 'line' // 默认为直线，可选为：'line' | 'shadow'
              }

            },
            toolbox: {
              show: true,
              orient: 'vertical',
              left: 'right',
              top: 'top',
              feature: {
                saveAsImage: { show: true } // 保存图表
              },
              right: '20'
            },
            legend: {
              orient: 'horizontal',
              right: '12%',
              data: [{ name: '不合格区域', icon: 'bar' }, { name: '合格区域', icon: 'bar' }, {
                name: '警告区域',
                icon: 'bar'
              }],

              selected: {
                '不合格区域': true,
                '合格区域': true,
                '警告区域': true
                // 不想显示的都设置成false
              }
            },
            color: ['#EE2C2C', '#7FFF00', '#f3d71c'],
            dataZoom: [
              {
                show: true,
                // realtime: false,
                textStyle: false,
                start: 0,
                end: 10
              }
            ],
            xAxis: {
              nameLocation: 'center',
              type: 'category',
              boundaryGap: true,
              data: xData,
              show: true,
              axisTick: {
                show: true
              }

            },
            yAxis: {
              type: 'value',
              min: (parseFloat(_this.lsl) - parseFloat(_this.lsl) * 2).toFixed(0),
              // max: function() {
              //   return parseFloat(_this.usl) + parseFloat(_this.usl) * 0.2
              // }
              max: (parseFloat(_this.usl) + parseFloat(_this.usl) * 1.5).toFixed(0)

              // scale: 'true'
            },
            series: [ // 就是从这个地方开始的    主要用的是markArea 和legend
              {
                name: '不合格区域',
                type: 'line',
                animation: false,
                areaStyle: {
                  normal: {}
                },
                lineStyle: {
                  normal: {
                    width: 1
                  }
                },
                markArea: {
                  data: [[{
                    yAxis: '0'
                  }, {
                    yAxis: this.lsl
                  }], [{
                    yAxis: this.usl
                  }, {
                    yAxis: 100000
                  }]]
                }

              }, {
                name: '合格区域',
                type: 'line',
                animation: false,
                areaStyle: {
                  normal: {}
                },
                lineStyle: {
                  normal: {
                    width: 1
                  }
                },
                markArea: {
                  data: [[{
                    yAxis: _this.usl + 300 - (parseFloat(_this.usl).toFixed(2) - parseFloat(_this.lsl).toFixed(2)) / 4 * 3
                  }, {
                    yAxis: parseFloat(_this.usl).toFixed(2) - (parseFloat(_this.usl).toFixed(2) - parseFloat(_this.lsl).toFixed(2)) / 4
                  }]]
                }
              }, {
                name: '警告区域',
                type: 'line',
                animation: false,
                areaStyle: {
                  normal: {}
                },
                lineStyle: {
                  normal: {
                    width: 1
                  }
                },
                markArea: {
                  data: [[{
                    yAxis: _this.lsl
                  }, {
                    yAxis: parseFloat(_this.usl).toFixed(2) - (parseFloat(_this.usl).toFixed(2) - parseFloat(_this.lsl).toFixed(2)) / 4 * 3
                  }], [{
                    yAxis: parseFloat(_this.usl).toFixed(2) - (parseFloat(_this.usl).toFixed(2) - parseFloat(_this.lsl).toFixed(2)) / 4
                  }, {
                    yAxis: this.usl
                  }]]
                }
              },
              {
                name: '测量值',
                type: 'line',
                data: lineData,
                markLine: {
                  data: [
                    { yAxis: this.usl, name: 'USL' },
                    { yAxis: this.lsl, name: 'LSL' },
                    // { yAxis: this.qu, name: 'QU' },
                    { yAxis: this.ql, name: 'QL' },
                    { yAxis: this.sl, name: 'SL' }
                  ],
                  label: {
                    normal: {
                      formatter: '{b} : {c}'
                    }
                    // color: function(params) {
                    //   var index_color = params.value
                    //
                    //   if (index_color >= 0) {
                    //     return '#fe4365'
                    //   } else {
                    //     return '#25daba'
                    //   }
                    // }
                  },
                  color: ['#81b22f', '#f3d71c', '#f4b9a9'],
                  lineStyle: {
                    color: {
                      type: 'radial',
                      x: 0.5,
                      y: 0.5,
                      r: 0.5,
                      colorStops: [{
                        offset: 0, color: 'red' // 0% 处的颜色
                      }, {
                        offset: 1, color: 'blue' // 100% 处的颜色
                      }],
                      globalCoord: false // 缺省为 false
                    }
                  }
                }
              }

            ]
            // visualMap: {
            //   show: false,
            //   type: 'piecewise',
            //   // seriesIndex: 2,
            //   pieces: [{
            //     gt: 10,
            //     background: 'green'
            //   }, {
            //     gt: 0,
            //     lte: 10,
            //     color: 'red'
            //   }]
            // },
            // series: [
            //   {
            //     name: '测量值',
            //     type: 'line',
            //     data: lineData,
            //     markLine: {
            //       data: [
            //         { yAxis: this.usl, name: 'USL' },
            //         { yAxis: this.lsl, name: 'LSL' },
            //         { yAxis: this.qu, name: 'QU' },
            //         { yAxis: this.ql, name: 'QL' },
            //         { yAxis: this.sl, name: 'SL' }
            //       ],
            //       label: {
            //         normal: {
            //           formatter: '{b} : {c}'
            //         }
            //         // color: function(params) {
            //         //   var index_color = params.value
            //         //
            //         //   if (index_color >= 0) {
            //         //     return '#fe4365'
            //         //   } else {
            //         //     return '#25daba'
            //         //   }
            //         // }
            //       },
            //       color: ['#81b22f', '#f3d71c', '#f4b9a9'],
            //       lineStyle: {
            //         color: {
            //           type: 'radial',
            //           x: 0.5,
            //           y: 0.5,
            //           r: 0.5,
            //           colorStops: [{
            //             offset: 0, color: 'red' // 0% 处的颜色
            //           }, {
            //             offset: 1, color: 'blue' // 100% 处的颜色
            //           }],
            //           globalCoord: false // 缺省为 false
            //         }
            //       }
            //     }
            //   }
            // ]
          })
          this.cp = ''
          this.cpk = ''
          this.usl = ''
          this.ql = ''
          this.qu = ''
          this.sl = ''
          this.lsl = ''
        })
      })
    },
    getCheckPosition() {
      this.checkPositionList = []
      this.TestPosition = ''
      var param = []
      param[0] = ['工位号', this.OpName]
      param[1] = ['开始时间', this.collectionTime[0]]
      param[2] = ['结束时间', this.collectionTime[1]]
      var Data = this.CreateData('11', 'SPC_测量位置_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) {
          // 添加到checkPositionList 下拉框
          for (let i = 0; i < response.data.length; i++) {
            this.checkPositionList.push({ label: response.data[i].测量项目, value: response.data[i].测量项目 })
          }
          this.TestPosition = this.checkPositionList[0].value
        }
      })
    },
    initEcharts() {
      getLine().then(response => {
        if (response.data.length !== 0) {
          this.leftTopColumnarOptionSet(response.data)
        } else {
          this.$message.error('需要两百条质量数据统计，当前选择数据数量过少,无法统计')
        }
      })
    },
    leftTopColumnarOptionSet(res) {
      const usl = parseFloat(res.split('|')[4].split(',')[0]).toFixed(4)
      const qu = parseFloat(res.split('|')[4].split(',')[1]).toFixed(4)
      const sl = parseFloat(res.split('|')[4].split(',')[2]).toFixed(4)
      const ql = parseFloat(res.split('|')[4].split(',')[3]).toFixed(4)
      const lsl = parseFloat(res.split('|')[4].split(',')[4]).toFixed(4)
      const cpk = parseFloat(res.split('|')[1].split(',')[6]).toFixed(2)
      const cp = parseFloat(res.split('|')[1].split(',')[5]).toFixed(2)
      const USL = parseInt(res.split('|')[4].split(',')[0])
      const QU = parseInt(res.split('|')[4].split(',')[1])
      const SL = parseInt(res.split('|')[4].split(',')[2])
      const QL = parseInt(res.split('|')[4].split(',')[3])
      const LSL = parseInt(res.split('|')[4].split(',')[4])
      const xData = res.split('|')[3].split(',')
      const xdata = []
      for (let i = 0; i < xData.length; i++) {
        xdata.push(xData[i])
      }
      const yData = res.split('|')[2].split(',')
      const ydata = []
      for (let i = 0; i < yData.length; i++) {
        ydata.push(yData[i])
      }
      const lineData = res.split('|')[0].split(',')
      const linedata = []
      for (let i = 0; i < lineData.length; i++) {
        linedata.push(lineData[i])
      }
      console.log(xData, 1, lineData, 2)
      const leftTopColumnarOption2 = {
        title: {
          left: 'center',
          text: '正态分布图',
          subtext: 'Cp=' + cp + ' Cpk=' + cpk,
          textStyle: {
            color: '#afafaf'
          }
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: xdata,
          show: false
        },
        yAxis: {
          type: 'value',
          scale: 'true'
        },
        series: [
          {
            smooth: true,
            showSymbol: false,
            name: '测量值',
            type: 'line',
            data: linedata,
            markLine: {
              data: [
                { xAxis: USL, name: 'USL', value: usl },
                { xAxis: LSL, name: 'LSL', value: lsl },
                { xAxis: QU, name: 'QU', value: qu },
                { xAxis: QL, name: 'QL', value: ql },
                { xAxis: SL, name: 'SL', value: sl }
              ],
              label: {
                normal: {
                  position: 'middle',
                  formatter: '{b} : {c}'
                }
              },
              lineStyle: {
                color: {
                  type: 'radial',
                  x: 0.5,
                  y: 0.5,
                  r: 0.5,
                  colorStops: [{
                    offset: 0, color: 'red' // 0% 处的颜色
                  }, {
                    offset: 1, color: 'blue' // 100% 处的颜色
                  }],
                  globalCoord: false // 缺省为 false
                }
              }
            }
          }
        ]
      }
      const doc = echarts.init(document.getElementById('Echarts'))
      doc.clear()
      doc.setOption(leftTopColumnarOption2)
    }
  }
}
</script>
