<template>
  <div>
    <el-card style="margin: 5px;">
      <el-form :model="inputQuery" label-width="110px" style="margin-bottom: -15px">
        <el-button-group style="display: flex; margin: 0px 0 15px 75%; height: 35px">
          <el-button size="mini" type="primary" @click.native="saveOrder(0)" :loading="draftLoading">草稿保存</el-button>
          <el-button size="mini" type="primary" @click.native="saveOrder(1)" :loading="submitLoading">立即提交</el-button>
        </el-button-group>
        <el-row>
          <el-col :span="17">
            <el-form-item label="UDI:">
              <el-input v-model="inputQuery.udiCode" ref="udiCodeInputRef" @keypress.enter.native="addCode($event)"
                        :disabled="detailList.length>0 || this.formName==2" placeholder="请输入UDI" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" size="mini" @click="addCode" :disabled="detailList.length>0"
                       style="margin-left: 15px">添加
            </el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="单据号:">
              <el-input v-model="inputQuery.orderIdFk" :disabled="true" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="标记:">
              <el-input v-model="inputQuery.mark" ref="markInputRef" :disabled="this.formName==2"
                        @keypress.enter.native="addMark($event)"
                        placeholder="请输入标记" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="物资名称:">
              <el-input v-model="inputQuery.cpmctymc" :disabled="true" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="规格型号:">
              <el-input v-model="inputQuery.ggxh" :disabled="true" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="总使用次数:">
              <el-input v-model="inputQuery.totalCount" :disabled="true" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="已使用次数:">
              <el-input v-model="inputQuery.useCount" :disabled="true" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="17">
            <el-form-item label="往来单位:">
              <el-input v-model="inputQuery.fromCorp" ref="fromCorpInputRef"
                        @keypress.enter.native="addFromCorp($event)" :disabled="this.inputQuery.udiCode==null || this.showFlg ==false"
                        placeholder="请输入往来单位" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" size="mini" :disabled="this.inputQuery.udiCode==null  || this.showFlg == false" @click="addFromCorp"
                       style="margin-left: 15px">添加
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card style="margin: 5px;">
      <el-table :data="detailList" style="width: 100%" border highlight-current-row>
        <el-table-column label="序号" type="index" width="60"></el-table-column>
        <el-table-column label="当前次数" prop="curIndex"></el-table-column>
        <el-table-column label="往来单位" prop="fromCorp" show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="使用人" prop="createUserName" show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="使用时间" prop="useTime" show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作" width="120px">
          <template slot-scope="scope">
            <el-button type="text" size="small" v-if="scope.row.status!=1" @click.native.stop="deleteDialog(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>


    <el-dialog
        :title="tableName"
        :visible.sync="orderMutiDelectVisible"
        width="60%"
        :append-to-body="true"
        v-if="orderMutiDelectVisible"
        @close='closeDialog'
        :close-on-click-modal="false"
        :close-on-press-escape="false"
    >
      <ioOrderMutiEditSelectDialog
          :closeDialogDelect="closeDialogDelect"
          :filterQuery="inputQuery"
      ></ioOrderMutiEditSelectDialog>
    </el-dialog>
  </div>
</template>

<script>
import {
  addMuti,
  addMutiDetail,
  addOrderMuti,
  checkUdi, delectMutiDelect, filterMutiDetailList,
  filterMutiList, getMark,
  selectMutiDetailList,
  updateMuti,
  updateOrderMuti
} from "@/api/inout/orderMuti";
import ioOrderMutiEditSelectDialog from "@/views/inout/muti/ioOrderMutiEditSelectDialog"


export default {
  name: "ioOrderMutiEditDialog",
  props: {
    closeDialog: {
      type: Function,
      required: true,
    },
    formName: {
      type: Object,
      required: true,
    },
    filterQuery: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      inputQuery: {
        udiCode: null,
        orderIdFk: null,
        mark: null,
        cpmctymc: null,
        ggxh: null,
        totalCount: null,
        useCount: null,
        supId: null,
      },
      pId: null,
      showFlg:false,
      popupsVisible: false,
      orderMutiDelectVisible: false,
      tableName: '使用记录选择',
      invList: [],
      fromInvOptions: [],
      busTypes: [],
      detailList: [],
      keyCode: '',
      lastTime: '',
      nextTime: '',// 上次时间、最新时间
      lastCode: '',
      nextCode: '',// 上次按键、最新按键
      draftLoading: false,
      submitLoading: false,
    }
  },
  mounted() {
    if (this.formName == 2) {
      this.$refs.fromCorpInputRef.focus();
    } else {
      this.$refs.udiCodeInputRef.focus();
    }
    this.enterKeyup();
  },
  destroyed() {
    // 销毁enter事件
    this.enterKeyupDestroyed();
  },
  methods: {
    enterKey(event) {
      this.nextCode = event.keyCode
      // 如果触发了回车事件(扫码结束时间)
      if (this.nextCode == 13) {
        if (this.keyCode == 'true') {
          this.saveOrder(1);
        } else if (this.keyCode == 'false') {
          this.saveOrder(0);
        }
        this.keyCode = ''
        this.lastCode = ''
        this.lastTime = ''
        return
      }
      this.nextTime = new Date().getTime() // 记录最新时间
      if (!this.lastTime && !this.lastCode) { // 如果上次时间和上次按键为空
        this.keyCode += event.key // 执行叠加操作
      }
      // 如果有上次时间及上次按键
      if (this.lastCode && this.lastTime && this.nextTime - this.lastTime > 30) { // 当扫码前有keypress事件时,防止首字缺失
        this.keyCode = event.key
      } else if (this.lastCode && this.lastTime) {
        this.keyCode += event.key
      }
      this.lastCode = this.nextCode
      this.lastTime = this.nextTime
    },
    enterKeyupDestroyed() {
      document.removeEventListener("keyup", this.enterKey);
    },
    enterKeyup() {
      document.addEventListener("keyup", this.enterKey);
    },
    addCode() {
      checkUdi(this.inputQuery).then((response) => {
        if (response.code == 20000) {
          this.pId = response.data;
          filterMutiList({id: this.pId}).then((response) => {
            if (response.code == 20000) {
              this.showFlg=true;
              this.inputQuery.cpmctymc = response.data.data.cpmctymc
              this.inputQuery.ggxh = response.data.data.ggxh
              this.inputQuery.totalCount = response.data.data.totalCount
              this.inputQuery.useCount = response.data.data.useCount
              if(this.inputQuery.mark!=null){
                this.formName=2
                this.inputQuery.mark = response.data.data.mark
              }
              this.detailList=response.data.detailList;
              this.$refs.fromCorpInputRef.focus();
            } else {
              this.$message.error(response.message);
            }
          }).catch(() => {
            this.$message.error("添加失败");
          });
        } else if (response.code == 999) {
          this.$message.error(response.message);
        } else if (response.code == 888) {
          this.$refs.udiCodeInputRef.blur();
          this.enterKeyupDestroyed();
          this.$showMsgBox({
            caption: "询问",
            msg: '是否要首次使用',
            callback: (data) => {
              if (data == 'yes') {
                addOrderMuti(this.inputQuery).then((response) => {
                  if (response.code == 20000) {
                    this.pId = response.data;
                    filterMutiList({id: this.pId}).then((response) => {
                      if (response.code == 20000) {
                        this.inputQuery.cpmctymc = response.data.data.cpmctymc
                        this.inputQuery.ggxh = response.data.data.ggxh
                        this.inputQuery.totalCount = response.data.data.totalCount
                        this.inputQuery.useCount = response.data.data.useCount
                        this.$refs.fromCorpInputRef.focus();
                        this.checkType=null;
                        this.showFlg=true;
                        this.formName=2
                        this.enterKeyup();
                      } else {
                        this.$refs.markInputRef.focus();
                      }
                    }).catch(() => {
                      this.$message.error("添加失败");
                    });
                  } else {
                    this.$message.error(response.message);
                  }
                }).catch(() => {
                  this.$message.error("添加失败");
                });
              } else if (data == 'no') {
                this.inputQuery.mark = "";
                this.checkType=1;
                this.showFlg=false;
                this.$refs.markInputRef.focus();
                this.enterKeyup();
              }

            }
          })
        }

      }).catch(() => {
        this.$message.error("添加失败");
      });
    },
    submitInv() {
      if (this.formName == 1) {
        addMuti(this.inputQuery).then((response) => {
          if (response.code == 20000) {
            this.closeDialog();
          } else {
            this.$message.error(response.message);
          }

        })
            .catch(() => {
              this.$message.error("添加失败");
            });
      } else {
        updateMuti(this.inputQuery).then((response) => {
          if (response.code == 20000) {
            this.closeDialog();
          } else {
            this.$message.error(response.message);
          }

        })
            .catch(() => {
              this.$message.error("添加失败");
            });
      }
    },
    addFromCorp() {
      if(this.$isBlank(this.inputQuery.fromCorp)){
        this.$message.error("往来单位不能为空！");
        return
      }
      if(this.$isBlank(this.inputQuery.mark)){
        this.$message.error("标记不能为空！");
        return
      }

      if (this.inputQuery.fromCorp != 'true' && this.inputQuery.fromCorp != 'false') {
        var query = {
          udiCode:this.inputQuery.udiCode,
          mark:this.inputQuery.mark,
          checkType:this.checkType,
          mutiIdFk: this.pId,
          fromCorp: this.inputQuery.fromCorp
        }
        addMutiDetail(query).then((response) => {
          if (response.code == 20000) {
            this.selectMutiDetailList();
            this.inputQuery.fromCorp = null;
          } else {
            this.$message.error(response.message);
          }
        })
            .catch(() => {
              this.$message.error("添加失败");
            });
      }
    },
    selectMutiDetailList() {
      selectMutiDetailList({mutiIdFk: this.pId}).then((response) => {
        if (response.code == 20000) {
          this.detailList = response.data || [];
          this.inputQuery.useCount = this.detailList.length
        }
      })
    },
    getMark() {
      getMark().then((response) => {
        if (response.code == 20000) {
          this.inputQuery.mark = response.data;
        }
      })
    },
    filterMutiList() {
      filterMutiList({id: this.pId}).then((response) => {
        if (response.code == 20000) {
          this.inputQuery.cpmctymc = response.data.data.cpmctymc
          this.inputQuery.mark = response.data.data.mark
          this.inputQuery.ggxh = response.data.data.ggxh
          this.inputQuery.totalCount = response.data.data.totalCount
          this.inputQuery.useCount = response.data.data.useCount
          this.detailList = response.data.detailList
          this.inputQuery.useCount = this.detailList.length
        } else {
          this.$message.error(response.message);
        }
      });
    },
    closeDialogDelect(row) {
      this.orderMutiDelectVisible = false;
      this.pId = row.id;
      this.filterMutiList();
    },
    saveOrder(status) {
      if(this.$isBlank(this.inputQuery.udiCode)){
        this.$message.error("UDI不能为空！");
        return
      }
      if(this.$isBlank(this.inputQuery.mark)){
        this.$message.error("标记不能为空！");
        return
      }
      if(this.detailList.length<=0 && status == 1){
        this.$message.error("往来单位不能为空！");
        return
      }

      var query = {
        id: this.pId,
        mark: this.inputQuery.mark,
        useCount: this.inputQuery.useCount,
        totalCount: this.inputQuery.totalCount,
        status: status
      }
      if (status === 0){
        this.draftLoading = true
      }else {
        this.submitLoading = true
      }
      updateOrderMuti(query).then((response) => {
        if (status == 0){
          this.draftLoading = false
        }else {
          this.submitLoading = false
        }
        if (response.code == 20000) {
          this.closeDialog()
        } else {
          this.$message.error(response.message);
        }
      });
    },
    deleteDialog(row) {
      delectMutiDelect({id: row.id}).then((response) => {
        if (response.code == 20000) {
          this.selectMutiDetailList()
        } else {
          this.$message.error(response.message);
        }
      });
    },
    addMark() {
      filterMutiDetailList({udiCode: this.inputQuery.udiCode, mark: this.inputQuery.mark}).then((response) => {
        if (response.code == 20000) {
          this.inputQuery.cpmctymc = response.data.cpmctymc
          this.inputQuery.ggxh = response.data.ggxh
          this.inputQuery.totalCount = response.data.totalCount
          this.inputQuery.useCount = response.data.useCount
          this.pId = response.data.id;
          this.showFlg=true;
          this.formName=2
          this.$refs.fromCorpInputRef.focus();
          this.selectMutiDetailList()
        } else {
          this.$message.error(response.message);
        }
      });
    }
  },
  components: {ioOrderMutiEditSelectDialog},
  created() {
    if (this.formName == 2) {
      this.inputQuery = this.filterQuery
      this.pId = this.inputQuery.id
      this.selectMutiDetailList()
    } else {
      this.getMark();
    }

  },
}
</script>

<style scoped>

</style>
