<template>
  <div class="app-container">
    <el-card v-loading="loading">
      <div style="width: 620px;margin: 0 auto">
        <div style="overflow: hidden">
          <div style="margin-bottom: 10px;">
            <span>项目：</span>
            <el-select v-model="projectValue" filterable size="small" placeholder="项目名称">
              <el-option
                v-for="item in project"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </div>
          <upload-excel-component @on-selected-file="selected"/>
        </div>
        <div>
          <el-tooltip content="删除全部" placement="top">
            <span v-show="worksheet.length > 1" style="cursor: pointer;float: right;margin: 5px" @click="removeAll"><i class="el-icon-close"/></span>
          </el-tooltip>
          <el-upload :on-remove="handleRemove" :file-list="itemFile" action=""/>
        </div>
        <div v-if="worksheet.length !== 0" style="float: right;margin: 20px 0">
          <el-button :disabled="disabled" icon="el-icon-upload2" type="primary" size="small" @click="basicPartsToSQL">导入到数据库</el-button>
        </div>
      </div>
    </el-card>
    <specification-data1 ref="specificationData" :groups-names="groupsNames" :machine-names="machineNames" :project-name="projectName" @machineChange="machineChange"/>
    <!--<el-upload-->
    <!--class="upload-demo"-->
    <!--drag-->
    <!--action="http://localhost:8410/submit/uploadImg.ashx?InvoiceNum=1"-->
    <!--multiple>-->
    <!--<i class="el-icon-upload"/>-->
    <!--<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>-->
    <!--<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
    <!--</el-upload>-->
  </div>
</template>

<script>
import UploadExcelComponent from '../ImportParts/UploadExcel/index.vue'
import specificationData1 from './specificationData1'
import { sleep } from '../../../utils/tool'
import { initProject, isExit, importBasics, importPurcharse, searchMachine, searchGroupNum1 } from '../../../api/TechnologyCenter/ImportParts'

export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent, specificationData1 },
  data() {
    return {
      project: [],
      projectValue: '',
      worksheet: [],
      itemFile: [],
      loading: false,
      groupsNames: [],
      machineNames: [],
      err: 0,
      disabled: false
    }
  },
  computed: {
    projectName() {
      for (let i = 0; i < this.project.length; i++) {
        if (this.project[i].value === this.projectValue) {
          return this.project[i].label
        }
      }
    }
  },
  watch: {
    projectValue(val) {
      if (val) {
        this.groupsNames = []
        this.machineNames = []
        this.projectChange(this.projectName)
      }
    },
    project(val) {
      if (val.length > 0) {
        this.projectValue = val[0].value
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    async test() {
      await sleep(10000)
      console.log(1)
    },
    fetchData() {
      this.getSelect(initProject, ['项目名称', '项目流水号'], 'project')
    },
    // 根据项目获取机床
    projectChange(val) {
      this.machineNames = []
      if (val) {
        this.getSelect(searchMachine, ['机床'], 'machineNames', val)
      }
    },
    // 根据机床获取分组
    machineChange(val) {
      this.groupsNames = []
      if (val) {
        searchGroupNum1(this.projectName, val).then(response => {
          const res = response.data
          res.forEach(item => {
            this.groupsNames.push({
              value: item.组号
            })
          })
        })
      }
    },
    async selected(data) { // 选择需要导入的文件
      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)
        }
      }
    },
    removeAll() {
      this.worksheet = []
      this.itemFile = []
    },
    async basicPartsToSQL() {
      try {
        this.loading = true
        this.dispatch = true
        this.err = 0
        for (let j = this.worksheet.length - 1; j >= 0; j--) {
          let establishment,
            proofread,
            review,
            date,
            machineName,
            machineNum,
            componentName,
            componentNum,
            groupNum,
            contractNum,
            pageNum,
            totalNum,
            drawingNum,
            name,
            type,
            material,
            spareNum,
            useNum,
            manufacturer,
            remarks,
            classificationCode
          console.log(this.worksheet[j].M2.v.substring(0, 1))
          if (this.worksheet[j].M2.v.substring(0, 1) === '9') {
            const response = await isExit(this.projectValue, this.worksheet[j].F2.v)
            const res = response.data
            if (res[0].Column1 === 0) {
              this.$notify.error(`${this.worksheet[j].F2.v}机床不存在，请确认文件是否正确`)
              this.loading = false
              this.disabled = false
              return
            } else {
              this.worksheet[j].G1 ? establishment = this.worksheet[j].G1.v : establishment = ''
              this.worksheet[j].I1 ? proofread = this.worksheet[j].I1.v : proofread = ''
              this.worksheet[j].L1 ? review = this.worksheet[j].L1.v : review = ''
              this.worksheet[j].P1 ? date = this.worksheet[j].P1.v : date = ''
              this.worksheet[j].Q1 ? pageNum = parseInt(this.worksheet[j].Q1.v.replace(/[^0-9]/ig, '')) : pageNum = ''
              this.worksheet[j].C2 ? machineName = this.worksheet[j].C2.v : machineName = ''
              this.worksheet[j].F2 ? machineNum = this.worksheet[j].F2.v : machineNum = ''
              this.worksheet[j].J2 ? componentName = this.worksheet[j].J2.v : componentName = ''
              this.worksheet[j].P2 ? componentNum = this.worksheet[j].P2.v : componentNum = ''
              this.worksheet[j].Q2 ? totalNum = parseInt(this.worksheet[j].Q2.v.replace(/[^0-9]/ig, '')) : totalNum = ''
              this.worksheet[j].R2 ? contractNum = this.worksheet[j].R2.v : contractNum = ''
              this.worksheet[j].M2 ? groupNum = this.worksheet[j].M2.v : groupNum = ''
              for (let i = 0; i < 999; i++) {
                const attr = i + 4
                drawingNum = this.worksheet[j][`B${attr}`] ? this.worksheet[j][`B${attr}`].v : ''
                name = this.worksheet[j][`D${attr}`] ? this.worksheet[j][`D${attr}`].v : ''
                type = this.worksheet[j][`F${attr}`] ? this.worksheet[j][`F${attr}`].v : ''
                material = this.worksheet[j][`J${attr}`] ? this.worksheet[j][`J${attr}`].v : ''
                spareNum = this.worksheet[j][`L${attr}`] ? this.worksheet[j][`L${attr}`].v : ''
                useNum = this.worksheet[j][`M${attr}`] ? this.worksheet[j][`M${attr}`].v : ''
                manufacturer = this.worksheet[j][`O${attr}`] ? this.worksheet[j][`O${attr}`].v : ''
                remarks = this.worksheet[j][`Q${attr}`] ? this.worksheet[j][`Q${attr}`].v : ''
                classificationCode = this.worksheet[j][`R${attr}`] ? this.worksheet[j][`R${attr}`].v : ''
                if (!drawingNum && !name && !type && !material && !spareNum && !useNum && !manufacturer && !remarks && !classificationCode) { // 当图号、名称、规格、材料、备件数量、装机数量、制造商、备注、分类码都为空时，循环终止，防止向数据库中插入多余且无用的数据
                  break
                } else {
                  if (machineNum && groupNum) {
                    await sleep(50)
                    await this.insertToSQL(establishment, proofread, review, date, machineName, machineNum, componentName, componentNum, groupNum, contractNum, pageNum, totalNum, drawingNum, name, type, material, spareNum, useNum, manufacturer, remarks, classificationCode)
                  } 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}，请检查文件是否正确`)
          } else {
            this.$message.error('只能导入整改组')
          }
        }
        this.loading = false
        this.projectChange(this.projectName) // 调用查询机床方法，通过watch属性检测变化会自动得到下面表格的值。
      } catch (e) {
        console.log(e)
        this.err++
        this.$notify.error(`导入数据错误,请检查导入文件是否正确`)
        console.log(`导入数据错误${e}`)
      }
    },
    async insertToSQL(establishment, proofread, review, date, machineName, machineNum, componentName, componentNum, groupNum, contractNum, pageNum, totalNum, drawingNum, name, type, material, spareNum, useNum, manufacturer, remarks, classificationCode) {
      try {
        if (groupNum.indexOf('MX') > -1) {
          const response = await importBasics(establishment, proofread, review, date, this.projectName, machineNum, machineName, componentName, componentNum, groupNum, contractNum, totalNum, pageNum, drawingNum, name, type, material, spareNum, useNum, manufacturer, remarks, classificationCode)
          const res = response.data
          console.log(res)
          if (res[0].result === '0') {
            this.$notify.error(`${drawingNum}导入失败`)
          }
          if (res[0].result === '2') {
            this.$notify.error(`${drawingNum}导入重复`)
          }
        } else {
          const response = await importPurcharse(establishment, proofread, review, date, this.projectName, machineNum, machineName, componentName, componentNum, groupNum, contractNum, totalNum, pageNum, drawingNum, name, type, material, spareNum, useNum, manufacturer, remarks, classificationCode)
          const res = response.data
          if (res[0].result === '0') {
            this.$notify.error(`${drawingNum}导入失败`)
          }
        }
      } catch (e) {
        this.err++
        this.$message.error(`导入数据错误`)
        console.log(`导入数据错误${e}`)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.wrapper{
  width: 100%;
  margin: 0 auto;
}
</style>
