<template>
  <div>
    <el-card class="el-card">
      <el-form :model="filterQuery" class="query-form" label-width="100px" v-if="showSearch">
        <el-row>
          <el-col :span="12">
            <el-form-item prop="code" label="扫码录入:">
              <el-input
                id="inputer"
                @focus="getInputFocus($event)"
                @keypress.enter.native="enterKey($event)"
                ref="inputRef"
                style="ime-mode: disabled"
                type="tel"
                placeholder="请点击输入框进行扫码设置或者扫码录入"
                v-model="filterQuery.code"
              ></el-input>
            </el-form-item>
         </el-col>
        </el-row>
        <el-row>
         <el-col :span="4">
           <el-form-item label="产品编码:">
             <el-input v-model="filterQuery.productCode"  placeholder="请输入产品编码" clearable></el-input>
           </el-form-item>
         </el-col>
         <el-col :span="4">
           <el-form-item label="批次号:">
             <el-input v-model="filterQuery.batchNo"  placeholder="请输入批次号" clearable></el-input>
           </el-form-item>
         </el-col>
         <el-col :span="4">
            <el-form-item label="失效日期:">
            <el-date-picker
                style="width: 100%"
                :picker-options="pickerOptions"
                v-model="actDateRange"
                type="daterange"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="top-right-btn">
        <el-button-group style="display:flex;">
          <el-button icon="el-icon-view" type="primary" @click="hideSearch">显示/隐藏搜索栏</el-button>
          <el-button type="primary" icon="el-icon-refresh" @click="onReset">重置</el-button>
          <el-button type="primary" icon="el-icon-search" @click="onSubmitFind">查询</el-button>
          <!-- <el-button type="primary" icon="el-icon-plus" @click="newDistributionForm()" :loading="loading">手动新增</el-button> -->
          <el-upload
              :action="action"
              :headers ="headers"
              accept=".xml"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :on-success="handleSuccess"
              :on-progress="handleProgress"
              :on-error="handleError"
              :before-upload="beforeUpload"
              :limit="5"
              :on-exceed="handleExceed"
              :file-list="fileList"
              :show-file-list="false"
              :data="extraData">
              <el-button size="small" icon="el-icon-upload" type="primary">文件上传</el-button>
              <!-- <div slot="tip" class="el-upload__tip">只能上传xml文件，且不超过5M</div> -->
            </el-upload>
        </el-button-group>
      </div>

      <el-divider style="margin: 15px"></el-divider>

      <el-table v-loading="loading" :data="list" border highlight-current-row
                :default-expand-all="isExpandAll"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                style="width: 100%"   row-key="id" >
        <el-table-column label="序号" type="index" width="60"></el-table-column>
        <el-table-column label="产品编码" prop="productCode"></el-table-column>
        <el-table-column label="包装规格" prop="packUnit"></el-table-column>
        <el-table-column label="装箱类型" prop="packageSpec"></el-table-column>
        <el-table-column label="批次号" prop="batchNo"></el-table-column>
        <el-table-column label="生产日期" prop="madeDate"></el-table-column>
        <el-table-column label="失效日期" prop="validateDate"></el-table-column>
        <el-table-column label="供应商Id" prop="erpId"></el-table-column>
        <el-table-column label="备注" prop="comment"></el-table-column>
        <el-table-column label="操作" width="120px">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click.native.stop="deleteDialog(scope.row)">删除</el-button>
<!--            <el-button type="text" size="small" @click.native="newDistributionForm(scope.$index, scope.row)">拼箱</el-button>-->
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="filterQuery.page"
        :limit.sync="filterQuery.limit"
        @pagination="handleCurrentChange"

      ></pagination>

      <el-dialog
        :title="formName"
        :visible.sync="newSpDistributionVisible"
        width="85%"
        append-to-body
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        v-if="newSpDistributionVisible"
        @close='closeDialog'
      >
        <operateRelCode
          :closeDialog="closeDialog"
          :orderQuery="idQuery"
        ></operateRelCode>
      </el-dialog>

    </el-card>
  </div>
</template>
<script>
import {getList,delRelCode} from "@/api/collect/relCode";
import {getAdminId, getToken} from '@/utils/auth';
import operateRelCode from "@/views/collect/relCode/operateRelCode"
import Treeselect from "@riophae/vue-treeselect";
import A from "@/plugins/KeyScaner";

export default {
  name: "relCode",
  data() {
    return {
      showSearch: true,
      newSpDistributionVisible: false,
      filterQuery: {
        billAction: null,
        billNo: "",
        page: 1,
        limit: 10,
        corpName: null
      },
      isExpandAll: true,
      idQuery: null,
      formName: null,
      loading: false,
      list: [],
      formData: null,
      total: 0,
      actDateRange:[],
      scanCode:null,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      headers:{
        ADMINID: getAdminId(),
        ADMINTOKEN: getToken()
      },
      extraData:{"uuid": "upload-xml"},
      uploadLoading: false,
      action: process.env.VUE_APP_BASE_API + "/udiwms/relCode/batch/xmlUpload",
      fileList: []
    };
  },

  methods: {
    onReset() {
      this.$router.push({
        path: "",
      });
      this.filterQuery = {
        billNo: "",
        thirdSysFk: "",
        billFlag: null,
        billAction: null,
        startDate: null,
        endDate: null,
        code:null,
        page: 1,
        limit: 10,
        corpName: null,
        type: 1,
        editStatus: 1,
      };
      this.actDateRange = [];
      this.getList();
    },
    onSubmitFind() {
      this.filterQuery.page = 1;
      this.getList();
    },
    hideSearch() {
      this.showSearch = !this.showSearch;
    },
    newDistributionForm(index, row) {
      if (this.$isNotBlank(row) && this.$isNotBlank(row.id)) {
        this.idQuery = row;
        this.formName = "拼箱";
        this.newSpDistributionVisible = true;
      } else {
        this.formName = "新增";
        this.newSpDistributionVisible = true;
      }
    },
    closeDialog() {
      this.newSpDistributionVisible = false;
      this.getList();
      this.detailList = [];
    },
    enterKey(event){
      this.onSubmitFind()
    },
    getInputFocus(event) {
        event.currentTarget.select();
    },
    deleteDialog(row) {
      this.$confirm("此操作将永久删除关联记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delRelCode({id:row.id})
          .then((response) => {
            if (response.code == 20000) {
              this.getList();
            } else {
              this.$message.error(response.message);
            }
          })
        .catch(() => {

        });
        })
        .catch(() => {
        });
    },
    getList() {
      this.loading = true;
      if (this.actDateRange !== null) {
        this.filterQuery.startDate = this.actDateRange[0];
        this.filterQuery.endDate = this.actDateRange[1];
      } else {
        this.filterQuery.startDate = null;
        this.filterQuery.endDate = null;
      }
      getList(this.filterQuery)
        .then((response) => {
          if (response.code == 20000) {
            this.list = response.data.list || [];
            this.total = response.data.total || 0;
          } else {
            this.$message.error(response.message);
          }
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
          this.list = [];
          this.total = 0;
        });
    },
    handleCurrentChange(val) {
      this.filterQuery.page = val.page;
      this.getList();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    handleSuccess(res, file, fileList) {
      fileList = fileList.filter(item => item.response.code === 20000);
      this.fileList = fileList;
      if (res.code === 20000) {
        this.$message.success(res.message);
      } else {
        this.$message.error(res.message);
      }
      this.uploadLoading.close();
    },
    beforeUpload(file) {
      const isXML = file.type === 'text/xml';
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isXML) {
        this.$message.error('上传文件只能是 XML 格式!');
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!');
      }
      return isXML && isLt5M;
    },
    handleProgress() {
      this.uploadLoading = this.$loading({
        lock: true,
        text: '文件上传中…',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      });
    },
    handleError() {
      this.uploadLoading.close();
      this.$message.error('文件上传失败，请检查文件大小或文件格式');
    }
  },
  components: {
    operateRelCode,
    Treeselect,
  },
  filters: {},
  mounted() {
      document.body.ondrop = function (event) {
        event.preventDefault();
        event.stopPropagation();
      };
      var that = this;
      var inputer = document.getElementById("inputer");
      window.sc = new A.KeyScaner(inputer); //传入要监听的DOM节点
      sc.onInput = function (text) {
        if (text.includes("delete")) {
          that.codeFormData.code = "";
          that.sictomText = "";
          that.originCode = "";
          return;
        }
        if (that.sitcomScan) {
          let tempTxt = text;
          let str = tempTxt.replace(/[\r]/g, "");
          that.sictomText = that.sictomText + str;
          that.codeFormData.code = that.sictomText;
        } else {
          that.codeFormData.code = text;
        }
      };
      inputer.focus();
      this.$refs.inputRef.focus();
  },
  created() {
    this.getList();
  },
}
;
</script>
<style scoped>
</style>

