<template>
  <div class="app-container">
    <el-card>
      <!--      <span style="margin-left: 15px">班次类型:</span>-->
      <el-select v-model="dataTypeValue" placeholder="工位号" clearable size="small" style="width:100px">
        <el-option
          v-for="item in dataType"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>
      <el-button type="primary" icon="el-icon-search" size="small" style="margin-left: 15px" plain @click="searchTable()">查询</el-button>
      <el-button type="distribution" icon="el-icon-circle-plus-outline" size="small" @click="writeVariable1()">写入变量</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
        stripe
        size="mini"
        height="800"
        center
        style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column :selectable="selectable" type="selection" width="45" align="center"/>
        <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="IP" align="center">
          <template slot-scope="scope">
            {{ scope.row.IP }}
          </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="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              plain
              icon="el-icon-edit"
              @click="editShiftTable(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog :visible.sync="dialogFormVisible" :title="title" 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="IP" prop="IP" style="display: inline-block">
          <el-input v-model="form.IP" clearable size="small" placeholder="IP"/>
        </el-form-item>
        <el-form-item label="报警数" prop="numberAlarms" style="display: inline-block">
          <el-input
            v-model="form.numberAlarms"
            clearable
            size="small"
            placeholder="报警数"/>
        </el-form-item>
        <el-form-item label="质量组数" prop="massNumber" style="display: inline-block">
          <el-input
            v-model="form.massNumber"
            clearable
            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 type="primary" size="small" @click="submitAdd1('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'
import request from '@/utils/request'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      loading: true,
      worksheet: [],
      itemFile: [],
      unSpecification: [],
      dataTypeValue: '',
      dataType: [],
      tableData: [],
      activeValue: '',
      multipleSelection: '',
      multipleSelection_variable: '',
      active: [{
        label: '启用',
        value: 1
      }, {
        label: '禁用',
        value: 0
      }],
      dialogFormVisible: false,
      dialogFormVisible3: false,
      form: {
        IP: '',
        numberAlarms: '',
        massNumber: '',
        stationNo: '',
        fourNumber: ''
      },
      rules: { // 表单验证规则
      },
      title: '',
      pageCurrent: 1,
      pageSize: 20,
      total: 0
    }
  },
  created() {
    this.getNumber()
    this.searchTable()
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log(this.multipleSelection, 'this.multipleSelection')
    },
    writeVariable1() {
      this.$confirm('是否投产?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.writeVariable()
      })
    },
    async writeVariable() {
      if (!this.multipleSelection.length) {
        this.$message.error('请选择工位号！')
      } else {
        // eslint-disable-next-line no-unused-vars
        let ip, numberAlarms, massNumber, stationNo, fourNumber
        this.multipleSelection_variable = this.multipleSelection
        this.multipleSelection = []
        for (let i = 0; i < this.multipleSelection_variable.length; i++) {
          stationNo = this.multipleSelection_variable[i].工位号
          fourNumber = this.multipleSelection_variable[i].工位代码
          ip = this.multipleSelection_variable[i].IP
          numberAlarms = this.multipleSelection_variable[i].报警数
          massNumber = this.multipleSelection_variable[i].质量组数
          await this.writeVariableDetermine(ip, numberAlarms, massNumber, stationNo, fourNumber)
          console.log(ip, numberAlarms, massNumber, stationNo, fourNumber, 'ip, numberAlarms, massNumber, stationNo, fourNumber')
        }
        this.$message.success(`写入完成！`)
      }
    },
    async writeVariableDetermine(ip, numberAlarms, massNumber, stationNo, fourNumber) {
      var param = []
      param[0] = ['IP', ip]
      param[1] = ['工位号', stationNo]
      param[2] = ['工位代码', fourNumber]
      param[3] = ['报警个数', numberAlarms]
      param[4] = ['质量组数', massNumber]
      var Data = this.CreateData('12', 'MES_基本变量数据_增加', param)
      return new Promise((resolve, reject) => {
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === '1') {
            console.log('1')
            resolve(1)
          } else {
            console.log('0')
            reject(2)
          }
        })
      })
    },
    selectable(row) {
      return row.IP && row.报警数 && row.质量组数
    },
    getNumber() {
      this.dataType = []
      request({
        url: '',
        method: 'post',
        data: {
          type: '3',
          name: `SELECT [工位号] FROM [dbo].[MES_计划BOM_工位与名称]`
        }
      }).then(response => {
        if (response.data.length) {
          for (let i = 0; i < response.data.length; i++) {
            this.dataType.push({
              label: response.data[i].工位号,
              value: response.data[i].工位号
            })
          }
        }
      })
    },
    changeName(val) {
      for (let i = 0; i < this.dataType.length; i++) {
        if (this.dataType[i].value === val) {
          console.log(this.dataType[i].label, 'this.stationNumber[i].label')
          this.form.name = this.dataType[i].label
        }
      }
    },
    searchTable() {
      this.tableData = []
      let dataTypeValue_check
      this.dataTypeValue ? dataTypeValue_check = 1 : dataTypeValue_check = 0
      var param = []
      param[0] = ['type_ischeck', dataTypeValue_check]
      param[1] = ['type', this.dataTypeValue]
      var Data = this.CreateData('11', '基础数据_工位信息维护_查询', param)
      this.ExecDatabase(Data).then(response => {
        console.log(response, 66)
        if (response.data.length !== 0) {
          this.tableData = response.data
        }
        this.loading = false
        console.log(this.tableData, 'this.tableData')
      })
    },
    addShiftTable(formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
      this.title = '增加'
      this.form.name = ''
      this.form.value = ''
      this.form.descript = ''
      this.form.comments = ''
      this.form.dataTypeValue = ''
      this.form.active = ''
      this.dialogFormVisible = true
    },
    submitAdd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var param = []
          param[0] = ['active', this.form.active]
          param[1] = ['type', this.form.dataTypeValue]
          param[2] = ['num', this.form.value]
          param[3] = ['descript', this.form.descript]
          param[4] = ['comments', this.form.comments]
          var Data = this.CreateData('12', 'Recipe_Machine_Add', 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.IP = row.IP
      this.form.numberAlarms = row.报警数
      this.form.massNumber = row.质量组数
      this.form.stationNo = row.工位号
      this.form.fourNumber = row.工位代码
      this.title = '编辑'
      this.dialogFormVisible = true
    },
    submitAdd1() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          var param = []
          param[0] = ['IP', this.form.IP]
          param[1] = ['工位号', this.form.stationNo]
          param[2] = ['工位代码', this.form.fourNumber]
          param[3] = ['报警数', this.form.numberAlarms]
          param[4] = ['质量组数', this.form.massNumber]
          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
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: '',
          method: 'post',
          data: {
            type: '4',
            name: `delete from Recipe_Machine where id = ${row.id}`
          }
        }).then(response => {
          if (response.data[0].result === '1') {
            this.$message.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 name,
            value,
            descript,
            comments
          for (let i = 0; i < 999; i++) {
            const attr = i + 2
            name = this.worksheet[j][`A${attr}`] ? this.worksheet[j][`A${attr}`].v : ''
            value = this.worksheet[j][`B${attr}`] ? this.worksheet[j][`B${attr}`].v : ''
            descript = this.worksheet[j][`C${attr}`] ? this.worksheet[j][`C${attr}`].v : ''
            comments = this.worksheet[j][`D${attr}`] ? this.worksheet[j][`D${attr}`].v : ''
            console.log(name, value, descript, comments)
            if (!name) {
              break
            } else {
              if (name) {
                await sleep(50)
                await this.insertToSQL(name, value, descript, comments)
              } else {
                this.loading = false
                this.$notify.error(`请确认导入文件是否正确`)
                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(name, value, descript, comments) {
      try {
        var param = []
        param[0] = ['name', name]
        param[1] = ['num', value]
        param[2] = ['descript', descript]
        param[3] = ['comments', comments]
        var Data = this.CreateData('12', 'Recipe_Machine_Excel', 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>

