<template>
  <div class="app-container">
    <el-card>
      <el-row>
        <span style="margin-left: 10px">时间：</span>
        <el-date-picker
          v-model="dateTime"
          :clearable="false"
          size="small"
          type="daterange"
          align="center"
          style="width: 250px;"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="searchData();searchChart()"/>
        <span>工位名称:</span>
        <el-select
          v-model="opName"
          placeholder="工位号"
          size="small"
          style="width: 150px"
          @change="searchData();searchChart()"
          @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" placeholder="请选择零件号" filterable clearable size="small" style="width: 150px">-->
        <!--  <el-option-->
        <!--    v-for="item in models"-->
        <!--    :key="item.value"-->
        <!--    :label="item.label"-->
        <!--    :value="item.value"-->
        <!--    size="mini"/>-->
        <!--</el-select>-->
      </el-row>
      <el-row style="margin-top: 10px">
        <span>测量名称:</span>
        <el-select
          v-model="measureName"
          placeholder="请选择测量位置"
          size="small"
          clearable
          style="width: 150px">
          <el-option
            v-for="item in measureNames"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            size="mini"/>
        </el-select>
        <span>测量内容:</span>
        <el-select v-model="measureContent" clearable placeholder="测量内容" size="small" style="width: 150px;">
          <el-option
            v-for="item in measureContents"
            :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="pageSize = 20 ;pageCurrent = 1;searchData();searchChart()">搜索
        </el-button>
        <el-button
          type="info"
          size="small"
          icon="el-icon-download"
          style="margin-left: 10px;margin-top: 15px"
          @click="handleDownload">Excel
        </el-button>
        <!--        <el-button-->
        <!--          type="info"-->
        <!--          size="small"-->
        <!--          icon="el-icon-download"-->
        <!--          style="margin-left: 10px;margin-top: 15px"-->
        <!--          @click="importOrder">导入-->
        <!--        </el-button>-->
      </el-row>

      <el-row style="margin-top: 10px">
        <div style="border: 1px solid #EBEEF5;width: 100%;height: 400px;margin-top: 7px">
          <div id="myChart" style="width: 100%;height: 380px;float: right;"/>
        </div>
        <el-table
          :data="tableData"
          border
          element-loading-text="Loading"
          fit
          class="main"
          height="350px"
          style="width: 100%;"
          size="small">
          <el-table-column label="序号" prop="" width="80" align="center">
            <template slot-scope="scope" align="left">
              <span v-text="getIndex(scope.$index)"/>
            </template>
          </el-table-column>
          <el-table-column label="发动机号" min-width="200px" align="center">
            <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">
            <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">
            <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">
            <template slot-scope="scope">
              {{ scope.row.理论值 }}
            </template>
          </el-table-column>
        </el-table>
        <div class="block" style="width: 600px">
          <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-row>
    </el-card>
    <el-dialog :visible.sync="importVisible" center style="min-height: 200px" title="SPC数据导入" width="900px">
      <div class="app-container">
        <upload-excel-component style="margin-left: 15%" @getSheetName="getSheetName" @on-selected-file="selected"/>
        <div style="margin-left: 395px">
          <span v-show="worksheet.length > 1" style="cursor: pointer;width: 50px;" @click="removeAll"><i
            class="el-icon-close"/></span>
          <el-upload
            :file-list="itemFile"
            :sheet-names="sheetNames"
            :on-remove="handleRemove"
            action=""
            style="width: 220px"/>
        </div>
        <div v-if="worksheet.length !== 0" style="margin: 3px 0 0 395px">
          <el-button icon="el-icon-upload2" size="small" type="primary" @click="basicPartsToSQL">导入到数据库
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ExecDatabase } from '@/main'
import { getEchart, getLine } from '@/api/SPCanalysis/basicTrendTap'
import { getNowTime, getNowTime2 } from '@/utils/tool'
import UploadExcelComponent from './UploadExcel.vue'
import request from '@/utils/request'

export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      input_Usl: 0,
      input_Lsl: 0,
      dateTime: '',
      opName: '',
      opNames: [],
      model: '',
      models: [],
      measureName: '',
      measureNames: [],
      measureContent: '',
      measureContents: [],
      uuid: '',
      listLoading: false,
      cp: '',
      cpk: '',
      usl: '',
      qu: '',
      sl: '',
      lsl: '',
      ql: '',
      currentPage: 1,
      pageSize: 20,
      pageCurrent: 1,
      totalNum: null,
      downloadLoading: '',
      MachineType: '',
      importVisible: false,
      worksheet: [],
      itemFile: [],
      sheetNames: [],
      tableData: [] // 总数据数组
    }
  },
  watch: {
    opName() {
      // 基本数据不存在 数据库中 无法获取到测量位置
      this.opNameSelect()
      // this.fetchData()
    }
  },
  created() {
    this.dateTime = [getNowTime2(), getNowTime()]
    this.machineTypeSelect()
  },
  methods: {
    // 获取表格序号
    getIndex($index) {
      // 表格序号
      return (this.pageCurrent - 1) * this.pageSize + $index + 1
    },
    opNameClear() {
      this.measureNames = []
      this.measureName = ''
      this.measureContents = []
      this.measureContent = ''
      this.models = []
      this.model = ''
    },
    // 获取机型
    fetchData() {
      this.models = []
      this.model = ''
      var param = []
      param[0] = ['开始时间', this.dateTime[0]]
      param[1] = ['结束时间', this.dateTime[1]]
      param[2] = ['工位号', this.opName]
      var Data = this.CreateData('11', '质量数据查询_基本机型_查询', param)
      ExecDatabase(Data).then(response => {
        this.models = []
        this.model = ''
        for (let i = 0; i < response.data.length; i++) {
          this.models.push({
            label: response.data[i].发动机型号,
            value: response.data[i].发动机型号
          })
        }
        if (this.models.length === 0) {
          this.$message.error('暂无数据')
          return
        }
        // this.model = this.models[0].value
      })
    },
    // 获取工位名称
    machineTypeSelect() {
      this.opNames = []
      this.opName = ''
      var param = []
      var Data = this.CreateData('11', 'MES_计划BOM_工位与名称_查询', 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].工位号
          })
        }
        this.opName = this.opNames[0].value
      })
    },
    // 获取测量位置
    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 = ''
    },

    searchData() {
      this.tableData = []
      this.listLoading = true
      let engineTypeValue_check, measuringPositionValue_check, measureContent_check, uuid_check
      if (this.opName) {
        this.opName_check = true
      } else {
        this.opName_check = false
      }
      if (this.model !== '') {
        engineTypeValue_check = 1
      } else {
        engineTypeValue_check = 0
      }
      if (this.measureName !== '') {
        measuringPositionValue_check = 1
      } else {
        measuringPositionValue_check = 0
      }
      if (this.measureContent !== '') {
        measureContent_check = 1
      } else {
        measureContent_check = 0
      }
      if (this.uuid !== '') {
        uuid_check = 1
      } else {
        uuid_check = 0
      }
      var param = []
      param[0] = ['结束时间', this.dateTime[1]]
      param[1] = ['开始时间', this.dateTime[0]]
      param[2] = ['测量位置_ischeck', measuringPositionValue_check]
      param[3] = ['测量位置', this.measureName]
      param[4] = ['测量项目', this.measureContent]
      param[5] = ['发动机型号代码', this.model]
      param[6] = ['发动机型号代码_ischeck', engineTypeValue_check]
      param[7] = ['工位号', this.opName]
      param[8] = ['工位号_ischeck', this.opName_check]
      param[9] = ['PageCount', 1000, 'int', '1']
      param[10] = ['ItemCount', 1000, 'int', '1']
      param[11] = ['PageCurrent', this.pageCurrent]
      param[12] = ['PageSize', this.pageSize]
      param[13] = ['测量项目_ischeck', measureContent_check]
      // param[14] = ['导入编号_ischeck', uuid_check]
      // param[15] = ['导入编号', this.uuid]
      var Data = this.CreateData('11', '质量数据_发动机质量数据_各个工位_视图_综合查询_趋势图', param)
      ExecDatabase(Data).then(response => {
        this.tableData = response.data.result
        console.log('this.tableData', this.tableData)
        this.totalNum = parseInt(response.data.output[0].ItemCount)
        this.listLoading = false

        // 在去查一遍去重的字段结果
        // opNames 工位号 models 零件号  measureNames 测量名称  measureContents  测量位置
        this.models = [] // 零件号
        this.measureNames = [] // 测量名称
        this.measureContents = [] // 测量内容
        param[14] = ['去重字段', '发动机型号']
        var Data2 = this.CreateData('11', 'SPC分析_去重字段_查询', param)
        ExecDatabase(Data2).then(response => {
          for (let i = 0; i < response.data.result.length; i++) {
            this.models.push({
              label: response.data.result[i].发动机型号,
              value: response.data.result[i].发动机型号
            })
          }
        })

        param[14] = ['去重字段', '测量位置']
        var Data3 = this.CreateData('11', 'SPC分析_去重字段_查询', param)
        ExecDatabase(Data3).then(response => {
          for (let i = 0; i < response.data.result.length; i++) {
            this.measureNames.push({
              label: response.data.result[i].测量位置,
              value: response.data.result[i].测量位置
            })
          }
        })

        param[14] = ['去重字段', '测量项目']
        var Data4 = this.CreateData('11', 'SPC分析_去重字段_查询', param)
        ExecDatabase(Data4).then(response => {
          for (let i = 0; i < response.data.result.length; i++) {
            this.measureContents.push({
              label: response.data.result[i].测量项目,
              value: response.data.result[i].测量项目
            })
          }
        })

        if (this.measureContents.length > 0) {
          // this.measureContent = this.measureContents[0].value
          // this.measureName = this.measureNames[0].value
        }
      })
    },
    // 获取图形数据
    searchChart() {
      const myChart = this.$echarts.init(document.getElementById('myChart'))
      myChart.clear()
      let engineTypeValue_check, measuringPositionValue_check, measureContent_check, uuid_check
      if (this.opName) {
        this.opName_check = true
      } else {
        this.opName_check = false
      }
      if (this.model !== '') {
        engineTypeValue_check = true
      } else {
        engineTypeValue_check = false
      }
      if (this.measureName !== '') {
        measuringPositionValue_check = true
      } else {
        measuringPositionValue_check = false
      }
      if (this.measureContent !== '') {
        measureContent_check = true
      } else {
        measureContent_check = false
      }
      if (this.uuid !== '') {
        uuid_check = 1
      } else {
        uuid_check = 0
      }
      console.log(this.opName_check, this.opName, measuringPositionValue_check, this.measureName, measureContent_check, this.measureContent, engineTypeValue_check, this.model, this.dateTime[0], this.dateTime[1], 2222)
      getLine(this.opName_check, this.opName, measuringPositionValue_check, this.measureName, measureContent_check, this.measureContent, engineTypeValue_check, this.model, this.dateTime[0], this.dateTime[1], this.pageSize, this.pageCurrent, uuid_check, this.uuid).then(response => {
        console.log(response.data, 111)
        if (response.data) {
          console.log(response.data, 111)
          const markData = response.data.split(',')
          console.log(markData, 222)
          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)
          let engineTypeValue_check, measuringPositionValue_check, measureContent_check
          if (this.opName) {
            this.opName_check = true
          } else {
            this.opName_check = false
          }
          this.model ? engineTypeValue_check = true : engineTypeValue_check = false
          this.measureName ? measuringPositionValue_check = true : measuringPositionValue_check = false
          this.measureContent ? measureContent_check = true : measureContent_check = false
          console.log(this.opName_check, this.opName, measuringPositionValue_check, this.measureName, measureContent_check, this.measureContent, engineTypeValue_check, this.model, this.dateTime[0], this.dateTime[1])
          getEchart(this.opName_check, this.opName, measuringPositionValue_check, this.measureName, measureContent_check, this.measureContent, engineTypeValue_check, this.model, this.dateTime[0], this.dateTime[1], uuid_check, this.uuid).then(response => {
            this.drawLine(response.data)
            this.uuid = ''
          })
        } else {
          this.$message.error('数据数量过少,无法统计')
        }
      })
    },
    // 分页功能改变显示数量
    handleSizeChange(val) {
      this.pageSize = val
      this.searchData()
    },
    // 分页功能改变当前页
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.searchData()
    },
    drawLine(res) {
      const myChart = this.$echarts.init(document.getElementById('myChart'))
      const lineData = res.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'
          }

        },
        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
          }
        ],
        toolbox: {
          feature: {
            restore: {},
            saveAsImage: {}
          },
          right: '30'
        },
        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 = ''
    },
    // 导入
    importOrder() {
      this.importVisible = true
    },
    getSheetName(val) {
      this.sheetNames = val
    },
    async selected(data) { // 选择需要导入的文件
      console.log(data, 1111)
      this.worksheet = data.worksheet // 获取每个多选文件的表格坐标及值
      this.itemFile = data.itemFile
    },
    removeAll() {
      this.worksheet = []
      this.itemFile = []
    },
    handleRemove(file) { // 移除文件
      for (let i = 0; i < this.itemFile.length; i++) {
        if (this.itemFile[i].name === file.name) {
          this.worksheet.splice(i, 1)
          this.itemFile.splice(i, 1)
        }
      }
    },
    async basicPartsToSQL() {
      try {
        this.loading = true
        this.err = 0
        console.log(this.worksheet.length, 'this.worksheet.length', this.itemFile)
        for (let j = this.worksheet.length - 1; j >= 0; j--) {
          let id,
            opName,
            project,
            position,
            value,
            unit,
            engineID,
            theoreticalValue

          const sheetName = this.itemFile[j]['name']
          console.log(sheetName, 'sheetName')
          const OpName = sheetName.split('-')[0]
          const EngineType = sheetName.split('-')[1]
          await this.importBeforeDispose()
          const itemList = []
          for (let i = 0; i < 500; i++) {
            const item = {}
            const attr = i + 2
            id = this.worksheet[j][`A${attr}`] ? this.worksheet[j][`A${attr}`].v : ''
            opName = this.worksheet[j][`B${attr}`] ? this.worksheet[j][`B${attr}`].v : ''
            project = this.worksheet[0][`C${attr}`] ? this.worksheet[0][`C${attr}`].v : ''
            position = this.worksheet[0][`D${attr}`] ? this.worksheet[0][`D${attr}`].v : ''
            value = this.worksheet[0][`E${attr}`] ? this.worksheet[0][`E${attr}`].v : ''
            unit = this.worksheet[0][`F${attr}`] ? this.worksheet[0][`F${attr}`].v : ''
            engineID = this.worksheet[0][`G${attr}`] ? this.worksheet[0][`G${attr}`].v : ''
            theoreticalValue = this.worksheet[0][`H${attr}`] ? this.worksheet[0][`H${attr}`].v : ''
            if (id != '' && opName != '' && project != '' && position != '' && value != '' && unit != '' && engineID != '' && theoreticalValue != '') {
              item.id = id
              item.opName = opName
              item.project = project
              item.position = position
              item.value = value
              item.unit = unit
              item.engineID = engineID
              item.theoreticalValue = theoreticalValue
              itemList.push(item)
            }
          }
          console.log('itemList', itemList)
          await this.insertToSQL(itemList)
          this.itemFile.splice(j, 1)
          this.worksheet.splice(j, 1)
          this.err === 0 ? this.$message.success(`导入完成`) : this.$message.error(`导入失败零件个数为${this.err}，请检查文件是否正确`)
        }
        this.loading = false
      } catch (e) {
        this.err++
        this.loading = false
        this.$notify.error(`导入数据错误,请检查导入文件是否正确`)
        console.log(`导入数据错误${e}`)
      }
    },
    async importBeforeDispose() {
      var param = []
      console.log(param)
      var Data = this.CreateData('12', 'SPC_导入前处理', param)
      return new Promise((resolve, reject) => {
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === '1') {
            resolve(1)
          } else {
            reject(2)
          }
        })
      })
    },
    async insertToSQL(itemList) {
      try {
        this.uuid = this.generateUniqueString()
        let sql = 'INSERT INTO SPC_导入表 ([Id],[工位号],[测量项目],[测量位置],[测量值],[测量单位],[发动机号],[理论值],[标识编号]) VALUES '
        for (const item of itemList) {
          sql += `('${item.id}','${item.opName}','${item.project}','${item.position}','${item.value}','${item.unit}','${item.engineID}','${item.theoreticalValue}','${this.uuid}'),`
        }
        sql = sql.slice(0, -1)
        request({
          url: '',
          method: 'post',
          data: {
            type: '3',
            name: sql
          }
        }).then(response => {
          this.searchData()
          this.searchChart()
        })
      } catch (err) {
      }
    },
    generateUniqueString() {
      return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
    },
    // 导出excel
    handleDownload() {
      if (this.tableData.length !== 0) {
        let engineTypeValue_check, measuringPositionValue_check, measureContent_check
        if (this.opName) {
          this.opName_check = true
        } else {
          this.opName_check = false
        }
        if (this.model !== '') {
          engineTypeValue_check = 1
        } else {
          engineTypeValue_check = 0
        }
        if (this.measureName !== '') {
          measuringPositionValue_check = 1
        } else {
          measuringPositionValue_check = 0
        }
        if (this.measureContent !== '') {
          measureContent_check = 1
        } else {
          measureContent_check = 0
        }
        var param = []
        param[0] = ['结束时间', this.dateTime[1]]
        param[1] = ['开始时间', this.dateTime[0]]
        param[2] = ['测量位置_ischeck', measuringPositionValue_check]
        param[3] = ['测量位置', this.measureName]
        param[4] = ['测量项目', this.measureContent]
        param[5] = ['发动机型号代码', this.model]
        param[6] = ['发动机型号代码_ischeck', engineTypeValue_check]
        param[7] = ['工位号', this.opName]
        param[8] = ['工位号_ischeck', this.opName_check]
        param[9] = ['测量项目_ischeck', measureContent_check]
        param[10] = ['PageCount', 999999, 'int', '1']
        param[11] = ['ItemCount', 1000, 'int', '1']
        param[12] = ['PageCurrent', 1]
        param[13] = ['PageSize', 999999999]
        var Data = this.CreateData('2001', '质量数据_发动机质量数据_各个工位_视图_综合查询_趋势图', param)
        this.exportExcel_NPOI(Data)
      } else {
        this.$message.warning('暂无数据')
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        return v[j]
      }))
    },
    drawLine2(res) {
      const myChart = this.$echarts.init(document.getElementById('myChart'))
      const lineData = res.split(',')
      const xData = []
      for (let i = 0; i < lineData.length; i++) {
        xData[i] = i
      }
      myChart.clear()
      myChart.setOption({
        title: {
          text: '线路故障发生概率预测',
          left: '50%',
          top: '5%'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'line' // 默认为直线，可选为：'line' | 'shadow'
          }

        },
        legend: {
          orient: 'horizontal',
          left: 'left',
          data: [{ name: '低故障率', icon: 'bar' }, { name: '中等故障率', icon: 'bar' }, {
            name: '高故障率',
            icon: 'bar'
          }],
          selected: {
            '低故障率': true,
            '蒸发量': true,
            '中等故障率': true,
            '高故障率': true
            // 不想显示的都设置成false
          }
        },
        color: ['#81b22f', '#f3d71c', '#f4b9a9'],
        xAxis: {
          nameLocation: 'center',
          type: 'category',
          boundaryGap: true,
          data: [],
          show: true,
          axisTick: {
            show: true
          }

        },
        grid: {
          top: '15%',
          bottom: '5%',
          containLabel: true
        },
        yAxis: {
          nameGap: 35,
          name: '故障发生概率(%)',
          min: 0,
          max: 4,
          splitNumber: 10,
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          }

        },

        series: [ // 就是从这个地方开始的    主要用的是markArea 和legend
          {
            name: '低故障率',
            type: 'line',
            animation: false,
            areaStyle: {
              normal: {}
            },
            lineStyle: {
              normal: {
                width: 1
              }
            },
            markArea: {
              data: [[{
                yAxis: '0'
              }, {
                yAxis: '2'
              }]]
            }

          }, {
            name: '中等故障率',
            type: 'line',
            animation: false,
            areaStyle: {
              normal: {}
            },
            lineStyle: {
              normal: {
                width: 1
              }
            },
            markArea: {
              data: [[{
                yAxis: '2'
              }, {
                yAxis: '4'
              }]]
            }
          }, {
            name: '高故障率',
            type: 'line',
            animation: false,
            areaStyle: {
              normal: {}
            },
            lineStyle: {
              normal: {
                width: 1
              }
            },
            markArea: {
              data: [[{
                yAxis: '4'
              }, {
                yAxis: '6'
              }]]
            }
          },
          {
            name: '故障发生概率',
            type: 'line',
            data: [2.3, 0.5, 1.5, 3.44]
          }

        ]
      })
      this.cp = ''
      this.cpk = ''
      this.usl = ''
      this.ql = ''
      this.qu = ''
      this.sl = ''
      this.lsl = ''
    }
  }
}
</script>

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

.datePicker {
  width: 135px;
}
</style>

