<template>
  <div class="app-container">
    <el-card>
      <div style="margin: 7px 0">
        <span style="margin-left: 10px">时间：</span>
        <el-date-picker
          v-model="dateTime"
          size="small"
          type="daterange"
          align="center"
          style="width: 240px;"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          range-separator="～"
          start-placeholder="开始日期"
          end-placeholder="结束日期"/>
        <span>工位名称:</span>
        <el-select v-model="opName" placeholder="工位名称" size="small" style="width: 150px" @change="getMeasuringPosition()" @clear="measureContents = [];measureContent = ''">
          <el-option
            v-for="item in opNames"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <span>机型:</span>
        <el-select v-model="engineTypeValue" placeholder="请选择机型" filterable clearable size="small" style="width: 150px">
          <el-option
            v-for="item in engineType"
            :key="item.ID"
            :label="item.label"
            :value="item.value"
            size="mini"/>
        </el-select>
        <span>测量名称:</span>
        <el-select v-model="measuringPositionValue" placeholder="请选择测量位置" filterable clearable size="small" style="width: 150px">
          <el-option
            v-for="item in measuringPosition"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            size="mini"/>
        </el-select>
        <span>测量内容:</span>
        <el-select v-model="measureContent" placeholder="测量内容" clearable size="small" style="width: 150px;" >
          <el-option
            v-for="item in measureContents"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <span>样本容量:</span>
        <el-select v-model="sampleSize" placeholder="样本容量" clearable size="small" style="width: 70px;">
          <el-option
            v-for="item in sampleSizes"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <span>样本个数:</span>
        <el-select v-model="sampleNumber" placeholder="样本个数" clearable size="small" style="width: 70px;">
          <el-option
            v-for="item in sampleNumbers"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <el-button type="primary" plain size="small" icon="el-icon-search" style="margin-left: 5px" @click="getLine()">搜索</el-button>
        <div id="myChart" style="width: 1011px;height: 400px;margin: auto;margin-top: 20px;"/>
        <div id="myChart2" style="width: 1011px;height: 400px;margin: auto;margin-top: 20px;"/>
    </div></el-card>

  </div>
</template>

<script>
import { ExecDatabase } from '@/main'
import { GetBaseTrendData, GetMarkLineByConditent } from '@/api/SPCanalysis/QualityData_XS'
import request from '@/utils/request'

export default {
  data() {
    return {
      dateTime: '',
      opName: '',
      opNames: [],
      model: '',
      models: [],
      measureName: '',
      measureNames: [],
      measureContent: '',
      measureContents: [],
      engineTypeValue: '', // 机型
      engineType: [], // 机型
      measuringPosition: [], // 测量位置
      measuringPositionValue: '', // 测量位置
      sampleSize: '5',
      sampleSizes: [
        {
          value: '2',
          label: '2'
        }, {
          value: '3',
          label: '3'
        }, {
          value: '4',
          label: '4'
        }, {
          value: '5',
          label: '5'
        }, {
          value: '6',
          label: '6'
        }, {
          value: '7',
          label: '7'
        }, {
          value: '8',
          label: '8'
        }, {
          value: '9',
          label: '9'
        }
      ],
      sampleNumber: '20',
      sampleNumbers: [
        {
          value: '15',
          label: '15'
        }, {
          value: '20',
          label: '20'
        }, {
          value: '25',
          label: '25'
        }, {
          value: '30',
          label: '30'
        }
      ],
      tableData: [],
      listLoading: false,
      ucl_x: '',
      cl_x: '',
      lcl_x: '',
      ucl_s: '',
      cl_s: '',
      lcl_s: '',
      usl: '',
      sl: '',
      lsl: '',
      Cpk: '',
      CPL: '',
      CPU: '',
      YvalueXk: '',
      YvalueXr: '',
      YvalueZT: '',
      downloadLoading: '',
      nums: '', // 均值图
      nums1: '', // 极差图
      nums2: '', // 排列图表
      nums3: '', // 正态分布图
      average: '',
      MachineType: ''
    }
  },
  created() {
    var year, month, day, audiTime
    this.date = new Date() // 修改数据date
    year = new Date().getFullYear()
    month = new Date().getMonth() + 1 < 10 ? '0' + (new Date().getMonth() + 1) : new Date().getMonth() + 1
    day = new Date().getDate() < 10 ? '0' + new Date().getDate() : new Date().getDate()
    audiTime = year + '-' + month + '-' + day
    console.log(audiTime, 'audiTime')
    this.dateTime = [audiTime, audiTime]
    this.machineTypeSelect()
    this.measureSelect()
    this.getEngineType()
  },
  methods: {
    // 机型
    getEngineType() {
      this.engineType = []
      var param = []
      var Data = this.CreateData('11', 'MES_基本变量_机型代码_查询 ', param)
      this.ExecDatabase(Data).then(response => {
        // if (response.data.length) { this.engineTypeValue = response.data[0].发动机型标志 }
        for (let i = 0; i < response.data.length; i++) {
          this.engineType.push({
            label: response.data[i].发动机型号,
            value: response.data[i].发动机机型标志,
            ID: response.data[i].序号
          })
        }
      })
    },
    getMeasuringPosition() {
      this.measuringPosition = []
      var param = []
      param[0] = ['工位号', this.opName]
      var Data = this.CreateData('11', '质量数据查询_测量位置 ', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length) { this.measuringPositionValue = response.data[0].测量位置 }
        for (let i = 0; i < response.data.length; i++) {
          this.measuringPosition.push({
            label: response.data[i].测量位置,
            value: response.data[i].测量位置
          })
        }
      }).then(() => this.measureSelect())
    },
    // 获取工位名称
    machineTypeSelect() {
      this.opNames = []
      this.opName = ''
      request({
        url: '',
        method: 'post',
        data: {
          type: '3',
          name: `select distinct  工位号 from dbo.MES_基本变量_原始数据
            where 变量类型代码 = 101 or 变量类型代码 = 105 or 变量类型代码 = 104
            order by 工位号`
        }
      }).then(response => {
        if (response.data.length) {
          for (let i = 0; i < response.data.length; i++) {
            this.opNames.push({
              label: response.data[i].工位号,
              value: response.data[i].工位号
            })
          }
        }
      }).then(() => {
        this.measureSelect() // LLJ  新增 20191022
        this.getMeasuringPosition()
      })
    },
    // 获取测量内容
    // LLJ  新增 20191022
    measureSelect() {
      this.measureContents = []
      this.measureContent = ''
      var param = []
      param[0] = ['工位号', this.opName]
      param[1] = ['测量位置', this.measuringPositionValue]
      var Data = this.CreateData('11', '质量数据查询_测量项目', param)
      ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.measureContents.push({
            label: response.data[i].测量项目,
            value: response.data[i].测量项目
          })
        }
      }).then(() => {
        if (this.measureContents.length) this.measureContent = this.measureContents[0].value
      })
    },
    eval(fn) {
      var Fn = Function // 一个变量指向Function，防止有些前端编译工具报错
      return new Fn('return ' + fn)()
    },
    // 分析线及Y轴/X轴
    getLine() {
      let engineTypeValue_check, measuringPositionValue_check, measureContent_check
      if (this.opName) { this.opName_check = true } else { this.opName_check = false }
      this.engineTypeValue ? engineTypeValue_check = true : engineTypeValue_check = false
      this.measuringPositionValue ? measuringPositionValue_check = true : measuringPositionValue_check = false
      this.measureContent ? measureContent_check = true : measureContent_check = false
      GetMarkLineByConditent(this.opName_check, this.opName,
        measuringPositionValue_check, this.measuringPositionValue,
        measureContent_check, this.measureContent,
        engineTypeValue_check, this.engineTypeValue,
        this.dateTime[0], this.dateTime[1],
        this.sampleSize, this.sampleNumber).then(response => {
        this.ucl_x = parseFloat(response.data.split('|')[0].split(',')[0]).toFixed(2)
        this.cl_x = parseFloat(response.data.split('|')[0].split(',')[1]).toFixed(2)
        this.lcl_x = parseFloat(response.data.split('|')[0].split(',')[2]).toFixed(2)
        this.ucl_s = parseFloat(response.data.split('|')[0].split(',')[3]).toFixed(2)
        this.cl_s = parseFloat(response.data.split('|')[0].split(',')[4]).toFixed(2)
        this.lcl_s = parseFloat(response.data.split('|')[0].split(',')[5]).toFixed(2)
        this.YvalueXk = '['
        for (let i = 0; i < response.data.split('|')[1].split(',').length; i++) {
          this.YvalueXk += response.data.split('|')[1].split(',')[i]
          if (i !== response.data.split('|')[1].split(',').length - 1) {
            this.YvalueXk += ','
          }
        }
        this.YvalueXk += ']'
        this.YvalueXr = '['
        for (let i = 0; i < response.data.split('|')[2].split(',').length; i++) {
          this.YvalueXr += response.data.split('|')[2].split(',')[i]
          if (i !== response.data.split('|')[2].split(',').length - 1) {
            this.YvalueXr += ','
          }
        }
        this.YvalueXr += ']'
        this.YvalueZT = '['
        for (let i = 0; i < response.data.split('|')[3].split(',').length; i++) {
          this.YvalueZT += response.data.split('|')[3].split(',')[i]
          if (i !== response.data.split('|')[3].split(',').length - 1) {
            this.YvalueZT += ','
          }
        }
        this.YvalueZT += ']'
        this.XvalueZT = '['
        for (let i = 0; i < response.data.split('|')[4].split(',').length; i++) {
          this.XvalueZT += response.data.split('|')[4].split(',')[i]
          if (i !== response.data.split('|')[4].split(',').length - 1) {
            this.XvalueZT += ','
          }
        }
        this.XvalueZT += ']'
        this.YvalueXr = this.eval(this.YvalueXr)
        this.YvalueXk = this.eval(this.YvalueXk)
        this.searchChart()
      })
    },
    // 获取图形数据
    searchChart() {
      let engineTypeValue_check, measuringPositionValue_check, measureContent_check
      if (this.opName) { this.opName_check = true } else { this.opName_check = false }
      this.engineTypeValue ? engineTypeValue_check = true : engineTypeValue_check = false
      this.measuringPositionValue ? measuringPositionValue_check = true : measuringPositionValue_check = false
      this.measureContent ? measureContent_check = true : measureContent_check = false
      GetBaseTrendData(this.opName_check, this.opName,
        measuringPositionValue_check, this.measuringPositionValue,
        measureContent_check, this.measureContent,
        engineTypeValue_check, this.engineTypeValue,
        this.dateTime[0], this.dateTime[1],
        this.sampleSize, this.sampleNumber).then(response => {
        if (response.data) {
          this.nums = '['
          for (let i = 0; i < response.data.split('|')[0].split(',').length; i++) {
            this.nums += response.data.split('|')[0].split(',')[i]
            if (i !== response.data.split('|')[0].split(',').length - 1) {
              this.nums += ','
            }
          }
          this.nums += ']'
          this.nums1 = '['
          for (let i = 0; i < response.data.split('|')[1].split(',').length; i++) {
            this.nums1 += response.data.split('|')[1].split(',')[i]
            if (i !== response.data.split('|')[1].split(',').length - 1) {
              this.nums1 += ','
            }
          }
          this.nums1 += ']'
          this.nums3 = '['
          for (let i = 0; i < response.data.split('|')[2].split(',').length; i++) {
            this.nums3 += response.data.split('|')[2].split(',')[i]
            if (i !== response.data.split('|')[2].split(',').length - 1) {
              this.nums3 += ','
            }
          }
          this.nums3 += ']'
          this.nums = this.eval(this.nums)
          this.nums1 = this.eval(this.nums1)
          this.nums3 = this.eval(this.nums3)
          this.drawLine1(response.data)
          this.drawLine2(response.data)
        } else {
          this.$message.error('数据数量过少,无法统计')
        }
      })
    },
    drawLine1(res) {
      const myChart = this.$echarts.init(document.getElementById('myChart'))
      const _this = this
      myChart.clear()
      myChart.setOption({
        title: {
          left: 'center',
          text: '均值图'
        },
        tooltip: {
          trigger: 'axis'
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          data: this.nums
        },
        yAxis: {
          type: 'value',
          // min: this.lcl_x - this.lcl_x * 0.2,
          // max: function() {
          //   return parseFloat(_this.ucl_x) + parseFloat(_this.ucl_x) * 0.2
          // }
          min: parseFloat(this.lcl_x) - 200,
          max: parseFloat(_this.ucl_x) + 200
        },
        series: [
          {
            name: '测量值',
            type: 'line',
            data: this.nums,
            markLine: {
              data: [
                { yAxis: this.ucl_x, name: 'UCL' },
                { yAxis: this.cl_x, name: 'CL' },
                { yAxis: this.lcl_x, name: 'LCL' }
              ],
              label: {
                normal: {
                  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% 处的颜色
                  }]
                }
              }
            }
          }
        ]
      })
      this.ucl_x = ''
      this.cl_x = ''
      this.lcl_x = ''
    },
    drawLine2(res) {
      const myChart2 = this.$echarts.init(document.getElementById('myChart2'))
      const _this = this
      myChart2.clear()
      myChart2.setOption({
        title: {
          left: 'center',
          text: '标准差图'
        },
        tooltip: {
          trigger: 'axis'
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          data: this.nums1
        },
        yAxis: {
          type: 'value',
          min: this.lcl_s - this.lcl_s * 0.2,
          max: function() {
            return parseFloat(_this.ucl_s) + parseFloat(_this.ucl_s) * 0.2
          }
        },
        series: [
          {
            name: '测量值',
            type: 'line',
            data: this.nums1,
            markLine: {
              data: [
                { yAxis: this.ucl_s, name: 'UCL' },
                { yAxis: this.cl_s, name: 'CL' },
                { yAxis: this.lcl_s, name: 'LCL' }
              ],
              label: {
                normal: {
                  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% 处的颜色
                  }]
                }
              }
            }
          }
        ]
      })
      this.ucl_s = ''
      this.cl_s = ''
      this.lcl_s = ''
    },
    // 导出excel
    handleDownload() {
      this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['工件号', '工位号', '测量位置', '测量项目', '测量值', '测量单位', '理论值', '上限值', '下限值', '生产日期']
          const filterVal = ['JSON_发动机号', 'JSON_工位号', 'JSON_测量位置', 'JSON_测量项目', 'JSON_测量单位', 'JSON_测量值', 'JSON_理论值', 'JSON_上限值', 'JSON_下限值', 'JSON_生产日期']
          const list = this.tableData
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel(tHeader, data, '物料数据报表')
          this.downloadLoading = false
        })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        return v[j]
      }))
    }
  }
}
</script>

<style scoped>
  span{
    margin: 10px 0px 10px 10px;
  }
</style>
