<template>
  <div class="app-container">
    <el-card v-loading="loading">
      <!--      <el-col :span="6">-->
      <!--        <el-steps :active="5" direction="vertical" style="height: 260px;margin-left: 50px">-->
      <!--          <el-step title="选择项目"/>-->
      <!--          <el-step title="选择类型"/>-->
      <!--          <el-step title="浏览"/>-->
      <!--          <el-step title="导入到数据库"/>-->
      <!--          <el-step title="传递"/>-->
      <!--        </el-steps>-->
      <!--      </el-col>-->
      <el-col :span="6">
        <div style="width: 650px;margin: 0px 400px ">
          <div style="overflow: hidden">
            <div style="margin-bottom: 0px;">
              <span>项目：</span>
              <el-select v-model="projectValue" filterable size="small" placeholder="项目名称" style="margin-top: 3px">
                <el-option
                  v-for="item in project"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
              <span style="margin-left: 10px">类型：</span>
              <el-select v-model="groupName" filterable size="small" placeholder="类型">
                <el-option
                  v-for="item in Group"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
              <el-button type="primary" size="small" icon="el-icon-upload2" style="margin-left: 10px" @click="opendialogVisibleMachine()">上传总图</el-button>
            </div>
            <upload-excel-component @on-selected-file="selected"/>
          </div>
          <div>
            <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" action=""/>
          </div>
          <div v-if="worksheet.length !== 0" style="float: right;margin: 3px 0">
            <el-button :disabled="disabled" icon="el-icon-upload2" type="primary" size="small" @click="basicPartsToSQL">导入到数据库</el-button>
          </div>
        </div>
      </el-col>
    </el-card>
    <specification-data ref="specificationData" :groups-names="groupsNames" :machine-names="machineNames" :project-name="projectName" :group-name="groupName" @machineChange="machineChange"/>
    <el-dialog
      v-el-drag-dialog
      :visible.sync="dialogVisibleMachine"
      width="30%">
      <el-card>
        <el-select v-model="machineDrawValue" clearable filterable size="small" placeholder="机床名称" @change="changeMachine">
          <el-option
            v-for="item in machineDraw"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <div style="float: right;">
          <el-upload
            :disabled="disabledMachine"
            :action="action"
            :on-success="uploadSuccess"
            :on-error="uploadFailure"
            :show-file-list="showFileList"
            :file-list="fileList"
            class="upload-demo"
            multiple>
            <el-button :disabled="disabledMachine" size="small" type="primary">点击上传</el-button>
          </el-upload>
        </div>
      </el-card>
      <el-card>
        <div v-for="(file, key) in hadFile" :key="key">
          <div class="wrapper">
            <div class="content">
              <div class="action">
                <a class="delete" @click="deleteFileData(file.id)">删除</a>
              </div>
              <div v-if="file.suffix==='pdf'" class="icon"><svg-icon icon-class="pdf" /></div>
              <div v-else-if="file.suffix==='docx'||file.suffix === 'doc'" class="icon"><svg-icon icon-class="doc" /></div>
              <div v-else-if="file.suffix==='xlsx' || file.suffix === 'xls'" class="icon"><svg-icon icon-class="excel" /></div>
              <div v-else-if="file.suffix==='pptx' || file.suffix === 'ppt'" class="icon"><svg-icon icon-class="ppt" /></div>
              <div v-else-if="file.suffix==='jpg' || file.suffix === 'jpeg'|| file.suffix === 'png'" class="icon"><svg-icon icon-class="pic" /></div>
              <div v-else class="icon"><svg-icon icon-class="file" /></div>
              <a :href="file.url"><div class="info">{{ file.name }}</div></a>
            </div>
          </div>
        </div>
      </el-card>
    </el-dialog>
  </div>
</template>

<script>
import UploadExcelComponent from './UploadExcel/index.vue'
import specificationData from './specificationData'
import { sleep } from '../../../utils/tool'
import { initProject, isExit, isExit1, importBasics, importPurcharse, searchMachine, searchGroupNum, machineSelect, getFileData, deleteFileData } from '../../../api/TechnologyCenter/ImportParts'
import { uploadFileMachine, downloadFileMachine } from '@/utils/request'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent, specificationData },
  data() {
    return {
      fileList: [],
      hadFile: [],
      showFileList: true,
      projectId: '',
      action: '',
      disabledMachine: true,
      machineDrawValue: '',
      machineDraw: [],
      dialogVisibleMachine: false,
      project: [],
      projectValue: '',
      worksheet: [],
      itemFile: [],
      loading: false,
      groupsNames: [],
      groupName: '',
      Group: [{
        value: 'MX',
        name: 'MX'
      }, {
        value: 'WG',
        name: 'WG'
      }, {
        value: 'BZ',
        name: 'BZ'
      }],
      group: '',
      ceshi: '',
      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: {
    opendialogVisibleMachine() {
      this.machineDraw = []
      this.machineDrawValue = ''
      this.dialogVisibleMachine = true
      this.machineDrawValue === '' ? this.disabledMachine = true : this.disabledMachine = false
      this.getSelect(machineSelect, ['机床图号', '机床流水号'], 'machineDraw', this.projectValue)
    },
    changeMachine() {
      this.machineDrawValue === '' ? this.disabledMachine = true : this.disabledMachine = false
      this.action = `${uploadFileMachine}?&MachineNum=${this.machineDrawValue}`
      this.getFileData(this.machineDrawValue)
    },
    uploadSuccess(res, file, fileList) {
      if (res[0].result === '1') {
        const index = fileList.indexOf(file)
        fileList.splice(index, 1)
      } else {
        this.$message.error(`${file.name}文件上传失败，请检查上传文件是否正确！`)
      }
      if (fileList.length === 0) {
        this.$message.success('文件上传成功')
        this.getFileData(this.machineDrawValue)
      }
    },
    uploadFailure(a, file, fileList) {
      fileList.map(file => {
        this.$message.error(`${file.name}文件上传失败，请检查上传文件是否正确！`)
      })
    },
    // 在什么情况下需要查询上传的附件，调用this.getFileData()即可根据
    getFileData(machineDrawValue) {
      this.hadFile = []
      getFileData(machineDrawValue).then(res => {
        if (res.data.length > 0) {
          res.data.map(item => {
            this.hadFile.push({
              url: `${downloadFileMachine}?id=${item.文件标识}.${item.文件后缀}&name=${item.文件名称}.${item.文件后缀}`,
              name: `${item.文件名称}.${item.文件后缀}`,
              suffix: item.文件后缀,
              id: item.文件标识
            })
          })
        }
      })
    },
    deleteFileData(id) {
      this.deleteRow(deleteFileData, id, function() { this.getFileData(this.machineDrawValue) })
    },
    async test() {
      await sleep(10000)
    },
    fetchData() {
      this.getSelect(initProject, ['项目名称', '项目流水号'], 'project')
    },
    // 根据项目获取机床
    projectChange(val) {
      this.machineNames = []
      if (val) {
        this.getSelect(searchMachine, ['机床'], 'machineNames', val)
      }
    },
    // 根据机床获取分组
    machineChange(val) {
      this.groupsNames = []
      if (val) {
        searchGroupNum(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,
            drawingNum,
            name,
            type,
            material,
            spareNum,
            useNum,
            manufacturer,
            remarks,
            classificationCode
          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 {
            if (this.worksheet[j].M2.v === '00-MX') {
              this.group = this.worksheet[j].M2.v
              if (this.worksheet[j].M2.v.substring(0, 1) !== '9') {
                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].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].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, 1, 1, drawingNum, name, type, material, spareNum, useNum, manufacturer, remarks, classificationCode)
                    } else {
                      this.loading = false
                      this.disabled = false
                      this.$notify.error(`请确认导入文件是否正确`)
                      return
                    }
                  }
                }
              } else {
                this.$notify.error('禁止导入整改组')
                break
              }
            } else {
              this.group = this.worksheet[j].M2.v.substring(0, this.worksheet[j].M2.v.indexOf('-')) + '组'
              const response = await isExit1(this.projectValue, this.worksheet[j].F2.v, this.group)
              const res = response.data
              if (res[0].Column1 === 0) {
                this.$notify.error(`${this.group}组件不存在，请确认文件是否正确`)
                this.loading = false
                this.disabled = false
                return
              } else {
                if (this.worksheet[j].M2.v.substring(0, 1) !== '9') {
                  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].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].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, 1, 1, drawingNum, name, type, material, spareNum, useNum, manufacturer, remarks, classificationCode)
                      } else {
                        this.loading = false
                        this.disabled = false
                        this.$notify.error(`请确认导入文件是否正确`)
                        return
                      }
                    }
                  }
                } else {
                  this.$notify.error('禁止导入整改组')
                  break
                }
              }
            }
          }
          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.projectChange(this.projectName) // 调用查询机床方法，通过watch属性检测变化会自动得到下面表格的值。
      } catch (e) {
        this.err++
        this.loading = false
        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, this.group, contractNum, totalNum, pageNum, drawingNum, name, type, material, spareNum, useNum, manufacturer, remarks, classificationCode)
          const res = response.data
          if (res.hasOwnProperty('output') === false) {
            if (res[0].result === '0') {
              this.$notify.error(`${drawingNum}导入失败`)
            }
          } else {
            if (res.result[0].result === '0') {
              this.$notify.error(`${drawingNum}导入失败`)
            }
            if (res.output[0].导入类型 === '2') {
              this.$notify.warning(`存在重复数据`)
            }
          }
        } else {
          const response = await importPurcharse(establishment, proofread, review, date, this.projectName, machineNum, machineName, componentName, componentNum, this.group, contractNum, totalNum, pageNum, drawingNum, name, type, material, spareNum, useNum, manufacturer, remarks, classificationCode)
          const res = response.data
          if (res.hasOwnProperty('output') === false) {
            if (res[0].result === '0') {
              this.$notify.error(`${drawingNum}导入失败`)
            }
          } else {
            if (res.result[0].result === '0') {
              this.$notify.error(`${drawingNum}导入失败`)
            }
            if (res.output[0].导入类型 === '2') {
              this.$notify.warning(`存在重复数据`)
            }
          }
        }
      } catch (e) {
        this.err++
        this.$message.error(`导入数据错误`)
        console.log(`导入数据错误${e}`)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
/*.wrapper{*/
  /*width: 100%;*/
  /*margin: 0 auto;*/
/*}*/
.wrapper{
  width: 225px;
  height: 50px;
  overflow: hidden;
  border: 1px solid #b8c7d9;
  float: left;
  margin: 10px;
}
.content{
  position: relative;
  padding: 8px 8px 0 8px;
}
.action{
  position: absolute;
  top: 4px;
  right: 8px;
}
.delete{
  padding: 0 5px;
  border-radius: 3px;
  color: #0f84b0;
  font-size: 12px;
}
.delete:hover{
  background: -webkit-linear-gradient(top,#0ba9e3,#0099d3);
  color: #fff;
}
a{
  text-decoration: none;
}
.icon{
  width: 30px;
  height: 30px;
  display: inline-block;
  margin-right: 7px;
  margin-top: 2px;
  font-size: 26px;
}
.info{
  position: absolute;
  left: 44px;
  line-height: 30px;
  display: inline-block;
  color: #999;
}
</style>
