<template>
  <div class="app-container">
    <el-card class="topCard">
      <div class="topDiv">
        <span style="margin-left: 10px">工位号：</span>
        <el-select v-model="dataTypeValue" clearable placeholder="工位号" size="small" style="width:150px">
          <el-option
            v-for="item in dataType"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <!--        <span style="margin-left: 10px">变量类型：</span>-->
        <!--        <el-select v-model="valueTypeValue" placeholder="变量类型" clearable size="small" style="width:100px">-->
        <!--          <el-option-->
        <!--            v-for="item in valueType"-->
        <!--            :key="item.value"-->
        <!--            :label="item.label"-->
        <!--            :value="item.value"/>-->
        <!--        </el-select>-->
        <el-button
          icon="el-icon-search"
          plain
          size="small"
          style="margin-left: 5px"
          type="primary"
          @click="pageSize=50;pageCurrent=1;searchTable()">查询
        </el-button>
        <!--        <el-button type="success" plain icon="el-icon-document-copy" size="small" @click="copyData('form4')">复制</el-button>-->
        <el-button icon="el-icon-upload2" plain size="small" type="info" @click="importOrder('form')">报警导入</el-button>
        <el-button icon="el-icon-upload2" plain size="small" type="success" @click="importQualityData()">质量数据导入</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        center
        height="740"
        highlight-current-row
        size="mini"
        style="width: 100%">
        <el-table-column align="center" label="序号" width="60">
          <template slot-scope="scope">
            {{ scope.row.序号 }}
          </template>
        </el-table-column>
        <!--        <el-table-column label="TagID" align="center">-->
        <!--          <template slot-scope="scope">-->
        <!--            {{ scope.row.TagID }}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column align="center" label="TagName" width="200px">
          <template slot-scope="scope">
            {{ scope.row.TagName }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="工位号">
          <template slot-scope="scope">
            {{ scope.row.工位号 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="地址">
          <template slot-scope="scope">
            【{{ scope.row.DbName }}】{{ scope.row.变量类型 }}{{ scope.row.变量地址 }} {{ 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 align="center" label="报警类型">
          <template slot-scope="scope">
            {{ scope.row.测量位置 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="报警内容" min-width="300px">
          <template slot-scope="scope">
            {{ scope.row.测量项目 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit"
              plain
              size="mini"
              type="text"
              @click="editShiftTable(scope.row)">编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="margin-top: 10px;">
        <el-pagination
          v-if="!loading"
          :current-page="pageCurrent"
          :page-size="pageSize"
          :page-sizes="[50, 100, 200]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>
    </el-card>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" center style="min-height: 200px;" width="400px">
      <el-form ref="form" :model="form" :rules="rules" label-position="right" label-width="110px">
        <el-form-item label="报警类型" prop="measurementItems" style="display: inline-block">
          <el-select v-model="form.measurementItems" placeholder="IP" size="small">
            <el-option
              v-for="item in alarmType"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="报警内容" prop="valueName" style="display: inline-block">
          <el-input
            v-model="form.valueName"
            clearable
            placeholder="变量类型名称"
            size="small"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="callOff('form')">取消</el-button>
        <el-button size="small" type="primary" @click="submitAdd1('form')">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogFormVisible3" center style="min-height: 200px" title="报警导入" width="900px">
      <div class="app-container">
        <upload-excel-component templateFileName="西开报警变量模板表.xlsx" @on-selected-file="selected"/>
        <div v-if="sheetNames.length > 0" style="margin-left: 395px; margin-top: 10px;">
          <div>已读取Sheet名称：</div>
          <ul>
            <li v-for="(name, idx) in sheetNames" :key="idx">{{ name }}</li>
          </ul>
        </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>
    <el-dialog :visible.sync="dialogFormVisible4" center style="min-height: 200px" title="数据复制" width="400px">
      <el-form ref="form1" :model="form4" :rules="rules4" label-position="right" label-width="110px">
        <el-form-item label="工位号" prop="engineTypeValue" style="display: inline-block">
          <el-select v-model="form4.engineTypeValue" placeholder="请选择工位号" size="small">
            <el-option
              v-for="item in dataType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              size="mini"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="callOff4()">取消</el-button>
        <el-button size="small" type="primary" @click="submitAdd4()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogFormVisible5" center style="min-height: 200px" title="质量数据导入" width="900px">
      <div class="app-container">
        <upload-excel-component templateFileName="西开质量数据模板表.xlsx" @on-selected-file="selectedQualityData"/>
        <div v-if="qualitySheetNames.length > 0" style="margin-left: 395px; margin-top: 10px;">
          <div>已读取Sheet名称：</div>
          <ul>
            <li v-for="(name, idx) in qualitySheetNames" :key="idx">{{ name }}</li>
          </ul>
        </div>
        <div v-if="qualityWorksheet.length !== 0" style="margin: 3px 0 0 395px">
          <el-button icon="el-icon-upload2" size="small" type="primary" @click="qualityDataToSQL">导入到数据库
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import UploadExcelComponent from './UploadExcel.vue'
import request from '@/utils/request'
import { sleep } from '../../../utils/tool'

export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      worksheet: [],
      itemFile: [],
      qualityWorksheet: [],
      qualityItemFile: [],
      qualitySheetNames: [],
      loading: false,
      tableData: [],
      err: 0,
      dataType: [], // 工位数组
      dataTypeValue: '', // 工位信息
      valueType: [
        {
          label: '基本变量',
          value: 8
        }, {
          label: '报警变量',
          value: 9
        }, {
          label: '质量变量',
          value: 7
        }
      ],
      valueTypeValue: '9',
      alarmType: [],
      alarmTypeValue: '',
      dialogFormVisible: false,
      dialogFormVisible4: false,
      dialogFormVisible5: false,
      form4: {
        engineTypeValue: ''
      },
      rules4: { // 订单下发验证
        engineTypeValue: [{ required: true, message: '请选择', trigger: 'blur' }]
      },
      title: '',
      dialogFormVisible3: false, // 订单导入
      form: {
        tagID: '',
        stationNo: '',
        measurementItems: '',
        valueName: ''
      },
      rules: { // 表单验证规则
      },
      total: 0, // 总条数
      pageList: 50, // 每页显示条数
      pageSize: 50, // 每页显示条数
      pageCurrent: 1, // 后台获取页
      sheetNames: [], // 新增sheet名称数组
      progressMsg: null
    }
  },
  created() {
    this.getNumber()
    this.getAlarmType()
  },
  methods: {
    // 初始化获取产品型号
    getNumber() {
      this.dataType = []
      request({
        url: '',
        method: 'post',
        data: {
          type: '3',
          name: `SELECT [工位号] FROM [dbo].[MES_计划BOM_工位与名称] WHERE 线体类型 != 2`
        }
      }).then(response => {
        if (response.data.length) {
          this.dataTypeValue = response.data[0].工位号
          for (let i = 0; i < response.data.length; i++) {
            this.dataType.push({
              label: response.data[i].工位号,
              value: response.data[i].工位号
            })
          }
        }
      }).then(() => {
        this.searchTable()
      })
    }, // 初始化获取报警类型
    getAlarmType() {
      this.alarmType = []
      request({
        url: '',
        method: 'post',
        data: {
          type: '3',
          name: `SELECT [ID], [报警类型] FROM [dbo].[MES_基本变量_报警类型]`
        }
      }).then(response => {
        if (response.data.length) {
          // console.log(response.data, 'response.data')
          for (let i = 0; i < response.data.length; i++) {
            this.alarmType.push({
              label: response.data[i].报警类型,
              value: response.data[i].报警类型
            })
          }
        }
      })
    },
    searchTable() {
      this.loading = true
      this.tableData = []
      let stationNumberValue_check, valueType_check
      // this.engineTypeValue ? engineTypeValue_check = 1 : (engineTypeValue_check = 0, this.engineTypeValue = '')
      this.dataTypeValue ? stationNumberValue_check = 1 : (stationNumberValue_check = 0, this.dataTypeValue = '')
      this.valueTypeValue ? valueType_check = 1 : (valueType_check = 0, this.valueTypeValue = '')
      var param = []
      param[0] = ['变量类型_ischeck', valueType_check]
      param[1] = ['变量类型', this.valueTypeValue]
      param[2] = ['工位号_ischeck', stationNumberValue_check]
      param[3] = ['工位号', this.dataTypeValue]
      param[4] = ['PageCurrent', this.pageCurrent]
      param[5] = ['PageSize', this.pageSize]
      param[6] = ['PageCount', '1111', 'int', '1']
      param[7] = ['ItemCount', '1111', 'int', '1']
      var Data = this.CreateData('11', 'MES_基本变量_查询数据', param)
      this.ExecDatabase(Data).then(response => {
        console.log(response, 66)
        if (response.data.result.length !== 0) {
          this.tableData = response.data.result
        }
        this.total = parseInt(response.data.output[0].ItemCount)
        this.loading = false
      })
    },
    editShiftTable(row) {
      if (this.$refs['form'] !== undefined) {
        this.$refs['form'].resetFields()
      }
      this.form.tagID = row.TagID
      this.form.measurementItems = row.测量位置
      this.form.stationNo = row.工位号
      this.form.valueName = row.测量项目
      this.title = '编辑'
      this.dialogFormVisible = true
    },
    submitAdd1() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          var param = []
          param[0] = ['工位号', this.form.stationNo]
          param[1] = ['TagID', this.form.tagID]
          param[2] = ['测量项目', this.form.measurementItems]
          param[3] = ['变量类型名称', this.form.valueName]
          var Data = this.CreateData('12', '基础数据_报警变量维护_编辑', param)
          this.ExecDatabase(Data).then(response => {
            if (response.data[0].result === '1') {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.searchTable()
            } else {
              this.$message.error('修改失败！')
            }
          })
          this.dialogFormVisible = false
        } else {
          return false
        }
      })
    },
    callOff() {
      this.dialogFormVisible = false
    },
    copyData(formName) {
      if (this.tableData.length) {
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields()
        }
        this.dialogFormVisible4 = true
      } else {
        this.$message({
          message: '暂无可复制的数据！',
          type: 'error'
        })
      }
    },
    callOff4() {
      this.dialogFormVisible4 = false
    },
    submitAdd4() {
      var param = []
      param[0] = ['原始工位号', this.dataTypeValue]
      param[1] = ['复制工位号', this.form4.engineTypeValue]
      var Data = this.CreateData('12', '基础数据_报警变量维护_复制', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data[0].result === '1') {
          this.$message({
            message: '修改成功',
            type: 'success'
          })
          this.dataTypeValue = this.form4.engineTypeValue
          this.searchTable()
          this.dialogFormVisible4 = false
        } else {
          this.$message.error('修改失败！')
        }
      })
      this.dialogFormVisible = false
    },
    // 分页
    handleSizeChange(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.searchTable()
    },
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.searchTable()
    },
    // 导入订单
    importOrder() {
      this.dialogFormVisible3 = true
    },
    // 导入质量数据
    importQualityData() {
      this.dialogFormVisible5 = true
    },
    removeAll() {
      this.worksheet = []
      this.itemFile = []
      this.sheetNames = []
    },
    removeAllQuality() {
      this.qualityWorksheet = []
      this.qualityItemFile = []
      this.qualitySheetNames = []
    },
    async selected(data) { // 选择需要导入的文件
      this.worksheet = data.worksheet
      this.itemFile = data.itemFile
      this.sheetNames = data.sheetNames
    },
    async selectedQualityData(data) { // 选择需要导入质量数据的文件
      this.qualityWorksheet = data.worksheet
      this.qualityItemFile = data.itemFile
      this.qualitySheetNames = data.sheetNames
    },
    async basicPartsToSQL() {
      try {
        this.loading = true
        this.err = 0
        const basicFields = ['序号','描述文本'] // 基本列
        const requiredFields = ['序号', '报警类型', '描述文本'] // 必填字段
        let invalidRowIndex = -1
        let invalidField = ''
        let invalidSheetName = ''
        let validRows = []
        let rowSheetMap = [] // 新增：记录每行对应的sheet名
        for (let j = this.worksheet.length - 1; j >= 0; j--) {
          const sheet = this.worksheet[j]
          const sheetName = this.sheetNames ? this.sheetNames[j] : `Sheet${j+1}`
          const XLSX = require('xlsx')
          const rows = XLSX.utils.sheet_to_json(sheet, {header: 1, defval: ''})
          if (!rows || rows.length < 2) continue
          const headers = rows[0]
          for (let i = 1; i < rows.length; i++) {
            const row = rows[i]
            let obj = {}
            headers.forEach((h, idx) => {
              obj[h] = row[idx] !== undefined ? row[idx] : ''
            })
            // 校验基本列
            const hasAllBasic = basicFields.every(f => obj[f] && obj[f].toString().trim() !== '')
            if (!hasAllBasic) {
              // 只要有一个基本列为空，直接跳过
              continue
            }
            // 校验必填列
            let valid = true
            for (let f of requiredFields) {
              if (!obj[f] || obj[f].toString().trim() === '') {
                valid = false
                invalidField = f
                invalidRowIndex = i + 1 // Excel行号（含表头）
                invalidSheetName = sheetName
                break
              }
            }
            if (!valid) break
            validRows.push(obj)
            rowSheetMap.push(sheetName) // 记录该行属于哪个sheet
          }
          if (invalidRowIndex !== -1) break
        }
        if (invalidRowIndex !== -1) {
          this.loading = false
          this.$message.error(`第${invalidRowIndex}行（Sheet: ${invalidSheetName}）字段"${invalidField}"为空，导入已终止！`)
          return
        }
        // 全部校验通过后，按sheet独立遍历导入（直接用校验通过的数据）
        if (!this.progressMsg) this.progressMsg = null
        let importCount = 0
        for (let j = this.worksheet.length - 1; j >= 0; j--) {
          const sheetName = this.sheetNames ? this.sheetNames[j] : `Sheet${j+1}`
          for (let idx = 0; idx < validRows.length; idx++) {
            if (rowSheetMap[idx] !== sheetName) continue
            const obj = validRows[idx]
            importCount++
            // 实际导入数据库
            console.log(obj['序号'], sheetName, obj['报警类型'], obj['描述文本'], obj['地址'])
            await this.insertToSQL(obj['序号'], sheetName, obj['报警类型'], obj['描述文本'], obj['地址'])

            if (this.progressMsg) this.progressMsg.close()
            this.progressMsg = this.$message.info({
              message: `导入进度：${importCount}/${validRows.length}`,
              duration: 0
            })
          }
        }
        if (this.progressMsg) {
          this.progressMsg.close()
          this.progressMsg = null
        }
        this.$message.success('全部数据导入完成')
        this.loading = false
        this.dialogFormVisible3 = false
        this.searchTable()
      } catch (e) {
        this.err++
        this.loading = false
        this.$notify.error(`导入数据错误,请检查导入文件是否正确`)
        console.log(`导入数据错误${e}`)
      }
    },
    async insertToSQL(sort,OpName,errType,text, position) {
      try {
        var param = []
        param[0] = ['序号', sort]
        param[1] = ['工位号', OpName]
        param[2] = ['报警类型', errType]
        param[3] = ['文本', text]
        param[4] = ['地址位置', position]
        var Data = this.CreateData('12', '报警变量_导入', param)
        const response = await this.ExecDatabase(Data)
        const res = response.data
        if (res.hasOwnProperty('output') === false) {
          if (res[0].result === '0') {
            this.$notify.error(`${OpName, position}导入失败`)
          }
        } else {
          if (res.result[0].result === '0') {
            this.$notify.error(`${OpName, position}导入失败`)
          }
          if (res.output[0].导入类型 === '2') {
            this.$notify.warning(`${OpName, position}存在重复数据`)
          }
        }
      } catch (e) {
        this.err++
        this.$message.error(`导入数据错误`)
        console.log(`导入数据错误${e}`)
      }
    },
    async qualityDataToSQL() {
      try {
        this.loading = true
        this.err = 0
        const basicFields = ['测量位置'] // 基本列
        const requiredFields = ['地址', '测量位置', '测量项目1'] // 必填字段
        let invalidRowIndex = -1
        let invalidField = ''
        let invalidSheetName = ''
        let validRows = []
        let rowSheetMap = [] // 记录每行对应的sheet名
        
        for (let j = this.qualityWorksheet.length - 1; j >= 0; j--) {
          const sheet = this.qualityWorksheet[j]
          const sheetName = this.qualitySheetNames ? this.qualitySheetNames[j] : `Sheet${j+1}`
          const XLSX = require('xlsx')
          const rows = XLSX.utils.sheet_to_json(sheet, {header: 1, defval: ''})
          
          if (!rows || rows.length < 2) continue
          
          const headers = rows[0]
          for (let i = 1; i < rows.length; i++) {
            const row = rows[i]
            let obj = {}
            headers.forEach((h, idx) => {
              obj[h] = row[idx] !== undefined ? row[idx] : ''
            })
            
            // 校验基本列
            const hasAllBasic = basicFields.every(f => obj[f] && obj[f].toString().trim() !== '')
            if (!hasAllBasic) {
              // 只要有一个基本列为空，直接跳过
              continue
            }
            
            // 校验必填列
            let valid = true
            for (let f of requiredFields) {
              if (!obj[f] || obj[f].toString().trim() === '') {
                valid = false
                invalidField = f
                invalidRowIndex = i + 1 // Excel行号（含表头）
                invalidSheetName = sheetName
                break
              }
            }
            
            if (!valid) break
            
            validRows.push(obj)
            rowSheetMap.push(sheetName) // 记录该行属于哪个sheet
          }
          
          if (invalidRowIndex !== -1) break
        }
        
        if (invalidRowIndex !== -1) {
          this.loading = false
          this.$message.error(`第${invalidRowIndex}行（Sheet: ${invalidSheetName}）字段"${invalidField}"为空，导入已终止！`)
          return
        }
        
        // 全部校验通过后，按sheet处理数据
        if (!this.progressMsg) this.progressMsg = null
        let importCount = 0
        let processedSheets = new Set()
        
        for (let j = 0; j < this.qualitySheetNames.length; j++) {
          const sheetName = this.qualitySheetNames[j]
          
          // 如果该sheet已处理过，则跳过
          if (processedSheets.has(sheetName)) continue
          
          processedSheets.add(sheetName)
          
          // 每个sheet调用一次前处理存储过程
          await this.preprocessQualityData(sheetName)
          await sleep(200)
          
          // 处理该sheet中的所有有效数据行
          const sheetRows = validRows.filter((_, idx) => rowSheetMap[idx] === sheetName)
          
          for (let i = 0; i < sheetRows.length; i++) {
            const obj = sheetRows[i]
            importCount++
            
            // 实际导入数据库
            await this.importQualityDataToSQL(
              sheetName,                     // 工位号
              parseInt(obj['地址']) || i + 1, // 测量位置编号
              obj['测量位置'] || '',          // 测量位置
              obj['测量项目1'] || '',         // 测量项目1
              obj['测量项目2'] || ''          // 测量项目2
            )
            
            if (this.progressMsg) this.progressMsg.close()
            this.progressMsg = this.$message.info({
              message: `导入进度：${importCount}/${validRows.length}`,
              duration: 0
            })
          }
        }
        
        if (this.progressMsg) {
          this.progressMsg.close()
          this.progressMsg = null
        }
        
        this.$message.success('质量数据导入完成')
        this.loading = false
        this.dialogFormVisible5 = false
        this.searchTable()
        
      } catch (e) {
        this.err++
        this.loading = false
        this.$notify.error(`导入数据错误,请检查导入文件是否正确`)
        console.log(`导入质量数据错误${e}`)
      }
    },
    async preprocessQualityData(workstation) {
      try {
        var param = []
        param[0] = ['工位号', workstation]
        var Data = this.CreateData('12', 'MES_基本变量_原始数据_质量数据_工位导入前处理', param)
        const response = await this.ExecDatabase(Data)
        const res = response.data
        if (res.hasOwnProperty('output') === false) {
          if (res[0].result === '0') {
            this.$notify.error(`${workstation} 工位前处理失败`)
          }
        } else if (res.result && res.result[0].result === '0') {
          this.$notify.error(`${workstation} 工位前处理失败`)
        }
      } catch (e) {
        this.err++
        this.$message.error(`工位前处理错误: ${workstation}`)
        console.log(`工位前处理错误${e}`)
      }
    },
    async importQualityDataToSQL(workstation, positionNo, position, item1, item2) {
      try {
        var param = []
        param[0] = ['工位号', workstation]
        param[1] = ['测量位置编号', positionNo]
        param[2] = ['测量位置', position]
        param[3] = ['测量项目1', item1]
        param[4] = ['测量项目2', item2 || '']
        var Data = this.CreateData('12', 'MES_基本变量_原始数据_质量数据_导入', param)
        const response = await this.ExecDatabase(Data)
        const res = response.data
        if (res.hasOwnProperty('output') === false) {
          if (res[0].result === '0') {
            this.$notify.error(`${workstation}, ${position} 导入失败`)
          }
        } else if (res.result && res.result[0].result === '0') {
          this.$notify.error(`${workstation}, ${position} 导入失败`)
        }
      } catch (e) {
        this.err++
        this.$message.error(`导入数据错误: ${workstation}, ${position}`)
        console.log(`导入质量数据错误${e}`)
      }
    },
  }
}
</script>

<style scoped>
.topDiv {
  margin-bottom: 10px;
}
</style>
