<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: 200px">
          <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">工位名称：</span>-->
        <!--        <el-input v-model="stationName" disabled style="width:150px;" placeholder="" size="small"/>-->
        <span style="margin-left: 10px">产品型号：</span>
        <el-select v-model="engineTypeValue" placeholder="请选择产品型号" size="small" style="width: 150px">
          <el-option
            v-for="item in engineType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            size="mini"/>
        </el-select>
        <el-button type="primary" plain size="small" icon="el-icon-order" @click="searchTable()">查询</el-button>
        <el-button type="distribution" icon="el-icon-circle-plus-outline" size="small" @click="addTo">上传</el-button>
      </div>
      <span>图片尺寸要求：宽*高（650 * 780）</span>
      <div style="height: 670px;overflow: auto;display: flex;flex-wrap: wrap;">
        <div v-for="(url, key) in urls" :key="key" style="width: 450px;height: 450px;margin: 5px;border: 1px solid black;display: flex;flex-direction: column;">
          <div style="display: flex;align-items: center">
            <span>【{{ key+1 }}】</span>
            <el-image :key="url.id" :src="url.url" :preview-src-list="urls1" lazy style="width: 64px; height: 77px;margin: 10px 10px 0 10px"/>
            <div style="width: 280px;word-break: break-all;">{{ url.name }}</div>
            <div>
              <div>
                <el-button type="text" size="mini" icon="el-icon-delete" style="color: #ff0000" @click="deleteInformation(url)">删除</el-button>
              </div>
              <div style="margin-top: 10px">
                <el-button type="text" size="mini" icon="el-icon-plus" @click="addMaterial(url)">物料</el-button>
              </div>
            </div>
          </div>
          <el-row>
            <el-table
              ref="multipleTable1"
              :data="url.data"
              :header-cell-style="{ background: '#F5F5F5' }"
              element-loading-text="数据加载中"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(0, 0, 0, 0.2)"
              height="340px"
              style="width: 100%;"
              border
            >
              <el-table-column align="center" label="物料号" width="120">
                <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="100">
                <template slot-scope="scope">
                  <el-button type="text" icon="el-icon-delete" style="color: #ff0000" @click="deleteInformationMaterial(scope.row)"/>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </div>
      </div>
    </el-card>
    <el-dialog v-el-drag-dialog :visible.sync="dialogFormVisible" title="上传图片" center width="300px">
      <el-upload
        id="invoiceScan"
        ref="upload"
        :on-remove="handelLimitStyle"
        :on-change="handelLimit"
        :multiple="true"
        :auto-upload="false"
        :on-success="uploadSuccess"
        :on-preview="handlePictureCardPreview"
        :before-upload="beforeUpload"
        :on-exceed="warningExceed"
        :limit="limit"
        :data="Data"
        :action="upload"
        accept=".png,.jpg"
        style="margin-left: 60px"
        list-type="picture-card">
        <i class="el-icon-plus"/>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible=false">取消</el-button>
        <el-button type="primary" style="width: 70px" @click="submitPicture()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogFormVisible1" title="绑定物料" center style="min-height: 200px;" width="800px">
      <el-row>
        <span style="margin-left: 10px">物料名/物料号：</span>
        <el-input v-model="materialCodeSelect" clearable size="small" style="width: 200px" @change="filterTable"/>
        <el-table
          ref="multipleTable1"
          :data="tableDataList"
          :header-cell-style="{ background: '#F5F5F5' }"
          element-loading-text="数据加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.2)"
          height="340px"
          style="width: 100%;"
          border
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"/>
          <el-table-column align="center" label="物料号" width="120">
            <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>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible1=false">取消</el-button>
        <el-button type="primary" size="small" @click="materialAddSubmit()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { url } from '@/utils/request'
export default {
  data() {
    return {
      urls: [], // 图片数组
      urlsID: [], // 图片数组
      urls1: [], // 图片数组
      dialogVisiblePictureCard: false,
      dialogImageUrl: '',
      limit: 1,
      Data: {},
      upload: url,
      tableData: [], // 总数据数组
      tableData1: [], // 总数据数组
      tableData2: [], // 总数据数组
      stationNumber: [],
      tableDataList: [],
      tableDataListOrigin: [],
      stationNumberValue: '',
      stationName: '',
      moduleDescription: [],
      moduleDescriptionValue: '',
      engineTypeValue: '',
      engineTypeValue1: '',
      engineTypeName: '',
      engineType: [],
      currentSelectRowList: [],
      isDisableValue: 0,
      labelText: '',
      labelNumber: '',
      materialCodeSelect: '',
      dialogFormVisible: false,
      dialogFormVisible1: false,
      currentSelectRow: false,
      title: ''
    }
  },
  computed: {
    ...mapGetters([
      'id',
      'token',
      'departmentName'
    ])
  },
  watch: {
    // stationNumberValue() {
    //   for (let i = 0; i < this.stationNumber.length; i++) {
    //     if (this.stationNumber[i].value === this.stationNumberValue) {
    //       this.stationName = this.stationNumber[i].labelName
    //     }
    //   }
    //   if (!this.stationNumberValue) {
    //     this.stationName = ''
    //   }
    // }
  },
  created() {
    // this.searchTable()
    this.selectDate1()
    this.getStationNumber()
    this.getEndStation()
  },
  methods: {
    // 绑定 提交
    materialAddSubmit() {
      const pl = []
      for (let i = 0; i < this.currentSelectRowList.length; i++) {
        pl.push(this.materialBinding(this.currentSelectRowList[i]))
      }
      Promise.all(pl).then(response => {
        this.$refs.multipleTable1.clearSelection()
        this.$message.success('绑定成功！')
        this.searchTableAfterFill(this.currentSelectRow.id)
      })
    },
    materialBinding(row) {
      return new Promise((resolve, reject) => {
        const param = []
        param[0] = ['ID', this.currentSelectRow.id]
        param[1] = ['物料号', row.物料号]
        const Data = this.CreateData('12', '电子看板_工位名称与产品型号产品图片_增加_绑定物料', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data.length > 0) {
            if (response.data[0].result === '1') {
              resolve(true)
            } else {
              reject(false)
            }
          } else {
            reject(false)
          }
        })
      })
    },
    handleSelectionChange(val) {
      this.currentSelectRowList = val
    },
    selectDate1() {
      this.tableDataList = []
      var param = []
      param[0] = ['站点编号', '']
      param[1] = ['物料号', '']
      param[2] = ['PageCurrent', 1]
      param[3] = ['PageSize', 1000]
      param[4] = ['PageCount', '1111', 'int', '1']
      param[5] = ['ItemCount', '1111', 'int', '1']
      var Data = this.CreateData('11', '电子看板_装配零件_物料拉动_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.result.length !== 0) {
          this.tableDataList = response.data.result
          this.tableDataListOrigin = response.data.result
        }
      })
    },
    filterTable() {
      if (this.materialCodeSelect === '') {
        this.tableDataList = this.tableDataListOrigin
      } else {
        this.tableDataList = this.tableDataListOrigin.filter(item => {
          if (item.物料号.includes(this.materialCodeSelect)) return true
          if (item.零件名称.includes(this.materialCodeSelect)) return true
          return false
        })
      }
    },
    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].工位号}】${response.data[i].工位名称}`,
            value: response.data[i].工位号,
            labelName: response.data[i].工序名称
          })
        }
        if (response.data.length > 0) this.stationNumberValue = response.data[0].工位号
      })
    },
    // 初始化获取产品型号
    getEndStation() {
      this.engineType = []
      var param = []
      var Data = this.CreateData('11', 'CATL_基础信息_机型信息_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) this.engineTypeValue = response.data[0].机型ID
        for (let i = 0; i < response.data.length; i++) {
          this.engineType.push({
            label: response.data[i].机型号,
            value: response.data[i].机型ID,
            labelName: response.data[i].机型号
          })
        }
      })
    },
    // 表格颜色变化
    tableRowClassName({ row, rowIndex }) {
      // console.log(row, rowIndex)
      if (rowIndex % 2 === 0) {
        return 'black'
      } else {
        return 'red'
      }
    },
    // 查询MES消息
    searchTable() {
      this.urls = []
      this.urls1 = []
      var param = []
      param[0] = ['发动机型号代码', this.engineTypeValue]
      param[1] = ['工位号', this.stationNumberValue]
      var Data = this.CreateData('11', '电子看板_工位名称与产品型号产品图片_SPC查询', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          if (response.data[i].产品图片) {
            this.urls.push({
              url: 'data:image/png;base64,' + response.data[i].产品图片,
              name: response.data[i].数字孪生,
              data: [],
              id: response.data[i].ID
            })
            this.urls1.push('data:image/png;base64,' + response.data[i].产品图片)
          }
        }
        this.searchTableAfter()
      })
    },
    searchTableAfter() {
      for (let i = 0; i < this.urls.length; i++) {
        this.searchTableAfterFill(this.urls[i].id)
      }
    },
    searchTableAfterFill(ID) {
      var param = []
      param[0] = ['图片ID', ID]
      var Data = this.CreateData('11', '电子看板_工位名称与产品型号产品图片_SPC查询_关联物料', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < this.urls.length; i++) {
          if (ID === this.urls[i].id) {
            this.urls[i].data = response.data
          }
        }
        this.dialogFormVisible1 = false
      })
    },
    addMaterial(row) {
      this.dialogFormVisible1 = true
      this.currentSelectRow = row
      this.currentSelectRowList = []
      this.materialCodeSelect = ''
    },
    addTo() {
      this.title = '添加'
      this.dialogFormVisible = true
    },
    handelLimit() {
      var obj = document.getElementsByClassName('el-upload--picture-card')
      if (obj[0].style.display === '') {
        for (var i = 0; i < obj.length; i++) {
          obj[i].style.display = 'none'
        }
      }
    },
    handelLimitStyle() {
      var obj = document.getElementsByClassName('el-upload--picture-card')
      if (obj[0].style.display === 'none') {
        for (var i = 0; i < obj.length; i++) {
          obj[i].style.display = 'block'
        }
      }
    },
    warningExceed() {
      this.$message.error('仅可上传一张照片')
    },
    beforeUpload(file) { // 上传前检测
      const isJPG = /^image\/.*/.test(file.type)
      if (!isJPG) {
        this.$message.error('只能上传图片。。')
      }
      return isJPG
    },
    uploadSuccess(res) { // 上传成功回调
      this.dialogFormVisible = false
      this.$refs.upload.clearFiles()
      var obj = document.getElementsByClassName('el-upload--picture-card')
      if (obj[0].style.display === 'none') {
        for (var i = 0; i < obj.length; i++) {
          obj[i].style.display = 'block'
        }
      }
    },
    updatePicture(row) {
      this.dialogFormVisible = true
      // this.purchaseContractID = row.采购合同流水号
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisiblePictureCard = true
    },
    submitPicture() {
      var param = []
      param[0] = ['发动机型号代码', this.engineTypeValue]
      param[1] = ['工位号', this.stationNumberValue]
      param[2] = ['文件名称', '']
      param[3] = ['文件后缀', '']
      param[4] = ['文件内容', null]
      console.log(param)
      var Data1 = this.CreateData('15', '电子看板_工位名称与产品型号产品图片_保存图片新', param)
      this.Data.param = Data1
      this.$refs.upload.submit()
      this.dialogFormVisible = false
    },
    callOff() {
      this.dialogFormVisible = false
      this.$refs['form'].resetFields()
      this.form.stationNumber = ''
      this.form.moduleDescription = ''
      this.form.number = ''
      this.form.text = ''
      this.engineTypeName = ''
      this.title = ''
    },
    callOff1() {
      this.dialogFormVisible1 = false
      this.$refs['form1'].resetFields()
      this.form.stationNumber = ''
      this.form.moduleDescription = ''
      this.form.number = ''
      this.form.text = ''
      this.engineTypeName = ''
      this.title = ''
    },
    editInformation(row) {
      this.labelNumber = row.ID
      this.form1.number = row.工步号
      this.form1.text = row.操作内容
      this.title = '编辑'
      this.dialogFormVisible1 = true
    },
    // 编辑消息
    submitUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var param = []
          param[0] = ['工步号', this.form1.number]
          param[1] = ['操作内容', this.form1.text]
          param[2] = ['ID', this.labelNumber]
          console.log(param)
          var Data = this.CreateData('12', '电子看板_工序内容_修改_要点理由YC', param)
          this.ExecDatabase(Data).then(response => {
            if (response.data[0].result === '1') {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.dialogFormVisible1 = false
              this.searchTable()
            } else {
              this.$message.error('修改失败！')
            }
          })
        } else {
          return false
        }
      })
    },
    deleteInformation(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: '已取消删除'
        })
      })
    },
    deleteInformationMaterial(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.searchTableAfterFill(row.图片ID)
          } else {
            this.$message.error('删除失败！')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</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;
  }

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

