<template>
  <div class="app-container">
    <el-card>
      <el-row style="margin-top: 3px">
        <!--<span>生产日期:</span>-->
        <!--<el-date-picker-->
        <!--v-model="timeValue"-->
        <!--size="small"-->
        <!--style="width: 180px"-->
        <!--type="date"-->
        <!--format="yyyy-MM-dd"-->
        <!--value-format="yyyy-MM-dd"-->
        <!--placeholder="选择日期"-->
        <!--align="right"/>-->
        <span>开始日期:</span>
        <el-date-picker v-model="startTime" :clearable="false" size="small" type="date" value-format="yyyy-MM-dd" style="width:150px" placeholder="开始时间"/>
        <span>结束日期:</span>
        <el-date-picker v-model="endTime" :clearable="false" size="small" type="date" value-format="yyyy-MM-dd" style="width:150px" placeholder="结束时间"/>
        <span>工位名称:</span>
        <el-select v-model="opName" clearable placeholder="工位号" size="small" style="width: 150px " @change="opNameSelect()" @clear="opNameClear">
          <el-option
            v-for="item in opNames"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <span>零件号:</span>
        <el-select v-model="model" filterable clearable placeholder="零件号" size="small" style="width: 150px">
          <el-option
            v-for="item in models"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
      </el-row>
      <el-row>
        <span>测量位置:</span>
        <el-select v-model="measureName" placeholder="测量位置" size="small" style="width: 150px" @change="measureSelect">
          <el-option
            v-for="item in measureNames"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <span>测量内容:</span>
        <el-select v-model="measureContent" placeholder="测量内容" size="small" style="width: 150px;margin-top: 15px" >
          <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: 70px;margin-top: 15px">
          <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: 70px;margin-top: 15px">
          <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"/>
        <span>下限值:</span>
        <el-input-number v-model="input_Lsl" :step="1" :min="0" size="small"/>
        <el-button type="success" size="small" icon="el-icon-search" style="margin-left: 20px;margin-top: 15px" @click="searchData()">查询</el-button>
        <!--<el-button type="primary" size="small" icon="el-icon-download" style="margin-left: 10px;margin-top: 15px" @click="handleDownload">导出EXCEL</el-button>-->
      </el-row>
      <div style="margin-left: 3px; margin-top: 10px">
        <el-col :span="14">
          <el-table
            v-loading.body="listLoading"
            :data="tableData"
            border
            element-loading-text="Loading"
            stripe
            fit
            style="max-height: 700px;width: 100%"
            height="700"
            size="small">
            <el-table-column label="序号" width="50" align="left">
              <template slot-scope="scope" align="left">
                <span align="left" v-text="getIndex(scope.$index)"/>
              </template>
            </el-table-column>
            <el-table-column label="工位号" min-width="120" width="170" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.工位号 }}
              </template>
            </el-table-column>
            <el-table-column label="测量值" min-width="120" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.测量值 }}
              </template>
            </el-table-column>
            <el-table-column label="测量单位" min-width="120" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.测量单位 }}
              </template>
            </el-table-column>
            <el-table-column label="发动机号" min-width="200" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.发动机号 }}
              </template>
            </el-table-column>
            <el-table-column label="日期" min-width="160" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.生产日期 }}
              </template>
            </el-table-column>
          </el-table>
          <div class="block" style="margin-top: 10px">
            <el-pagination
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="20"
              :total="totalNum"
              style="width: 600px"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"/>
          </div>
        </el-col>
        <el-col :span="10">
          <el-card style="margin-top: 3px;width: 650px;">
            <div id="myChart" style="width: 99%;height: 640px;margin: 50px auto auto;"/>
          </el-card>
        </el-col>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ExecDatabase } from '@/main'
import { linegetList, 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_check: false,
      model_check: false,
      measureName_check: false,
      measureContent_check: false,
      opName: '',
      opNames: [],
      measureName: '',
      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'
        }, {
          value: '10',
          label: '10'
        }
      ],
      sampleNumber: '20',
      sampleNumbers: [
        {
          value: '15',
          label: '15'
        }, {
          value: '20',
          label: '20'
        }, {
          value: '25',
          label: '25'
        }, {
          value: '30',
          label: '30'
        }, {
          value: '35',
          label: '35'
        }, {
          value: '40',
          label: '40'
        }
      ],
      tableData: [],
      listLoading: false,
      currentPage: 1,
      pageSize: 20,
      pageCurrent: 1,
      totalNum: null,
      lineData: '',
      usl: '',
      qu: '',
      sl: '',
      ql: '',
      lsl: '',
      MachineType: '',
      barres: []
    }
  },
  watch: {
    opName() {
      this.opNameSelect()
      this.fetchData()
    }
  },
  created() {
    this.machineTypeSelect()
  },
  methods: {
    opNameClear() {
      this.measureNames = []
      this.measureName = ''
      this.measureContents = []
      this.measureContent = ''
      this.models = []
      this.model = ''
    },
    // 获取表格序号
    getIndex($index) {
      // 表格序号
      return (this.pageCurrent - 1) * this.pageSize + $index + 1
    },
    // 获取机型
    fetchData() {
      this.models = []
      var param = []
      param[0] = ['开始时间', this.startTime]
      param[1] = ['结束时间', this.endTime]
      param[2] = ['工位号', this.opName]
      var Data = this.CreateData('11', '质量数据查询_基本机型_北汽福田_查询', param)
      ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.models.push({
            label: response.data[i].发动机型号,
            value: response.data[i].发动机型号
          })
        }
      }).then(() => {
        this.model = this.models[0].value
      })
    },
    // 获取工位名称
    machineTypeSelect() {
      this.opNames = []
      this.opName = ''
      var param = []
      var Data = this.CreateData('11', '质量数据查询_工位号', param)
      ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.opNames.push({
            label: response.data[i].工位号,
            value: response.data[i].工位号
          })
        }
      })
    },
    // 获取测量位置
    opNameSelect() {
      if (this.opName) {
        this.measureNames = []
        this.measureName = ''
        var param = []
        param[0] = ['工位号', this.opName]
        var Data = this.CreateData('11', '质量数据查询_测量位置', param)
        ExecDatabase(Data).then(response => {
          this.measureNames = []
          this.measureName = ''
          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
          this.measureSelect()
        })
      }
    },
    // 获取测量项目
    measureSelect() {
      if (this.opName === '' || this.measureName === '') return
      this.measureContents = []
      this.measureContent = ''
      var param = []
      param[0] = ['工位号', this.opName]
      param[1] = ['测量位置', this.measureName]
      var Data = this.CreateData('11', '质量数据查询_测量项目', param)
      ExecDatabase(Data).then(response => {
        this.measureContents = []
        this.measureContent = ''
        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() {
      if (this.opName === '' || this.measureName === '' || this.measureContent === '') {
        this.$message.error('请选择完整的查询条件！')
        return
      }
      this.opName_check = !!this.opName
      // if (this.model) { this.model_check = true } else { this.model_check = false }
      this.model_check = this.model !== ''
      this.measureName_check = !!this.measureName
      this.measureContent_check = !!this.measureContent
      this.searchChart()
      linegetList(this.opName_check, this.opName, this.measureName_check, this.measureName, this.model_check, this.model, this.measureContent_check, this.measureContent, this.startTime, this.endTime, this.sampleSize, this.sampleNumber, this.pageSize, this.pageCurrent).then(response => {
        this.listLoading = true
        this.tableData = response.data.rows
        console.log(this.tableData)
        this.totalNum = parseInt(response.data.total)
        this.listLoading = false
      })
    },
    // 获取图形数据
    searchChart() {
      linegetLine(this.opName_check, this.opName, this.measureName_check, this.measureName, this.model_check, this.model, 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) {
      bargetLine(this.opName_check, this.opName, this.measureName_check, this.measureName, this.model_check, this.model, 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.model, 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 = ['JSON_工位号', 'JSON_测量值', 'JSON_生产日期']
          const list = this.tableData
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '工序能力分析表',
            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(lineres, barres, barxdata) {
      const usl = parseFloat(lineres.split('|')[4].split(',')[0]).toFixed(4)
      const qu = parseFloat(lineres.split('|')[4].split(',')[1]).toFixed(4)
      const sl = parseFloat(lineres.split('|')[4].split(',')[2]).toFixed(4)
      const ql = parseFloat(lineres.split('|')[4].split(',')[3]).toFixed(4)
      const lsl = parseFloat(lineres.split('|')[4].split(',')[4]).toFixed(4)
      const cpk = parseFloat(lineres.split('|')[1].split(',')[6]).toFixed(2)
      const cp = parseFloat(lineres.split('|')[1].split(',')[5]).toFixed(2)
      const USL = parseInt(lineres.split('|')[4].split(',')[0])
      const QU = parseInt(lineres.split('|')[4].split(',')[1])
      const SL = parseInt(lineres.split('|')[4].split(',')[2])
      const QL = parseInt(lineres.split('|')[4].split(',')[3])
      const LSL = parseInt(lineres.split('|')[4].split(',')[4])
      const xData = lineres.split('|')[3].split(',')
      const xdata = []
      for (let i = 0; i < xData.length; i++) {
        xdata.push(parseFloat(xData[i]).toFixed(2))
      }
      const yData = lineres.split('|')[2].split(',')
      const ydata = []
      for (let i = 0; i < yData.length; i++) {
        ydata.push(yData[i])
      }
      const lineData = lineres.split('|')[0].split(',')
      const linedata = []
      for (let i = 0; i < lineData.length; i++) {
        linedata.push(lineData[i])
      }
      // const temp = barres.split(',')
      // const bxdata = []
      // for (let i = 0; i < temp.length; i++) {
      //   xdata.push(temp[i])
      // }

      const max = Math.max(...barxdata)
      // const min = Math.min(...barxdata)
      const myChart = this.$echarts.init(document.getElementById('myChart'))
      myChart.clear()
      myChart.setOption({
        title: {
          left: 'center',
          text: '正态分布图',
          subtext: 'Cp=' + cp + ' Cpk=' + cpk
        },
        tooltip: {
          trigger: 'axis'
          // formatter: function(params) {
          //   var res = '测量值:' + params[0].name
          //   console.log(res)
          //   return res
          // }
        },
        xAxis: [{
          type: 'category',
          data: xdata,
          show: true }
          // { type: 'category',
        //   axisLine: { show: false },
        //   axisTick: { show: false },
        //   axisLabel: { show: false, interval: 0 },
        //   splitArea: { show: false },
        //   splitLine: { show: false },
        //   data: bxdata }
        // {
        //   type: 'category',
        //   data: xdata,
        //   show: true
        // }
        ],
        yAxis: [
          // 左边Y
          {
            type: 'value',
            scale: 'true'
          },
          // 右边Y
          {
            type: 'value',
            scale: 'true',
            name: '频数',
            min: 0,
            max: max + 10,
            interval: 10,
            axisLabel: {
              formatter: '{value}'
            }
          }
          // 右边y轴
          // {
          //   type: 'value',
          //   name: '增长',
          //   axisLabel: {
          //     show: true,
          //     interval: 'auto',
          //     formatter: '{value} %'
          //   },
          //   splitNumber: 10,
          //   splitLine: {
          //     show: true,
          //     lineStyle: {
          //       type: 'dashed'
          //     }
          //   },
          //   splitArea: {
          //     show: false
          //   }
          //   // max: 100,
          //   // interval: 10,
          // }
        ],
        series: [
          {
            smooth: true,
            showSymbol: false,
            name: '概率',
            type: 'line',
            data: linedata,
            xAxisIndex: '0',
            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
                }
              }
            }
          },
          {
            name: '频数',
            type: 'bar',
            symbol: 'emptyCircle',
            showAllSymbol: true, // 动画效果
            smooth: true, // 光滑的曲线
            yAxisIndex: '1',
            data: barxdata,
            // label: {
            //   normal: {
            //     show: true,
            //     position: 'top'
            //   }
            // }
            itemStyle: {
              normal: {
                color: '#ffb348',
                label: {
                  show: true,
                  formatter: '{c}',
                  textStyle: {
                    color: '#000000'
                  }
                }
              }
            }
          }
          // {
          //   name: '频数',
          //   type: 'line',
          //   symbol: 'emptyCircle',
          //   showAllSymbol: true, // 动画效果
          //   smooth: true, // 光滑的曲线
          //   yAxisIndex: '1',
          //   data: barxdata,
          //   // label: {
          //   //   normal: {
          //   //     show: true,
          //   //     position: 'top'
          //   //   }
          //   // }
          //   itemStyle: {
          //     normal: {
          //       color: '#ffb348',
          //       label: {
          //         show: true,
          //         formatter: '{c}',
          //         textStyle: {
          //           color: '#000000'
          //         }
          //       }
          //     }
          //   }
          // }
          // 右边Y轴的数据
          // {
          //   name: '增长',
          //   type: 'bar',
          //   symbol: 'emptyCircle',
          //   showAllSymbol: true, // 动画效果
          //   symbolSize: 3,
          //   smooth: true, // 光滑的曲线
          //   yAxisIndex: '1',
          //   itemStyle: {
          //     normal: {
          //       color: '#ffb348',
          //       label: {
          //         show: true,
          //         formatter: '{c}%',
          //         textStyle: {
          //           color: '#000000'
          //         }
          //       }
          //     }
          //   },
          //   data: [3, 9, 2, 5, 7, 10]
          // },
        ]
      })
    }
  }
}
</script>

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