<template>
  <div class="app-container">
    <el-card class="topCard">
      <div class="topDiv">
        <span style="margin-left: 10px">工位号：</span>
        <el-select v-model="stationNumberValue" placeholder="请选择工位号" size="small" style="width: 150px">
          <el-option
            v-for="item in stationNumber"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            size="mini"/>
        </el-select>
        <span style="margin-left: 10px">Andon类型：</span>
        <el-select v-model="andonValue" placeholder="请选择Andon类型" size="small" style="width: 150px">
          <el-option
            v-for="item in andonArr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            size="mini"/>
        </el-select>
        <el-button type="primary" plain size="small" icon="el-icon-search" style="margin-left: 10px" @click="searchOrder()">查询</el-button>
        <el-button type="distribution" size="small" icon="el-icon-circle-plus" @click="creatOrder('form')">添加</el-button>
        <el-button type="info" plain size="small" icon="el-icon-upload2" @click="importOrder('form')">导入</el-button>
      </div>
      <el-table
        v-loading="loading"
        ref="multipleTable"
        :data="tableData"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :cell-class-name="tableRowClassName"
        element-loading-text="数据加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.2)"
        class="main"
        tooltip-effect="dark"
        style="width: 100%;max-height: 700px"
        border
        size="mini"
        @selection-change="handleSelectionChange">
        <el-table-column type="index" width="60" label="序号" align="center"/>
        <el-table-column align="center" label="工位号">
          <template slot-scope="scope">
            {{ scope.row.工位号 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="Andon类型">
          <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="编号描述">
          <template slot-scope="scope">
            {{ scope.row.编号描述 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)">修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="deleteInformation(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-sizes="[15, 30, 40]"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>
    </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="工位号" prop="stationNumberValue" style="display: inline-block">
          <el-select v-model="form.stationNumberValue" size="small" placeholder="请选择工位号">
            <el-option
              v-for="item in stationNumber"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="Andon类型" prop="andonValue" style="display: inline-block">
          <el-select v-model="form.andonValue" size="small" placeholder="请选择Andon类型">
            <el-option
              v-for="item in andonArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="编号描述" prop="numberDescription" style="display: inline-block">
          <el-input
            v-model="form.numberDescription"
            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 v-if="title === '添加'" type="primary" size="small" @click="submitAdd('form')">确定</el-button>
        <el-button v-if="title === '修改'" type="primary" size="small" @click="submitAdd1()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogFormVisible1" title="编辑生产订单" center style="min-height: 200px" width="400px">
      <el-form ref="form1" :model="form1" :rules="rules1" label-position="right" label-width="110px">
        <el-form-item label="物料号" prop="orderNumber" style="display: inline-block">
          <el-input
            v-model="form1.orderNumber"
            clearable
            size="small"
            placeholder="请输入物料号"/>
        </el-form-item>
        <el-form-item label="零件名称" prop="partName" style="display: inline-block">
          <el-input
            v-model="form1.partName"
            clearable
            size="small"
            placeholder="零件名称"/>
        </el-form-item>
        <el-form-item label="零件图号" prop="partDrawing" style="display: inline-block">
          <el-input
            v-model="form1.partDrawing"
            clearable
            size="small"
            placeholder="请输入零件图号"/>
        </el-form-item>
        <el-form-item label="数量" prop="number" style="display: inline-block">
          <el-input
            v-model="form1.number"
            clearable
            size="small"
            placeholder="请输入数量"/>
        </el-form-item>
        <el-form-item label="生产厂家" prop="manufactor" style="display: inline-block">
          <el-input
            v-model="form1.manufactor"
            clearable
            size="small"
            placeholder="请输入生产厂家"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="callOff1()">取消</el-button>
        <el-button type="primary" size="small" @click="submitAdd1()">确定</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 UploadExcelComponent from './UploadExcel.vue'
import { sleep } from '../../../utils/tool'
// import request from '@/utils/request'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      stationNumber: [],
      stationNumberValue: '',
      stationName: '',
      andonArr: [],
      andonValue: '',
      andonLabel: '',
      worksheet: [],
      itemFile: [],
      unSpecification: [],
      title: '',
      andonID: '',
      form: { // 创建订单
        stationNumberValue: '',
        andonValue: '',
        numberDescription: ''
      },
      rules: { // 创建订单验证
        stationNumberValue: [{ required: true, message: '请选择工位号', trigger: 'change' }],
        andonValue: [{ required: true, message: '请选择Andon类型', trigger: 'change' }],
        numberDescription: [{ required: true, message: '请输入编号描述', trigger: 'blur' }]
      },
      form1: { // 修改订单
        partName: '',
        orderNumber: '',
        partDrawing: '',
        number: '',
        manufactor: '',
        verificationValue: 0,
        mainMaterialValue: 0,
        ID: ''
      },
      rules1: { // 修改订单验证
        partName: [{ required: true, message: '请输入零件名称', trigger: 'blur' }],
        orderNumber: [{ required: true, message: '请输入物料号', trigger: 'blur' }],
        partDrawing: [{ required: true, message: '请输入零件图号', trigger: 'blur' }],
        number: [{ required: true, message: '请输入数量', trigger: 'blur' }],
        manufactor: [{ required: true, message: '请输入生产厂家', trigger: 'blur' }],
        verificationValue: [{ required: true, message: '请选择是否验证', trigger: 'change' }],
        mainMaterialValue: [{ required: true, message: '请选择是否主物料', trigger: 'change' }]
      },
      form2: { // 订单下发
        planQuantity: '',
        orderNumber: '',
        engineTypeValue: '',
        MID: '',
        IssuedQuantity: 1
      },
      rules2: { // 订单下发验证
        planQuantity: [{ required: true, message: '请输入计划数量', trigger: 'blur' }],
        orderNumber: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
        engineTypeValue: [{ required: true, message: '请选择机型', trigger: 'blur' }],
        IssuedQuantity: [{ required: true, message: '请输入订单下发数量', trigger: 'blur' }]
      },
      // planTime: [new Date(new Date().getTime() - 3600 * 1000 * 24 * 3000), new Date(new Date().getTime())],
      planTime: [],
      tableData: [],
      importData: [],
      dialogFormVisible: false, // 创建订单
      dialogFormVisible1: false, // 修改订单
      dialogFormVisible3: false, // 订单导入
      states: '', // 当前库存状态
      MIDGroup: [],
      total: 0, // 总条数
      pageList: 15, // 每页显示条数
      pageSize: 15, // 每页显示条数
      pageCurrent: 1, // 后台获取页
      loading: false
    }
  },
  watch: {
    andonValue() {
      for (let i = 0; i < this.andonArr.length; i++) {
        if (this.andonArr[i].value === this.andonValue) {
          this.andonLabel = this.andonArr[i].label
        }
      }
      if (!this.andonValue) {
        this.andonLabel = ''
      }
    }
  },
  created() {
    this.getStationNumber()
    this.getEndStation()
    this.searchOrder()
  },
  methods: {
    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)
        }
      }
    },
    // 初始化获取产品型号
    getEndStation() {
      this.andonArr = []
      var param = []
      var Data = this.CreateData('11', 'ANDON_类型_查询', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.andonArr.push({
            label: response.data[i].安东类型描述,
            value: response.data[i].安东类型代码
          })
        }
      })
    },
    // 初始化获取工位号
    getStationNumber() {
      this.stationNumber = []
      var param = []
      var Data = this.CreateData('11', 'MES_计划BOM_工位与名称_查询', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.stationNumber.push({
            label: response.data[i].工位号,
            value: response.data[i].工位号,
            labelName: response.data[i].工序名称
          })
        }
      })
    },
    // 查询订单
    searchOrder() {
      this.tableData = []
      var param = []
      param[0] = ['工位号', this.stationNumberValue]
      param[1] = ['安东类型描述', this.andonLabel]
      var Data = this.CreateData('11', 'ANDON_类型_编号_工艺页查询', param)
      this.ExecDatabase(Data).then(response => {
        console.log(response, 66)
        if (response.data.length !== 0) {
          this.tableData = response.data
        }
      })
    },
    // 创建订单
    creatOrder(formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
      this.form.stationNumberValue = ''
      this.form.andonValue = ''
      this.form.numberDescription = ''
      this.dialogFormVisible = true
      this.title = '添加'
    },
    // 提交新增订单
    submitAdd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var param = []
          param[0] = ['工位号', this.form.stationNumberValue]
          param[1] = ['安东类型代码', this.form.andonValue]
          param[2] = ['编号描述', this.form.numberDescription]
          var Data = this.CreateData('12', 'ANDON_类型_编号_工艺页增加', param)
          this.ExecDatabase(Data).then(response => {
            if (response.data[0].result === '1') {
              this.$message({
                message: '增加成功',
                type: 'success'
              })
              this.dialogFormVisible = false
              this.searchOrder()
            } else {
              this.$message.error('增加失败！')
            }
          })
          this.dialogFormVisible = false
        } else {
          return false
        }
      })
    },
    // 取消新增订单
    callOff(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    // 导入订单
    importOrder() {
      this.dialogFormVisible3 = true
    },
    // 删除订单
    deleteInformation(row) {
      this.$confirm('此操作将永久删除该行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var param = []
        param[0] = ['ID', row.ID]
        var Data = this.CreateData('12', 'ANDON_类型_编号_工艺页删除', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === '1') {
            this.$message({
              message: '订单删除成功',
              type: 'success'
            })
            this.searchOrder()
          } else {
            this.$message.error('订单删除失败！')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 修改订单
    handleEdit(row) {
      if (this.$refs['form'] !== undefined) {
        this.$refs['form'].resetFields()
      }
      this.andonID = row.ID
      this.form.stationNumberValue = row.工位号
      this.form.andonValue = row.安东类型代码
      this.form.numberDescription = row.编号描述
      this.dialogFormVisible = true
      this.title = '修改'
    },
    // 提交修改订单
    submitAdd1() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          var param = []
          param[0] = ['ID', this.andonID]
          param[1] = ['工位号', this.form.stationNumberValue]
          param[2] = ['安东类型代码', this.form.andonValue]
          param[3] = ['编号描述', this.form.numberDescription]
          var Data = this.CreateData('12', 'ANDON_类型_编号_工艺页编辑', param)
          this.ExecDatabase(Data).then(response => {
            if (response.data[0].result === '1') {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.searchOrder()
            } else {
              this.$message.error('修改失败！')
            }
          })
          this.dialogFormVisible = false
        } else {
          return false
        }
      })
    },
    // 取消修改订单
    callOff1() {
      this.dialogFormVisible = false
      this.$refs['form'].resetFields()
    },
    // 多选
    handleSelectionChange(val) {
      this.MIDGroup = []
      for (let i = 0; i < val.length; i++) {
        this.MIDGroup.push(val[i].MID)
      }
    },
    // 表格颜色变化
    tableRowClassName({ row, rowIndex }) {
      // console.log(row, rowIndex)
      if (rowIndex % 2 === 0) {
        return 'black'
      } else {
        return 'red'
      }
    },
    async basicPartsToSQL() {
      try {
        this.loading = true
        this.err = 0
        for (let j = this.worksheet.length - 1; j >= 0; j--) {
          let
            stationNumberValue,
            andonTypeNumber,
            number,
            numberDescription,
            numberDescription2
          var param = []
          param[0] = ['编号', this.worksheet[j].C2.v]
          console.log('编号', this.worksheet[j].C2.v)
          var Data = this.CreateData('11', 'ANDON_类型_编号_导入校验', param)
          const response = await this.ExecDatabase(Data)
          const res = response.data
          if (res[0].Column1 !== 0) {
            this.$notify.error(`${this.worksheet[j].C2.v}已经存在，请确认文件是否正确`)
            this.loading = false
            this.disabled = false
            return
          } else {
            for (let i = 0; i < 999; i++) {
              const attr = i + 2
              stationNumberValue = this.worksheet[j][`A${attr}`] ? this.worksheet[j][`A${attr}`].v : ''
              andonTypeNumber = this.worksheet[j][`B${attr}`] ? this.worksheet[j][`B${attr}`].v : ''
              number = this.worksheet[j][`C${attr}`] ? this.worksheet[j][`C${attr}`].v : ''
              numberDescription = this.worksheet[j][`D${attr}`] ? this.worksheet[j][`D${attr}`].v : ''
              numberDescription2 = this.worksheet[j][`E${attr}`] ? this.worksheet[j][`E${attr}`].v : ''
              if (!stationNumberValue && !andonTypeNumber &&
                  !number && !numberDescription && !numberDescription2) {
                break
              } else if (!number) { // 名称不能为空
                this.$notify.error(`编号不能为空`)
                break
              } else {
                if (number) {
                  await sleep(50)
                  await this.insertToSQL(stationNumberValue,
                    andonTypeNumber,
                    number,
                    numberDescription,
                    numberDescription2)
                } else {
                  this.loading = false
                  this.disabled = 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.searchOrder()
      } catch (e) {
        this.err++
        this.loading = false
        this.$notify.error(`导入数据错误,请检查导入文件是否正确`)
        console.log(`导入数据错误${e}`)
      }
    },
    async insertToSQL(stationNumberValue,
      andonTypeNumber,
      number,
      numberDescription,
      numberDescription2) {
      try {
        var param = []
        param[0] = ['工位号', stationNumberValue]
        param[1] = ['安东类型代码', andonTypeNumber]
        param[2] = ['编号', number]
        param[3] = ['编号描述', numberDescription]
        param[4] = ['编号描述2', numberDescription2]
        param[5] = ['导入类型', '1', 'int', '1']
        var Data = this.CreateData('12', 'ANDON_类型_编号_导入Excel', param)
        const response = await this.ExecDatabase(Data)
        const res = response.data
        if (res.hasOwnProperty('output') === false) {
          if (res[0].result === '0') {
            this.$notify.error(`${number}导入失败`)
          }
        } else {
          if (res.result[0].result === '0') {
            this.$notify.error(`${number}导入失败`)
          }
          if (res.output[0].导入类型 === '2') {
            this.$notify.warning(`${number}存在重复数据`)
          }
        }
      } catch (e) {
        this.err++
        this.$message.error(`导入数据错误`)
        console.log(`导入数据错误${e}`)
      }
    },
    // 分页
    handleSizeChange(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.searchOrder()
    },
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.searchOrder()
    }
  }
}
</script>

<style scoped>
  .topCard{
    margin: 5px;
  }
  .topDiv{
    margin-bottom: 10px;
  }
  .el-select{
    width:200px
  }
  .el-input{
    width:200px
  }
  .text {
    font-size: 14px;
  }

  .item {
    padding: 18px 0;
  }

  .box-card {
    position: absolute;
    right: 6px;
    top: 80px;
    width: 300px;
  }
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }

  /deep/.el-input.is-disabled .el-input__inner{
    color: #606266!important;
  }
  /deep/.el-input.is-disabled .el-input__inner{
    background-color: white!important;
  }
</style>

