<template>
  <div class="app-container">
    <el-card>
      <!--      <span style="margin-left: 15px">班次类型:</span>-->
      <span style="margin-left: 10px">工位号：</span>
      <el-select v-model="dataTypeValue" placeholder="请选择工位号" clearable size="small" style="width: 150px">
        <el-option
          v-for="item in dataType"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          size="mini"/>
      </el-select>
      <el-button
        type="primary"
        icon="el-icon-search"
        size="small"
        style="margin-left: 15px"
        plain
        @click="pageSize=20;pageCurrent=1;searchTable()">查询
      </el-button>
      <el-button type="distribution" icon="el-icon-circle-plus-outline" size="small" @click="addShiftTable('form')">
        新增
      </el-button>
      <el-button type="info" plain size="small" icon="el-icon-upload2" @click="importOrder('form')">巡检项导入</el-button>
      <el-table
        :data="tableData"
        border
        size="mini"
        height="450"
        center
        style="width: 70%">
        <el-table-column label="工位号" align="center">
          <template slot-scope="scope">
            {{ scope.row.工位号 }}
          </template>
        </el-table-column>
        <el-table-column label="检验项目" align="left" width="400">
          <template slot-scope="scope">
            序号{{ scope.row.检验项目 }}
          </template>
        </el-table-column>
        <el-table-column disabled 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="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              plain
              icon="el-icon-edit"
              @click="editShiftTable(scope.row)">编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              plain
              icon="el-icon-delete"
              @click="handleDelete(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="margin-top: 10px;">
        <el-pagination
          :current-page="pageCurrent"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="20"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>
    </el-button></el-card>
    <el-dialog :visible.sync="dialogFormVisible" :title="title" center style="min-height: 200px;" width="400px">
      <el-form ref="form" :model="form" label-position="right" label-width="110px">
        <el-form-item label="工位号" prop="name" style="display: inline-block">
          <el-select
            v-model="form.opName"
            placeholder="请选择工位号"
            clearable
            size="small"
            style="width: 185px">
            <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-item label="检验项目" prop="value" style="display: inline-block">
          <el-input v-model="form.testDemo" size="small" placeholder="检验项目"/>
        </el-form-item>
        <el-form-item label="检验标准" prop="descript" style="display: inline-block">
          <el-input
            v-model="form.testStandard"
            size="small"
            placeholder="检验标准"/>
        </el-form-item>
        <el-form-item label="检验方法" prop="descript" style="display: inline-block">
          <el-input
            v-model="form.testFunction"
            size="small"
            placeholder="检验方法"/>
        </el-form-item>
        <el-form-item label="自动判断合格" prop="name" style="display: inline-block">
          <el-select
            v-model="form.isAutoOk"
            placeholder="是否自动判断合格"
            size="small"
            style="width: 185px">
            <el-option
              label="是"
              value="1"
              size="mini"/>
            <el-option
              label="否"
              value="0"
              size="mini"/>
          </el-select>
        </el-form-item>
        <el-form-item label="合格上限值" prop="descript" style="display: inline-block">
          <el-input
            v-model="form.okUpperLimit"
            size="small"
            placeholder="检验方法"/>
        </el-form-item>
        <el-form-item label="合格下限值" prop="descript" style="display: inline-block">
          <el-input
            v-model="form.okLowerLimit"
            size="small"
            placeholder="检验方法"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="callOff('form')">取消</el-button>
        <el-button v-if="title === '编辑'" type="primary" size="small" @click="submitAdd1('form')">确定</el-button>
        <el-button v-if="title === '增加'" type="primary" size="small" @click="submitAdd('form')">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogFormVisible3" title="导入" center style="min-height: 200px" width="900px">
      <div class="app-container">
        <upload-excel-component style="margin-left: 15%" @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 :on-remove="handleRemove" :file-list="itemFile" style="width: 220px" action=""/>
        </div>
        <div v-if="worksheet.length !== 0" style="margin: 3px 0 0 395px">
          <el-button icon="el-icon-upload2" type="primary" size="small" @click="basicPartsToSQL">导入到数据库
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

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

export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      worksheet: [],
      itemFile: [],
      unSpecification: [],
      dataTypeValue: '',
      dataType: [],
      tableData: [],
      hour: '',
      minutes: '',
      seconds: '',
      dialogFormVisible: false,
      dialogFormVisible3: false,
      form: {
        id: '',
        opName: '', // 工位号
        testDemo: '', // 检验项目
        testStandard: '', // 检验标准
        testFunction: '', // 检验方法
        isAutoOk: '0', // 是否自动判断合格
        okUpperLimit: 0, // 合格上限值
        okLowerLimit: 0 // 合格下限值
      },
      rules: { // 表单验证规则
        dataTypeValue: [{ required: true, message: '请选择', trigger: 'change' }],
        name: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      title: '编辑',
      pageCurrent: 1,
      pageSize: 20,
      total: 0
    }
  },
  created() {
    this.searchTable()
    this.getStationNumber()
  },
  methods: {
    getStationNumber() {
      this.stationNumber = []
      var param = []
      var Data = this.CreateData('11', 'MES_计划BOM_工位与名称_查询', param)
      this.ExecDatabase(Data).then(response => {
        // if (response.data.length) {
        //   this.stationNumberValue = response.data[0].工位号
        //   this.stationName = response.data[0].工序名称
        // }
        for (let i = 0; i < response.data.length; i++) {
          this.dataType.push({
            label: response.data[i].工位号,
            value: response.data[i].工位号,
            labelName: response.data[i].工位名称
          })
        }
      })
    },
    searchTable() {
      this.tableData = []
      let dataTypeValue_check
      this.dataTypeValue ? dataTypeValue_check = 1 : dataTypeValue_check = 0
      var param = []
      param[0] = ['工位号_ischeck', dataTypeValue_check]
      param[1] = ['工位号', this.dataTypeValue]
      param[2] = ['PageCurrent', this.pageCurrent]
      param[3] = ['PageSize', this.pageSize]
      param[4] = ['PageCount', '1111', 'int', '1']
      param[5] = ['ItemCount', '1111', 'int', '1']
      var Data = this.CreateData('11', '福田_巡检检验项维护项_查询', 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
        console.log(this.tableData, 'this.tableData')
      })
    },
    addShiftTable(formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
      this.title = '增加'
      this.form.id = ''
      this.form.opName = '' // 工位号
      this.form.testDemo = '' // 检验项目
      this.form.testStandard = '' // 检验标准
      this.form.testFunction = '' // 检验方法
      this.form.isAutoOk = '0'
      this.form.okLowerLimit = 0
      this.form.okUpperLimit = 0
      this.dialogFormVisible = true
    },
    submitAdd(formName) {
      if (!this.form.opName || !this.form.testDemo || !this.form.testStandard || !this.form.testFunction) {
        this.$message.warning('请填写完全后提交')
        return
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var param = []
          param[0] = ['工位号', this.form.opName]
          param[1] = ['检验项目', this.form.testDemo]
          param[2] = ['检验标准', this.form.testStandard]
          param[3] = ['检验方法', this.form.testFunction]
          param[4] = ['是否自动判断', this.form.isAutoOk]
          param[5] = ['上限值', this.form.okUpperLimit]
          param[6] = ['下限值', this.form.okLowerLimit]
          var Data = this.CreateData('12', '福田_巡检检验项维护项_增加', param)
          this.ExecDatabase(Data).then(response => {
            console.log(response)
            if (response.data[0].result === '1') {
              this.$message({
                message: '增加成功',
                type: 'success'
              })
              this.dialogFormVisible = false
              this.searchTable()
            } else {
              this.$message.error('增加失败！')
            }
          })
          this.dialogFormVisible = false
        } else {
          return false
        }
      })
    },
    editShiftTable(row) {
      if (this.$refs['form'] !== undefined) {
        this.$refs['form'].resetFields()
      }
      this.form.id = row.id
      this.form.opName = row.工位号 // 工位号
      this.form.testDemo = row.检验项目 // 检验项目
      this.form.testStandard = row.检验标准 // 检验标准
      this.form.testFunction = row.检验方法 // 检验方法
      this.form.isAutoOk = String(row.是否自动判断)
      this.form.okUpperLimit = row.上限值
      this.form.okLowerLimit = row.下限值
      this.title = '编辑'
      this.dialogFormVisible = true
    },
    submitAdd1() {
      var param = []
      param[0] = ['工位号', this.form.opName]
      param[1] = ['检验项目', this.form.testDemo]
      param[2] = ['检验标准', this.form.testStandard]
      param[3] = ['检验方法', this.form.testFunction]
      param[4] = ['id', this.form.id]
      param[5] = ['是否自动判断', this.form.isAutoOk]
      param[6] = ['上限值', this.form.okUpperLimit]
      param[7] = ['下限值', this.form.okLowerLimit]
      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
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var param = []
        param[0] = ['id', row.id]
        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('删除失败！')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    callOff() {
      this.dialogFormVisible = false
    },
    importOrder() {
      this.dialogFormVisible3 = true
    },
    removeAll() {
      this.worksheet = []
      this.itemFile = []
    },
    async selected(data) { // 选择需要导入的文件
      console.log(data, 1111)
      this.worksheet = data.worksheet // 获取每个多选文件的表格坐标及值
      this.itemFile = data.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
        for (let j = this.worksheet.length - 1; j >= 0; j--) {
          let opName,
            checkItem,
            checkStandard,
            checkFunction,
            isAutoOk,
            okUpperLimit,
            okLowerLimit
          for (let i = 0; i < 999; i++) {
            const attr = i + 2
            opName = this.worksheet[j][`A${attr}`] ? this.worksheet[j][`A${attr}`].v : ''
            checkItem = this.worksheet[j][`B${attr}`] ? this.worksheet[j][`B${attr}`].v : ''
            checkStandard = this.worksheet[j][`C${attr}`] ? this.worksheet[j][`C${attr}`].v : ''
            checkFunction = this.worksheet[j][`D${attr}`] ? this.worksheet[j][`D${attr}`].v : ''
            isAutoOk = this.worksheet[j][`E${attr}`] ? this.worksheet[j][`E${attr}`].v : ''
            okUpperLimit = this.worksheet[j][`F${attr}`] ? this.worksheet[j][`F${attr}`].v : ''
            okLowerLimit = this.worksheet[j][`G${attr}`] ? this.worksheet[j][`G${attr}`].v : ''
            console.log(opName,
              checkItem,
              checkStandard,
              checkFunction,
              isAutoOk,
              okUpperLimit,
              okLowerLimit)
            if (!opName || !checkItem || !checkStandard || !checkFunction) {
              break
            } else {
              if (opName) {
                await sleep(50)
                await this.insertToSQL(opName, checkItem, checkStandard, checkFunction, isAutoOk, okUpperLimit, okLowerLimit)
              } else {
                this.loading = false
                this.disabled = false
                return
              }
            }
          }
          this.itemFile.splice(j, 1)
          this.worksheet.splice(j, 1)
          this.err === 0 ? this.$message.success(`导入完成`) : this.$message.error(`导入失败个数为${this.err}，请检查文件是否正确`)
        }
        this.loading = false
        this.searchTable()
      } catch (e) {
        this.err++
        this.loading = false
        this.$notify.error(`导入数据错误,请检查导入文件是否正确`)
        console.log(`导入数据错误${e}`)
      }
    },
    async insertToSQL(opName, checkItem, checkStandard, checkFunction, isAutoOk, okUpperLimit, okLowerLimit) {
      try {
        var param = []
        param[0] = ['工位号', opName]
        param[1] = ['检验项目', checkItem]
        param[2] = ['检验标准', checkStandard]
        param[3] = ['检验方法', checkFunction]
        param[4] = ['是否自动判断合格', isAutoOk]
        param[5] = ['合格上限值', okUpperLimit]
        param[6] = ['合格下限值', okLowerLimit]
        var Data = this.CreateData('12', '巡检检验项_导入', param)
        const response = await this.ExecDatabase(Data)
        if (response.data[0].result === '1') {
          this.$notify.success(`${name}导入成功`)
        } else {
          this.$notify.error(`${name}导入失败`)
        }
      } catch (e) {
        this.err++
        this.$message.error(`导入数据错误`)
        console.log(`导入数据错误${e}`)
      }
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.pageCurrent = 1
      this.searchTable()
    },
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.searchTable()
    }
  }
}
</script>

<style scoped>
</style>

