<template>
  <el-dialog :visible.sync="dialog" append-to-body :title="isEdit ? '追加归档' : '扫码归档'" width="50%" @close="closeDialog">
    <el-alert title="请将光标移动到“扫码框”内，并用扫码枪扫描纸质报告右上方条形码进行归档，请勿手动输入。" style="margin-top: -10px; margin-bottom: 5px;" type="warning" :closable="false" />
    <el-form ref="archive" :model="archive" size="small" label-width="100px">
      <el-row :gutter="16">
        <el-col :span="8">
          <el-form-item label="扫码框">
            <el-input v-model="baogaobianhao" style="width: 300px;" @paste.native.capture.prevent="handlePaste" @keyup.enter.native="handleKeyUpEnter" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="8">
          <el-form-item label="归档架号" required>
            <AutoComplete ref="autoComplete" :frame-nums="frameNums" :frame-num="archive.frameNum" :is-edit="isEdit" @getFrameNum="setValMethod" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="列" prop="columnNum" required>
            <el-input v-model="archive.columnNum" :disabled="isEdit" style="width: 150px;" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="8">
          <el-form-item label="归档盒号" prop="boxNum" required>
            <el-input v-model="archive.boxNum" :disabled="isEdit" style="width: 150px;" />
          </el-form-item>
        </el-col>
      </el-row>
      <!--表格渲染-->
      <el-table :data="paramList" size="mini" height="400px" border fit highlight-current-row stripe width="100%">
        <el-table-column type="index" align="center" label="序号" />
        <el-table-column align="center" label="报告编号" prop="baogaobianhao" />
        <el-table-column align="center" label="设备种类" prop="shebeizhonglei" />
        <el-table-column align="center" label="使用单位" prop="shiyongdanwei" />
        <el-table-column align="center" label="注册代码" prop="zhucedaima" />
        <el-table-column align="center" label="使用登记证编号" prop="shiyongdengjibianhao" />
        <el-table-column align="center" label="产品编号" prop="chanpinbianhao" />
        <el-table-column align="center" label="操作" min-width="65">
          <template slot-scope="scope">
            <el-button v-if="!scope.row.archiveId" type="danger" size="small" icon="el-icon-delete" @click="removeInfo(scope.$index)" />
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="dialog = false">
        取消
      </el-button>
      <el-button type="primary" @click="doSubmit">
        确认
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import Utils from '../../utils/contact.js'
import AutoComplete from './components/AutoComplete/index'
export default {
  components: { AutoComplete },
  props: {
    frameNums: {
      type: Array,
      required: true
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    id: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      paramList: [],
      dialog: false,
      archive: {},
      baogaobianhao: '',
      isJd: false,
      isCy: false,
      jianyijiahao: [] // 建议输入框里的归档架号
    }
  },
  methods: {
    doInit() {
      this.$nextTick(() => {
        this.jianyijiahao = this.frameNums
        if (this.isEdit) {
          this.server({
            url: '/archive/archive/getArchiveInfo/' + this.id,
            method: 'get'
          }).then(data => {
            this.archive = data.archive
            this.paramList = data.paramList
          })
        }
      })
    },
    // 扫码
    handleKeyUpEnter() {
      // 判断是否第一次进行录入
      if (this.paramList.length === 0) {
        this.unknownScan()
      } else {
        // ------ 第二条及之后的逻辑
        // 生成报告编号数组，用来判断新录入的报告编号是否存在
        const bgbhArray = []
        this.paramList.forEach(data => bgbhArray.push(data.baogaobianhao))
        // 判断所有元素确定是哪个系统的报告数据
        // 有三种情况 1、16版机电类 2、18版承压类 3、未在系统内的报告
        if (bgbhArray.indexOf(this.baogaobianhao) < 0) {
          if (this.isJd) {
            // 去16版机电类查询
            this.server.defaults.headers.common['projectMark'] = 'OLD'
            this.server({
              url: '/archive/report/getReportByBgbh/' + this.baogaobianhao,
              method: 'get'
            }).then(data => {
              this.server.defaults.headers.common['projectMark'] = ''
              if (data != null && data !== '') {
                this.addJdData()
              } else {
                // 去18版承压类进行查询
                this.server({
                  url: '/archive/ysjl/getYsjlByBgbh/' + this.baogaobianhao,
                  method: 'get'
                }).then(data => {
                  if (data != null && data !== '') {
                    this.$message.error('请选择机电类纸质报告进行扫描！')
                    this.baogaobianhao = ''
                  } else {
                    this.addUnknownData()
                  }
                })
              }
            }).catch(() => {
              this.baogaobianhao = ''
              this.server.defaults.headers.common['projectMark'] = ''
            })
          } else if (this.isCy) {
            // 去18版承压类进行查询
            this.server({
              url: '/archive/ysjl/getYsjlByBgbh/' + this.baogaobianhao,
              method: 'get'
            }).then(data => {
              if (data != null && data !== '') {
                this.addCyData()
              } else {
                // 去16版机电类查询
                this.server.defaults.headers.common['projectMark'] = 'OLD'
                this.server({
                  url: '/archive/report/getReportByBgbh/' + this.baogaobianhao,
                  method: 'get'
                }).then(data => {
                  this.server.defaults.headers.common['projectMark'] = ''
                  if (data != null && data !== '') {
                    this.$message.error('请选择承压类纸质报告进行扫描！')
                    this.baogaobianhao = ''
                  } else {
                    this.addUnknownData()
                  }
                }).catch(() => {
                  this.baogaobianhao = ''
                  this.server.defaults.headers.common['projectMark'] = ''
                })
              }
            }).catch(() => {
              this.baogaobianhao = ''
            })
          } else {
            this.unknownScan()
          }
        } else {
          this.baogaobianhao = ''
        }
      }
    },
    // 当未确定下来时
    unknownScan() {
      // 先去18版承压类进行查询
      this.server({
        url: '/archive/ysjl/getYsjlByBgbh/' + this.baogaobianhao,
        method: 'get'
      }).then(data => {
        if (data != null && data !== '') {
          this.isCy = true
          this.addCyData(data)
        } else {
          // 去16版机电类查询
          this.server.defaults.headers.common['projectMark'] = 'OLD'
          this.server({
            url: '/archive/report/getReportByBgbh/' + this.baogaobianhao,
            method: 'get'
          }).then(data => {
            this.server.defaults.headers.common['projectMark'] = ''
            if (data != null && data !== '') {
              this.isJd = true
              this.addJdData(data)
            } else {
              this.addUnknownData()
            }
          }).catch(() => {
            this.server.defaults.headers.common['projectMark'] = ''
            this.baogaobianhao = ''
          })
        }
      }).catch(() => {
        this.baogaobianhao = ''
      })
    },
    // 禁止扫码框粘贴
    handlePaste() {
      return false
    },
    addUnknownData() {
      this.server({
        url: '/archive/archive/checkArchiveState/' + this.baogaobianhao,
        method: 'get'
      }).then(() => {
        this.paramList.unshift({ baogaobianhao: this.baogaobianhao })
        this.baogaobianhao = ''
      }).catch(() => {
        this.baogaobianhao = ''
      })
    },
    addCyData(data) {
      this.paramList.unshift({
        id: data.id,
        baogaobianhao: data.baogaobianhao,
        shebeizhonglei: data.shebeizhonglei,
        shiyongdanwei: data.shiyongdanwei,
        zhucedaima: data.zhucedaima,
        shiyongdengjibianhao: data.shiyongdengjibianhao,
        chanpinbianhao: data.chanpinbianhao
      })
      this.baogaobianhao = ''
    },
    addJdData(data) {
      this.paramList.unshift({
        annalid: data.annalid,
        baogaobianhao: data.baogaobianhao,
        shebeizhonglei: data.shebeizhonglei,
        shiyongdanwei: data.shiyongdanwei,
        zhucedaima: data.zhucedaima,
        shiyongdengjibianhao: data.shiyongdengjibianhao,
        chanpinbianhao: data.chanpinbianhao
      })
      this.baogaobianhao = ''
    },
    // 执行归档报告
    doSubmit() {
      let archiveParamList = Object.assign([], this.paramList)
      if (this.isEdit) {
        archiveParamList = archiveParamList.filter(archiveParam => !archiveParam.archiveId)
      }
      if (!this.archive.frameNum) {
        this.$message.warning('请填写归档架号')
        return false
      }
      if (archiveParamList.length === 0) {
        this.$message.warning('请添加要归档的报告数据')
        return false
      }
      this.$refs['archive'].validate(valid => {
        if (valid) {
          this.archive.archiveUser = this.$store.getters.nickname
          this.archive.archiveCount = this.paramList.length
          if (this.isCy) {
            this.server({
              url: '/archive/archive/addNew',
              method: 'post',
              data: {
                archive: this.archive,
                params: archiveParamList,
                isEdit: this.isEdit
              }
            }).then(() => {
              this.$message.success('添加成功。')
              Utils.$emit('archive-list')
              this.dialog = false
            })
          } else if (this.isJd) {
            this.server({
              url: '/archive/archive/addOld',
              method: 'post',
              data: {
                archive: this.archive,
                params: archiveParamList,
                isEdit: this.isEdit
              }
            }).then(() => {
              this.server.defaults.headers.common['projectMark'] = 'OLD'
              archiveParamList = archiveParamList.filter(archiveParam => archiveParam.annalid)
              this.server({
                url: '/archive/report/updateReportState',
                method: 'post',
                data: {
                  params: archiveParamList
                }
              }).then(() => {
                this.$message.success('添加成功。')
                this.dialog = false
                this.$nextTick(() => {
                  this.server.defaults.headers.common['projectMark'] = ''
                  Utils.$emit('archive-list')
                })
              })
            })
          } else {
            this.server({
              url: '/archive/archive/addOld',
              method: 'post',
              data: {
                archive: this.archive,
                params: archiveParamList,
                isEdit: this.isEdit
              }
            }).then(() => {
              this.$message.success('添加成功。')
              this.dialog = false
              Utils.$emit('archive-list')
            })
          }
        } else {
          return false
        }
      })
    },
    // 清空单条已归档数据
    removeInfo($index) {
      if ($index === 0) {
        this.paramList.splice($index, $index + 1)
      } else {
        this.paramList.splice($index, 1)
      }
    },
    // 关闭归档报告窗口触发事件
    closeDialog() {
      this.$refs['archive'].resetFields()
      this.$refs.autoComplete.cleanNum()
      this.archive = {}
      this.baogaobianhao = ''
      this.paramList = []
      this.isCy = false
      this.isJd = false
    },
    // AutoComplete组件通信
    setValMethod(data) {
      this.archive.frameNum = data
    }
  }
}

</script>
