<!--
  功能：无来源标签打印
  作者：lz
-->
<template>
  <div class="page-horizontal-wrap" ref="tableContainer">
    <div class="page-left-container">
      <div class="left-form-container" style="min-height:150px">
        <el-form ref="formDataRef" label-position="left" label-width="120px" :model="queryParam.materialreceiveAct">
          <el-form-item label="料号" prop="SENDORDERNO">
            <el-input size="small" v-model="queryParam.materialreceiveAct.MATERIALSPECNAME" placeholder="请输入料号" @change="getSdkInfo" @input="clearInfo" />
          </el-form-item>
          <el-form-item label="选择SDK规格" prop="SENDORDERNO" >
            <el-select filterable v-model="queryParam.materialreceiveAct.sdkid" placeholder="选择SDK规格" @click="getMATERIALSPECNAME"  :filter-method="locatioNFilter"
                       style="width: 300px">
              <!--                       @change="GetERPLocationForList">-->
              <el-option v-for="item in state.sdkList" :key="item.text" :label="item.text" lwhlslsk
                         :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="选择阶段" prop="SENDORDERNO">
            <el-select v-model="queryParam.materialreceiveAct.PHASE" placeholder="选择阶段">
              <el-option label="C" value="C" />
              <el-option label="D" value="D" />
              <el-option label="S" value="S" />
              <el-option label="" value="" />
            </el-select>
          </el-form-item>
          <el-form-item label="选择生产日期">
            <el-col :span="24">
              <el-date-picker
                v-model="queryParam.materialreceiveAct.MAKEDATE"
                type="date"
                placeholder="选择生产日期"
                style="width: 100%"
              />
            </el-col>
          </el-form-item>
          <el-form-item label="总数量">
            <el-input v-model="queryParam.materialreceiveAct.MATERIALQUANTITY" placeholder="填写总数量" />
          </el-form-item>
          <!-- <el-form-item label="组织" prop="ERPFACTORY">
            <el-select filterable v-model="queryParam.materialreceiveAct.ERPFACTORY" placeholder="下拉选择组织"
                       style="width: 240px">
              <el-option v-for="item in ERPFactoryList" :key="item.ENUMVALUE" :label="item.DESCRIPTION"
                         :value="item.ENUMVALUE" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="标签个数">
            <el-input v-model="queryParam.materialreceiveAct.MATERIALCREATEQUANTITY" placeholder="填写标签数量" />
          </el-form-item>

          <el-form-item label="选择单位" prop="SENDORDERNO">
            <el-select filterable v-model="queryParam.materialreceiveAct.UNIT" placeholder="选择单位"
                       style="width: 240px">
              <el-option v-for="item in state.unitList" :key="item.FNAME" :label="item.FNAME"
                         :value="item.FNUMBER" />
            </el-select>
          </el-form-item>
          <el-form-item label="实际规格">
            <el-input v-model="queryParam.materialreceiveAct.TRUEGG" placeholder="填写实际规格" />
          </el-form-item>
          <el-form-item label="备注">
          <el-input v-model="queryParam.materialreceiveAct.REMARK" placeholder="填写备注" />
        </el-form-item>
          <el-button type="primary" @click="getpows">新建</el-button>
        </el-form>
      </div>
    </div>
    <div class="vue-element-page-wrap" ref="tableContainer">
      <div class="vue-element-page-table">
        <!-- <el-row>
              <el-button type="primary" @click="clearFn">清空</el-button>
            </el-row> -->
        <el-table :height="tableHeight" border v-loading="undistributed_loading" :data="undistributed_list"
                  highlight-current-row row-key="id">
          <template v-for="(col, index) in undistributed_column" :key="index">
            <el-table-column v-if="!col.hide" :label="col.header" show-overflow-tooltip>
              <template #default="scope">
                <span>{{ scope.row[col.field] }}</span>
              </template>
            </el-table-column>
          </template>
          <template v-slot:empty>
            <svg-icon icon-class="noData" width="160px" height="160px" />
          </template>
        </el-table>
      </div>
      <div class="vue-element-page-table flex">
        <div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="选择打印机" v-model="state.PRINTNAME">
                <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="2">
              <el-button type="primary" @click="print" :disabled="state.button_print" v-loading="state.loadings">打印</el-button>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
  </div>
</template>


<script lang="ts">
const value = ref('')
import { ref } from 'vue'
export default {
  name: "printingOfWithoutSource",
};
</script>


<script lang="ts" setup>
import { ElForm, ElMessageBox } from 'element-plus'
import { onMounted, reactive, toRefs } from 'vue'
import { getSdkList, getTrackOutBox, getUnitList, printLabel } from '@/api/label'
import { getQueryList } from '@/api/common'
import { localStorage } from '@/utils/storage'
import { msToDate } from '@/utils/CommonUtil'
import { bTableHeight } from "../../../composables/calcTableHeight";

const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(100);
const formDataRef = ref(ElForm)
const queryParamRef = ref(ElForm)
const state = reactive({
  loadings: false,
  button_print: false,
  queryParam:{
    user:'',
    materialreceiveAct: {
      MATERIALSPECNAME: '',
      sdkid: '',
      PHASE: '',
      MAKEDATE: '',
      MATERIALQUANTITY: '',
      ERPFACTORY: '',
      MATERIALCREATEQUANTITY: '',
      UNIT: '',
      TRUEGG : '',
      REMARK : ''
    }
  },
  queryParamsERPFactory: {
    queryId: "GetErpFactoryList",
    version: "WEB00001",
    params: {
      SITENAME: localStorage.get("siteName") || 'SDK',
    },
    pageNum: 1,
    pageSize: 10
  },
  queryParamsSDK: {
    materialSpecName: ""
  },
  PRINTNAME: '',
  unit:'',
  PRINTLIST: [] as any,//打印机
  multipleSelection: [] as any,
  undistributed_column: [] as any,
  undistributed_list: [] as any,
  ERPFactoryList:[] as any,
  unitList:[] as any,
  sdkList:[] as any,
  sdkListAll:[] as any,
  undistributed_loading: false
})

const { queryParam, undistributed_column, undistributed_loading, undistributed_list ,ERPFactoryList,} = toRefs(state)

onMounted(() => {
  state.undistributed_column = [
    {
      header: '料号',
      field: 'MATERIALSPECNAME',
      width: '100px',
      hide: false
    },
    {
      header: '规格',
      field: 'SPECNAME',
      width: '100px',
      hide: false
    },
    {
      header: '阶段',
      field: 'PHASE',
      width: '100px',
      hide: false
    },
    {
      header: '数量',
      field: 'MATERIALQUANTITY',
      width: '100px',
      hide: false
    },
    {
      header: '单位',
      field: 'UNIT',
      width: '100px',
      hide: false
    }
    ,
    {
      header: '批次',
      field: 'CHARGE',
      width: '100px',
      hide: false
    },
    {
      header: '标签',
      field: 'MATERIALPACKINGNAME',
      width: '100px',
      hide: false
    },
    {
      header: '实际规格',
      field: 'TRUEGG',
      width: '100px',
      hide: false
    },
    {
      header: '备注',
      field: 'REMARK',
      width: '100px',
      hide: false
    }
  ]
  let pwd: any = localStorage.get('remeberPwd');
  state.queryParam.materialreceiveAct.ERPFACTORY = JSON.parse(localStorage.get('orgNo')) || '';
  getPRINTLIST();
  // ERPFactoryQuery();
  getUnitInfo();
  updateTableHeight();
  window.addEventListener('resize', handleResize);
})
function clearFn() {
  state.undistributed_list = []
}
function getpows() {
  let time = formatDate(msToDate(state.queryParam.materialreceiveAct.MAKEDATE).withoutTime)
  state.queryParam.user = localStorage.get('userId')
  state.queryParam.materialreceiveAct.MAKEDATE = time
  if('' == state.queryParam.materialreceiveAct.MATERIALSPECNAME){
    ElMessageBox.alert('请输入料号', {
      confirmButtonText: 'OK'
    })
    return
  }
  // if('1' != state.queryParam.materialreceiveAct.MATERIALSPECNAME.slice(0,1) || '2' != state.queryParam.materialreceiveAct.MATERIALSPECNAME.slice(0,1)){
  if('6' == state.queryParam.materialreceiveAct.MATERIALSPECNAME.slice(0,1)) {
      if ('' == state.queryParam.materialreceiveAct.PHASE) {
        ElMessageBox.alert('请输入阶段', {
          confirmButtonText: 'OK'
        })
        return
      }
  } else if ('3' == state.queryParam.materialreceiveAct.MATERIALSPECNAME.slice(0, 1) || '4' == state.queryParam.materialreceiveAct.MATERIALSPECNAME.slice(0, 1)) {
    if ('' == state.queryParam.materialreceiveAct.sdkid) {
      ElMessageBox.alert('请输入规格', {
        confirmButtonText: 'OK'
      })
      return
    }
    if ('' == state.queryParam.materialreceiveAct.PHASE) {
      ElMessageBox.alert('请输入阶段', {
        confirmButtonText: 'OK'
      })
      return
    }
  }
  if('NaN-NaN-NaN' == state.queryParam.materialreceiveAct.MAKEDATE){
    ElMessageBox.alert('请输入生产日期', {
      confirmButtonText: 'OK'
    })
    return
  }
  if('' == state.queryParam.materialreceiveAct.MATERIALCREATEQUANTITY){
    ElMessageBox.alert('请输入个数', {
      confirmButtonText: 'OK'
    })
    return
  }
  if('' == state.queryParam.materialreceiveAct.MATERIALQUANTITY){
    ElMessageBox.alert('请输入总数量', {
      confirmButtonText: 'OK'
    })
    return
  }
  if('' == state.queryParam.materialreceiveAct.ERPFACTORY){
    ElMessageBox.alert('请输入组织', {
      confirmButtonText: 'OK'
    })
    return
  }
  if('' == state.queryParam.materialreceiveAct.UNIT){
    ElMessageBox.alert('请输入单位', {
      confirmButtonText: 'OK'
    })
    return
  }
  // if(state.queryParam.materialreceiveAct.MATERIALQUANTITY < state.queryParam.materialreceiveAct.MATERIALCREATEQUANTITY){
  //   ElMessageBox.alert('输入的总数量 大于 标签个数', {
  //     confirmButtonText: 'OK'
  //   })
  //   return
  // }
  getTrackOutBox(state.queryParam)
    .then((res: any) => {
      if(res.success){
        state.undistributed_list = res.resultObj;
      } else {
        ElMessageBox.alert(res.message, {
          confirmButtonText: 'OK'
        })
      }
    })
    .catch(() => { });
}

function getUnitInfo(){
  getUnitList(state.unit)
    .then((res: any) => {
      state.unitList = res.resultObj;
    })
    .catch(() => { });
}

function getMATERIALSPECNAME() {
  if(queryParam.value.materialreceiveAct.MATERIALSPECNAME == null || queryParam.value.materialreceiveAct.MATERIALSPECNAME == ""){
    ElMessageBox.alert('请输入料号', {
      confirmButtonText: 'OK'
    })
    return ;
  }
}

function formatDate(dateString: any) {
  const date = new Date(dateString);
  // if (isNaN(date.getTime())) {
  //   throw new Error('Invalid date string');
  // }

  // 使用padStart方法来确保月份和日期都是两位数
  const year = date.getFullYear().toString();
  const month = (date.getMonth() + 1).toString().padStart(2, '0'); // getMonth() 返回的是0-11
  const day = date.getDate().toString().padStart(2, '0');
  // 拼接结果
  return `${year}-${month}-${day}`;
}

function getSdkInfo () {
  state.queryParam.materialreceiveAct.sdkid = ''
  state.sdkList = []
  state.queryParamsSDK.materialSpecName=queryParam.value.materialreceiveAct.MATERIALSPECNAME
  getSdkList(state.queryParamsSDK).then((res: any) => {
      state.sdkListAll = res.resultObj;
      locatioNFilter('1')
    })
    .catch(() => { });
}
function clearInfo () {
  console.log(11)
  state.queryParam.materialreceiveAct.sdkid = ''
  state.sdkList = []
}
function locatioNFilter(query : any) {
    console.log(query)
  let arr = state.sdkListAll.filter((item : any) => {
    return (item.text.includes(query) || item.value.includes(query))
  })
  if (arr.length > 50) {
    state.sdkList = arr.slice(0, 50)
  } else {
    state.sdkList = arr
  }
}

function ERPFactoryQuery() {
  getQueryList(state.queryParamsERPFactory)
    .then((res: any) => {
      state.ERPFactoryList = res.data;
      state.ERPFactoryList.unshift({
        ENUMVALUE: ''
      });
    })
    .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.undistributed_list.length == 0) {
    ElMessageBox.alert('打印清单为空', {
      confirmButtonText: 'OK'
    })
    return
  }
  let PRINT = {
    LIST: state.undistributed_list,
    PRINTNAME: state.PRINTNAME,
    USER: localStorage.get('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 {
    //   ElMessageBox.alert(res.message, {
    //     confirmButtonText: 'OK',
    //   })
    //   state.button_print = false;
    //   state.loadings = false;
    // }
  }).catch(() => {
    state.button_print = false;
    state.loadings = false;
  });
    ElMessageBox.alert('标签打印成功', {
      confirmButtonText: 'OK',
    })
    state.button_print = false;
    state.loadings = false;
}
</script>


<style scoped>

.demo-datetime-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
  justify-content: space-around;
  align-items: stretch;
}

.page-horizontal-wrap {
  display: flex;
  width: 100%;
  height: 100%;

  .page-left-container {
    width: 360px;
    height: 100%;
    background: #FFFFFF;
    border: 1px solid #DBDEE3;
    box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.10);
    border-radius: 4px;
    margin-right: 6px;
    padding: 10px;
    display: flex;
    flex-direction: column;

    :deep(.el-form-item) {
      margin-bottom: 20px;
    }

    .page-left-container-head {
      display: flex;
      justify-content: space-between;

      .page-form-title {
        font-size: 14px;
        color: #000000;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-weight: bold;
        margin-bottom: 10px;

        .el-icon {
          cursor: pointer;
        }
      }
    }
  }

  .vue-element-page-wrap {
    flex: 1;
  }
}
</style>