<!--
  功能：功能描述 标签打印
  作者：
  邮箱：mingxichen@163.com
  时间：2024年04月08日 15:46:01
  版本：v1.0
  修改记录：
  修改内容：
  修改人员：
  修改时间：
-->
<template>
  <div class="vue-element-page-wrap" ref="tableContainer">
    <el-row class="page-search" justify="space-between" align="middle">
      <el-form ref="queryFormRef" :model="state.queryParams.params" :inline="true" @submit.native.prevent>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="物料编号" prop="MATERIALSPECNAME">
              <el-Input v-model="state.queryParams.params.MATERIALSPECNAME" placeholder="物料编号"
                v-on:keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="批次" prop="queryParams.params">
              <el-Input v-model="state.queryParams.params.CHARGE" placeholder="批次"
                v-on:keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="到货单" prop="MATERIALSPECNAME">
              <el-Input v-model="state.queryParams.params.RECEIVEREQUESTNAME" placeholder="请输入到货单"
                v-on:keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" @click="handleQueryInfo">搜索</el-button>
        <el-button type="primary" @click="print" :disabled="state.button_print" v-loading="state.loadings">打印</el-button>
      </div>
    </el-row>

    <div class="vue-element-page-table">
      <div class="page-table-operate">
        <div class="page-table-title">
          <div class="page-table-title-left">
            <span>库内标签打印</span>
          </div>
        </div>
        <div class="page-table-operateBtns">
          <el-popover :persistent="false" placement="right" popper-class="config-table-wrap" trigger="click">
            <template #reference>
              <el-button class="operateBtns-setting">
                <svg-icon icon-class="table_title" width="16px" height="16px" />
              </el-button>
            </template>
            <ConfigTable :list="materialTableConfig.column" @updateList="updateList" />
          </el-popover>
        </div>
      </div>
      <el-table :height="tableHeight" border v-loading="materialTableConfig.loading" :data="state.MaterialList" highlight-current-row height="600px"
        row-key="id" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <template v-for="(col, index) in materialTableConfig.column" :key="index">
          <el-table-column v-if="!col.hide" :label="col.header" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ col.field === "MAKEDATE" ? dayjs(scope.row[col.field]).format("YYYY-MM-DD") :
                scope.row[col.field] }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <pagination v-if="state.total > 0" :total="state.total" v-model:pageNumTo="state.queryParams.pageNum"
        v-model:pageSizeTo="state.queryParams.pageSize" @pagination="handleQuery" />
    </div>
    <div class="vue-element-page-table flex">
      <div>
        <el-row class="page-search" justify="space-between" align="middle">
          <el-form ref="portFormRef" :inline="true" label-position="left">
            <el-row :gutter="20">
              <el-col :span="4">
                <el-form-item label="选择打印机" v-model="state.PRINTNAME" >
                  <!--                <el-select clearable filterable v-model="state.PRINTLIST" placeholder="请选择打印机"-->
                  <!--                           class="product-input">-->
                  <!--                  <el-option v-for="item in state.PRINTLIST" :key="item.VALUE" :label="item.LABEL"-->
                  <!--                             :value="item.VALUE" />-->
                  <!--                </el-select>-->
                  <el-select v-model="state.PRINTNAME" placeholder="请选择打印机" style="width: 240px">
                    <el-option v-for="item in state.PRINTLIST" :key="item.VALUE" :label="item.LABEL" :value="item.VALUE" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-button type="primary" @click="print" :disabled="state.button_print"
                           v-loading="state.loadings">打印</el-button>
              </el-col>
            </el-row>

          </el-form>
        </el-row>
      </div>

    </div>
  </div>
</template>
<script lang="ts">
export default {
  name: 'labels'
};
</script>
<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import { ElForm, ElMessageBox,ElTable, ElMessage } from "element-plus";
import {getQueryPageList, BpelEvent, getQueryList} from '@/api/common';
import { printLabel, Getprinter } from "@/api/label";
import dayjs from 'dayjs';
import queryListStore from "@/store/modules/queryList";
import { bTableHeight } from "../../../composables/calcTableHeight";

const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(270);
const queryFormRef = ref(ElForm);
const formDataRef = ref(ElForm);
const store: any = queryListStore()


/***---------------------------------------------------------------------------
 * -------------------------------------页面SQL语句配置------------------------------------------ */
const state = reactive({
  button_print: false,
  loadings: false,
  rsa: '',
  FIRSTORDERLIST: '',
  DBProcessType: 'save',
  queryParams: {
    queryId: 'GetlabelList',
    version: 'sdk003',
    listCode: '', // 查询类型
    params: {
      MATERIALSPECNAME: '',
      SITENAME: 'SDK',
      RECEIVEACTNO: '',
      RECEIVEREQUESTNAME: '',
      CHARGE: ''
    },
    pageNum: 1,
    pageSize: 10
  },
  ChangeParams: {
    header: {
      MESSAGENAME: '',
      LANGUAGE: 'Chinese',
    },
    body: {
      INRATIO: '',
      OUTRATIO: '',
      IS_CON_TEMP: '',
      DESCRIPTION: '',
      MATERIALSPECNAME: '',
      SITENAME: 'SDK',
      MATERIALSPECDESCRIPTION: '',
      CHECKSTATE: '',
      MATERIALSPECTYPE: '',
      MAKEDATE: '',
      MAKEUSER: '',
      DESC_CN: '',
      DESC_EN: '',
      MATERIALTYPE: '',
      MATERIALGROUP: '',
      MATERIALGROUPDESCRIPTION: '',
      MATERIALUNIT: '',
      MATERIALWEIGHT: '',
      ERPFACTORY: '',
      ERPLOCATION: '',
      MATERIALLIFEMARK: '',
      EXPIRINGDATE: '',
      STOCKDATE: '',
    }
  },
  total: 0,
  loading: false,
  MaterialList: [] as any,
  dialog: {
    title: '新增用户',
    visible: false
  },

  formData: {
    total: 0,
    SUPPLIERNO: '',
    SUPPLIERNAME: '',
    NATIONALNO: '',
    DESCRIPTION: '',
    ADDRESS: '',
    POSTCODE: '',
    CITY: '',
    TEL: '',
    FAX: '',
    INCHARGE: '',
    EMAIL: '',
    LASTEVENTTIME: '',
  } as any,
  PRINTLIST : []as any,//打印机
  PRINTNAME : '',
  column: [] as any,
  selectItem: undefined as any,
  currentTime: '',
  allRole: [] as any,
  ReceiveACTList: [] as any,
  multipleSelection: [] as any

})

const materialTableConfig = ref({
  loading: false,
  column: [] as any,
  data: [],
})

/***---------------------------------------------------------------------------
 * -------------------------------------钩子函数区域------------------------------------------ */
onMounted(() => {
  materialTableConfig.value.column = [
    // { header: "工厂", field: "SITENAME", hide: false },
    { header: "组织", field: "ERPFATCORYNAME", hide: false },
    { header: "仓库", field: "ERPLOCATIONNAME", hide: false },
    { header: "货位", field: "LOCATIONNAMEDESC", hide: false },
    { header: "标签编号", field: "MATERIALPACKINGNAME", hide: false },
    { header: "物料编码", field: "MATERIALSPECNAME", hide: false },
    { header: "批次", field: "CHARGE", hide: false },
    { header: "数量", field: "MATERIALQUANTITY", hide: false },
    { header: "单位", field: "FNAME", hide: false },
    { header: "实际规格", field: "TRUEGG", hide: false },
    { header: "SDK规格", field: "SPECNAME", hide: false },
    { header: "质检结果", field: "OQARESULT", hide: false },
    { header: "生产日期", field: "MAKEDATE", hide: false },
    { header: "用户", field: "User", hide: true },

  ]
  // 初始化时调用 handleQuery  
  handleQuery();
  getPRINTLIST();
  updateTableHeight();
  window.addEventListener('resize', handleResize);
});

const exportLabel = () => {
  console.log("state.multipleSelection", state.multipleSelection); // 打印选中行的数据  
  printLabel(state.multipleSelection)
    .then((res: any) => {
      console.log(res.data);
    })
    .catch(() => { });
}



const handleSelectionChange = (val: any) => {
  state.multipleSelection = val;

};
function handleQueryInfo() {
  state.queryParams.pageNum = 1
  handleQuery()
}
const handleQuery = () => {
  console.log(state.queryParams)
  state.MaterialList = []
  getQueryPageList(state.queryParams)
    .then((res: any) => {
      if(res.data.list.length == 0){
        
        ElMessageBox.alert('查无数据', '提醒框', {
          confirmButtonText: 'OK',
        })
        state.loading = false
      } else {
        state.MaterialList = []
        for (let i = 0; i < res.data.list.length; i++) {
          state.MaterialList.push({ ...res.data.list[i], User: localStorage.getItem('userId') })
        }
        //state.MaterialList = res.data.list;
        state.total = res.data.total;
      }
    })
    .catch(() => { });
}
function getPRINTLIST() {
  getQueryList({
    queryId: "getPRINTLIST",
    version: "00001",
    params: {
    },
  }).then((res: any) => {
    state.PRINTLIST = res.data
  })
}
function print() {
  if (state.PRINTNAME == null || state.PRINTNAME == "") {
    ElMessageBox.alert('请选择打印机', {
      confirmButtonText: 'OK',
    })
    return
  }
  if ( state.multipleSelection.length == 0) {
    ElMessageBox.alert('打印清单为空', {
      confirmButtonText: 'OK',
    })
    return
  }
  
  let PRINT = {
    LIST : state.multipleSelection,
    PRINTNAME : state.PRINTNAME,
    USER : localStorage.getItem('userId')
  }
  state.button_print = true;
  state.loadings = true;
  printLabel(PRINT).then((res: any) => {
    console.log('re',res)
    // if (res.success) {
    //   ElMessageBox.alert('标签打印成功', {
    //     confirmButtonText: 'OK',
    //   })
    //   state.button_print = false;
    //   state.loadings = false;
    // }else {
    //   state.button_print = false;
    //   state.loadings = false;
    // }
    console.log(state.PRINTNAME)
    if(state.PRINTNAME == 'PDF') {
      console.log(res.resultObj)
      let arrList = res.resultObj;
      arrList.map((item: any) => {
        let fileName = JSON.parse(item)?.filePath;
        downloadPDF(fileName);
      })
      
    }
  }).catch(() => { 
    state.button_print = false;
      state.loadings = false;
  })
  ElMessageBox.alert('标签打印成功', {
    confirmButtonText: 'OK',
  })
  state.button_print = false;
  state.loadings = false;
}
function downloadPDF(fileName: any) {
  // 要下载的文件路径
  var fileUrl =  fileName;
  // 创建一个隐藏的<a>元素，用于下载文件
  var a = document.createElement('a');
  a.href = fileUrl;
  a.download = fileName; // 可以自定义下载文件的名称
  a.style.display = 'none';
  a.target = '_blank'
  // 将<a>元素添加到页面上
  document.body.appendChild(a);
  // 触发点击事件，开始下载
  a.click();
  // 下载完成后，移除<a>元素
  document.body.removeChild(a);
}
function Queryprinter() {
  Getprinter({

  }).then((res: any) => {
    state.FIRSTORDERLIST = res.data
  })
}
// function SelectReceiveAct(): void {
//   state.queryParams.queryId = 'GetNormalReceiveActNoList'
//   state.queryParams.version = 'H0002'
//   state.queryParams.listCode = 'select'

//   store.getQueryList(state.queryParams)
//   state.ReceiveACTList = dataArr

// }

const updateList = (col: any) => {
  materialTableConfig.value.column = col
}
</script>

<style scoped></style>
