<template>
  <div class="app-container">
    <el-card>
      <el-row style="margin-top: 3px">
        <span style="margin-left: 10px">生产日期：</span>
        <el-date-picker
          :clearable = "false"
          v-model="dateTime"
          size="small"
          type="daterange"
          align="center"
          style="width: 250px;"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          range-separator="～"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
        <span>产品型号：</span>
        <el-select v-model="model" placeholder="请选择产品型号" size="small" clearable style="width: 150px">
          <el-option
            v-for="item in models"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            size="mini"/>
        </el-select>
        <span>工位号：</span>
        <el-select v-model="opName" clearable placeholder="工位名称" size="small" style="width: 180px " @change="measureSelect(opName)" @clear="measureContents = [];measureContent = ''">
          <el-option
            v-for="item in opNames"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <span style="margin-left: 10px">产品编号：</span>
        <el-input v-model="assemblyNumberValue" style="width:240px;" placeholder="产品编号" size="small" clearable/>
      </el-row>
      <el-row style="margin-bottom: 5px;margin-top: 10px">
        <span>测量项目：</span>
        <el-select v-model="measureContent" placeholder="测量项目" size="small" style="width: 250px;" >
          <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="样本容量" size="small" style="width: 83px">
          <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="样本个数" size="small" style="width: 83px">
          <el-option
            v-for="item in sampleNumbers"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <!--        <span>上限值：</span>-->
        <!--        <el-input-number v-model="input_Usl" :step="1" :min="0" size="small" style="width: 120px"/>-->
        <!--        <span>下限值：</span>-->
        <!--        <el-input-number v-model="input_Lsl" :step="1" :min="0" size="small" style="width: 120px"/>-->
        <el-button type="success" size="small" icon="el-icon-search" style="margin-left: 20px;" @click="searchData(),searchChart()">查询</el-button>
        <el-button type="primary" size="small" icon="el-icon-download" style="margin-left: 10px;" @click="handleDownload">导出</el-button>
        <div style="display: inline-block">
          <el-col :span="11">
            <el-table
              v-loading.body="listLoading"
              :data="tableData"
              :header-cell-style="{background:'#eef1f6',color:'#606266'}"
              border
              element-loading-text="Loading"
              stripe
              fit
              style="width: 100%"
              height="610"
              size="small">
              <el-table-column label="序号" width="50" type="index" align="left" />
              <el-table-column label="工位号" width="100" align="center">
                <template slot-scope="scope">
                  {{ scope.row.工位号 }}
                </template>
              </el-table-column>
              <el-table-column label="产品编号" width="100" align="center">
                <template slot-scope="scope">
                  {{ scope.row.发动机号 }}
                </template>
              </el-table-column>
              <el-table-column label="测量值" align="center" width="70">
                <template slot-scope="scope">
                  {{ scope.row.测量值 }}
                </template>
              </el-table-column>
              <el-table-column label="测量项目" align="center">
                <template slot-scope="scope">
                  {{ scope.row.测量项目 }}
                </template>
              </el-table-column>
              <el-table-column label="测量时间" align="center" width="150">
                <template slot-scope="scope">
                  {{ scope.row.生产日期 }}
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="13">
            <div style="width: 700px;border: 1px solid #00893d">
              <div id="myChart" style="width: 99%;height: 610px;"/>
            </div>
          </el-col>

        </div>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import { ExecDatabase } from '@/main'
import { linegetLine, bargetxData, bargetLine } from '@/api/SPCanalysis/normal_distribution'
import { getNowTime, getNowTime2 } from '@/utils/tool'

export default {
  data() {
    return {
      input_Usl: 0,
      input_Lsl: 0,
      startTime: getNowTime2(),
      endTime: getNowTime(),
      model: '',
      models: [],
      opName: '',
      dateTime: [], // 时间
      opNames: [],
      measureName: '',
      assemblyNumberValue: '',
      measureNames: [],
      measureContent: '',
      measureContents: [],
      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: [],
      tableDataX: [],
      tableDataY: [],
      listLoading: false,
      currentPage: 1,
      pageSize: 20,
      pageCurrent: 1,
      totalNum: null,
      lineData: '',
      usl: '',
      qu: '',
      sl: '',
      ql: '',
      lsl: '',
      MachineType: '',
      barres: []
    }
  },
  watch: {
    opName(val) {
    }
  },
  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
    this.dateTime = [audiTime, audiTime]
    // this.fetchData()
    this.getEndStation()
    this.getStationNumber()
    // this.measureSelect()
  },
  methods: {
    // 获取表格序号
    getIndex($index) {
      // 表格序号
      return (this.pageCurrent - 1) * this.pageSize + $index + 1
    },
    // 初始化获取产品型号
    getEndStation() {
      this.models = []
      var param = []
      var Data = this.CreateData('11', 'CATL_基础信息_机型信息_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) this.engineTypeValue = response.data[0].机型ID
        for (let i = 0; i < response.data.length; i++) {
          this.models.push({
            label: response.data[i].机型号,
            value: response.data[i].机型ID
          })
        }
      })
    },
    // 工位号
    getStationNumber() {
      this.opNames = []
      var param = []
      var Data = this.CreateData('11', 'MES_计划BOM_工位与名称_查询', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.opNames.push({
            label: response.data[i].工位号,
            value: response.data[i].工位号
          })
        }
      }).then(() => {
        // this.getBatchBarcode()
        // this.getMeasuringPosition()
      })
    },
    // 获取测量名称
    opNameSelect() {
      if (this.opName) {
        this.measureNames = []
        this.measureName = ''
        var param = []
        param[0] = ['工位号', this.opName]
        var Data = this.CreateData('11', '质量数据查询_测量位置_大柴', param)
        ExecDatabase(Data).then(response => {
          for (let i = 0; i < response.data.length; i++) {
            this.measureNames.push({
              label: response.data[i].测量位置,
              value: response.data[i].测量位置
            })
          }
        }).then(() => {
          this.measureName = this.measureNames[0].value
        })
      }
    },
    // 获取测量内容
    // LLJ  新增 20191022
    measureSelect(opname) {
      if (!opname) { return }
      this.measureContents = []
      this.measureContent = ''
      var param = []
      param[0] = ['工位号', opname]
      var Data = this.CreateData('11', '质量数据查询_测量项目_LLJ', 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(() => {
        this.measureContent = this.measureContents[0].value
      })
    },
    // 获取表格数据
    searchData() {
      this.tableData = []
      if (this.opName) { this.opName_check = true } else { this.opName_check = false }
      if (this.model) { this.model_check = true } else { this.model_check = false }
      if (this.MachineType !== '') { this.model_check = true } else { this.model_check = false }
      if (this.assemblyNumberValue !== '') { this.Machine_check = true } else { this.Machine_check = false }
      if (this.measureName) { this.measureName_check = true } else { this.measureName_check = false }
      if (this.measureContent) { this.measureContent_check = true } else { this.measureContent_check = false }
      var param = []
      param[0] = ['开始时间', this.dateTime[0] + ' ' + '00:00:00']
      param[1] = ['结束时间', this.dateTime[1] + ' ' + '23:59:59']
      param[2] = ['机型代码_ischeck', this.model_check]
      param[3] = ['机型代码', this.MachineType]
      param[4] = ['发动机号_ischeck', this.Machine_check]
      param[5] = ['发动机号', this.assemblyNumberValue]
      param[6] = ['工位号_ischeck', this.opName_check]
      param[7] = ['工位号', this.opName]
      param[8] = ['测量位置_ischeck', this.measureName_check]
      param[9] = ['测量位置', this.measuringPositionValue]
      param[10] = ['测量项目_ischeck', this.measureContent_check]
      param[11] = ['测量项目', this.measureContent]
      param[12] = ['k', this.sampleSize]
      param[13] = ['n', this.sampleNumber]
      var Data = this.CreateData('11', '质量数据查询_综合查询_数据分组', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length !== 0) {
          this.tableData = response.data
          this.drawLine(this.tableData)
        } else {
          this.$message.error('暂无数据')
          this.drawLine([])
        }
        this.loading = false
      })
    },
    // 获取图形数据
    searchChart() {
      if (this.opName) { this.opName_check = true } else { this.opName_check = false }
      // if (this.model) { this.model_check = true } else { this.model_check = false }
      if (this.MachineType !== '') { this.model_check = true } else { this.model_check = false }
      if (this.measureName) { this.measureName_check = true } else { this.measureName_check = false }
      if (this.measureContent) { this.measureContent_check = true } else { this.measureContent_check = false }
      linegetLine(this.opName_check, this.opName, this.measureName_check, this.measureName, this.model_check, this.MachineType, this.measureContent_check, this.measureContent, this.startTime, this.endTime, this.sampleSize, this.sampleNumber, this.input_Usl, this.input_Lsl).then(response => {
        if (response.data.length !== 0) {
          this.searchChart2(response.data)
        } else {
          this.$message.error('数据数量过少,无法统计')
        }
      })
    },
    // 获取图形数据
    searchChart2(res) {
      if (this.opName) { this.opName_check = true } else { this.opName_check = false }
      // if (this.model) { this.model_check = true } else { this.model_check = false }
      if (this.MachineType !== '') { this.model_check = true } else { this.model_check = false }
      if (this.measureName) { this.measureName_check = true } else { this.measureName_check = false }
      if (this.measureContent) { this.measureContent_check = true } else { this.measureContent_check = false }
      bargetLine(this.opName_check, this.opName, this.measureName_check, this.measureName, this.model_check, this.MachineType, this.measureContent_check, this.measureContent, this.startTime, this.endTime, this.sampleSize, this.sampleNumber).then(response => {
        this.lineData = response.data.split(',')
        bargetxData(this.opName_check, this.opName, this.measureName_check, this.measureName, this.model_check, this.MachineType, this.measureContent_check, this.measureContent, this.startTime, this.endTime, this.sampleSize, this.sampleNumber).then(response => {
          // this.drawLine(response.data, this.lineData)
          this.barres = response.data
          this.drawLine(res, this.barres, this.lineData)
        })
      })
    },
    // 分页功能改变显示数量
    handleSizeChange(val) {
      this.pageSize = val
      this.searchData()
    },
    // 分页功能改变当前页
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.searchData()
    },
    // 导出excel
    handleDownload() {
      this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          // console.log(this.tableData)
          const tHeader = ['工位号', '产品编号', '测量值', '测量项目', '测量时间']
          const filterVal = ['工位号', '发动机号', '测量值', '测量项目', '生产日期']
          const list = this.tableData
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'SPC数据表',
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
          this.downloadLoading = false
        })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        return v[j]
      }))
    },

    // drawLine(res) {
    //   const myChart = this.$echarts.init(document.getElementById('myChart'), null, { renderer: 'svg' })
    //   myChart.clear()
    //   var lnList = ['一年级', '二年级', '三年级', '四年级', '五年级', '六年级']// 类目轴X轴数据
    //   var scoreList = [88, 90, 77, 80, 82, 60, 70]// 为类目轴所对应y轴数值
    //   var optionList = [] // 第二轴数据与上类似
    //   var option = {
    //
    //     xAxis: [{
    //       type: 'category',
    //       data: lnList,
    //       axisLabel: {
    //         interval: 0,
    //         formatter: function(value) {
    //           return value.split('').join('\n')// 此处为类目轴X轴文字反转竖排,由于lz是做的手机端h5
    //         }
    //       },
    //       axisTick: {
    //         'show': false // x轴刻度线,true为显示, fase为不显示
    //       }
    //     }, {
    //       type: 'value', // 第二个X轴为数值轴不需要提供数据, 根据数值自适应
    //       scale: true
    //     }],
    //     yAxis: [{
    //       type: 'value',
    //       name: 'M值',
    //       max: 3.5,
    //       nameLocation: 'end',
    //       interval: 0.5
    //       /* axisLabel: {
    //            show: true,
    //            textStyle: {
    //                color: 'black'
    //            },
    //            formatter: function (value) {			//;利用回调 y轴上数值显示对应的文字
    //                var texts = []
    //                if (value === 1.5 || value === '1.5') {
    //                    texts.push('无')
    //                } else if (value === 2.5 || value === '2.5') {
    //                    texts.push('轻')
    //                } else if (value === 3.5 || value === '3.5') {
    //                    texts.push('中')
    //                } else if (value === 4.5 || value === '4.5') {
    //                    texts.push('重')
    //                } else if (value === 5.5) {
    //                    texts.push('严重')
    //                }
    //                return texts
    //            }
    //        }*/
    //     }],
    //     series: [{
    //       name: '分类',
    //       data: scoreList,
    //       type: 'bar',
    //       barWidth: 10,
    //       markLine: {
    //         symbol: 'none',
    //         label: {
    //           position: 'end', // 将警示值放在哪个位置，三个值“start”,“middle”,“end” 开始 中点 结束
    //
    //           formatter: function(data) { // 警戒线回调, 对应X轴数值
    //             console.log(data)
    //             if (data.value === 1.5) {
    //               return '警戒'
    //             } else {
    //               return ''
    //             }
    //           },
    //           color: 'red',
    //           fontSize: 10
    //         },
    //         data: [
    //           {	name: '目标值',
    //             yAxis: 1.5, // res.targetTwo,
    //             lineStyle: {
    //               color: '#F70000'
    //             }
    //           }
    //         ]
    //       },
    //       itemStyle: {
    //         normal: {
    //           color: function(params) {	// 根据值的不同柱状图可以显示不同的颜色,lz需求只显示一种颜色,忘了删掉这段了,						正好安利一下
    //             if (params.value < 1.50) {
    //               return '#999'
    //             } else if (params.value >= 1.50 && params.value <= 2.50) {
    //               return '#999'
    //             } else if (params.value >= 2.50 && params.value <= 3.50) {
    //               return '#999'
    //             } else if (params.value >= 3.50 && params.value <= 4.50) {
    //               return '#999'
    //             } else if (params.value >= 4.50) {
    //               return '#999'
    //             }
    //           }
    //         }
    //       }
    //     }, {
    //       name: '题号', // 此为第二轴数据
    //       type: 'scatter',
    //       data: optionList,
    //       symbolSize: 4,
    //       itemStyle: {
    //         color: '#999'
    //       }
    //     }]
    //   }
    //   myChart.setOption(option)
    // }
    //  绘制图形
    drawLine(tableData) {
      this.tableDataX = []
      this.tableDataY = []
      for (let i = 0; i < tableData.length; i++) {
        this.tableDataX.push(i + 1)
        this.tableDataY.push(tableData[i].测量值)
      }
      const myChart = this.$echarts.init(document.getElementById('myChart'))
      myChart.clear()
      myChart.setOption({
        title: {
          left: 'center',
          text: '数据分布图'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: this.tableDataX
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: this.tableDataY,
            type: 'line'
          }
        ]
      })
    }
  }
}
</script>

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