<template>
  <div class="vue-element-page-wrap" ref="tableContainer">
    <el-row class="page-search" justify="space-between" align="bottom">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="发货单据" prop="params.SHIPREQUESTNAME">
              <el-Input v-model="queryParams.params.SHIPREQUESTNAME" @keydown.enter.prevent="handleQuery" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" @click="handleQuery">搜索</el-button>
      </div>
    </el-row>
     
    
    <div class="vue-element-page-table">
      <el-row>
        <div class="page-table-operate">
          <div class="page-table-title">
            <div class="page-table-title-left">
              <span>发货单据信息</span>
            </div>
          </div>
        </div>
    </el-row>
      <el-table border v-loading="loading" :data="ShipList" highlight-current-row row-key="id" style="width: 100%;min-height: 100px;"
        @row-click="handle">
        <template v-for="(col, index) in 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>
      </el-table>
    </div>
  
    <!-- 左右结构 -->
    <div class="vue-element-page-table">
      <el-row>
        <el-col :span="11">
          
          <div class="vue-element-page-table">
           
              <el-row :gutter="20">
                <el-col :span="20">
                  <div class="page-table-operate">
                    <div class="page-table-title">
                      <div class="page-table-title-left">
                        <span>未分配标签信息</span>
                      </div>
                      &nbsp; &nbsp; &nbsp; &nbsp;
                      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px" label-position="left">
                        <el-form-item label="货位" prop="params.LOCATION">
                          <el-select v-model="state.ChangeLocation"  clearable collapse-tags placeholder="请选择货位"
                                     popper-class="custom-header" :max-collapse-tags="1" style="width: 240px"
                                     @visible-change="JudgeMentERPLocation" filterable>
                            <template #header>
                            </template>
                            <el-option v-for="item in state.LocationList" :key="item.STORAGENAME" :label="item.DESCRIPTION"
                                       :value="item.STORAGENAME" />
                          </el-select>
                        </el-form-item>
                      </el-form>
                    </div>
                  </div>
                </el-col>
<!--                <el-col :span="10">-->
<!--                  <el-input  v-model="queryParams.params.CHARGE" type="textarea"  />-->
<!--                </el-col>-->
<!--                <el-col :span="3">-->
<!--                  <el-button type="primary" @click="chargeReserve"  v-loading="state.button_loading">指定批次</el-button>-->
<!--                </el-col>-->
<!--                <el-col :span="3">-->
<!--                  <el-button type="primary" @click="clearCharge"  v-loading="state.button_loading">清空批次</el-button>-->
<!--                </el-col>-->


              </el-row>
       
          
            <el-table :height="tableHeight" border v-loading="loading" :data="state.MaterialPackingList" highlight-current-row row-key="id"
            style="width: 100%;min-height:50px" @selection-change="handleSelectionChange2">
              <el-table-column type="selection" width="40" :selectable="selectable" :reserve-selection="false" />
              <template v-for="(col, index) in column1" :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>
            </el-table>
          </div>
        </el-col>
        
        <el-col :span="2" class="transfer-switch">
          <el-button type="primary" @click="LeftIn" v-loading="loading"><el-icon>
              <ArrowRight />
            </el-icon></el-button>
          <el-button type="primary" @click="RightIn" v-loading="loading2"><el-icon>
              <ArrowLeft />
            </el-icon></el-button>
        </el-col>
        <el-col :span="11">
          <div class="vue-element-page-table">
            <div class="page-table-operate">
              <el-row>
              <div class="page-table-title">
                <div class="page-table-title-left">
                  <span>已分配标签信息</span>                  
                </div>
                <div class="page-table-button">
                  <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
                  <el-button type="primary" @click="exportExcel" :disabled="state.button_state3" v-loading="state.button_loading3">导出</el-button>
                </div>
              </div>
            </el-row>
            </div>
            <el-table :height="tableHeight" border v-loading="loading" :data="state.MaterialPackingUsername" highlight-current-row
              row-key="id" style="width: 100%;min-height:50px" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="50" />
              <template v-for="(col, index) in column2" :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>
              <el-table-column prop="MATERIALQUANTITY2" label="本次发货数量" width="120">
                <template #default="scope">
                  <el-input v-model="scope.row.MATERIALQUANTITY2" min = 0  type =number style="width: 170px">
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="180">
                  <template #default="scope">
                    <el-button @click="UpdateQty(scope.row)" type="primary" size="small">修改数量</el-button>
                  </template>
                </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
    </div>

    <el-row class="page-search" justify="end" align="middle">
      <div class="block"  style="float: right">
        <el-form-item label="过账日期" prop="state.commitDate">
          <el-date-picker :clearable="true" :editable="true" v-model="state.commitDate" type="date" placeholder="选择过账时间" value-format="YYYY-MM-DD"/>
        </el-form-item>
      </div>
      <div class="page-search-btns">
        <!-- <el-button type="primary" @click="handleReserve" :disabled="state.button_state" v-loading="state.button_loading">备货</el-button> -->
        <el-button type="primary" @click="handleStockOut" :disabled="state.buttonOut_state" v-loading="state.buttonOut_loading">出库</el-button>
      </div>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "shipRequestReserve",
};
</script>

<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance, nextTick } from "vue";
import { ElForm, ElMessageBox, ElTable, ElMessage, ElNotification } from "element-plus";
import { getQueryList, BpelEvent } from '@/api/common';
import { useRouter } from "vue-router";
import { create } from "sortablejs";
import {areAllNotEmpty, FirstInFirstOut, IFTRUE} from '@/utils/CommonUtil'
import exportDataToExcel from "@/utils/export-excel";
import { AssignShipRequest, AssignShipRequestByCharge, CompleteShipRequest, DeAssignShipRequest, UpdateOutQty } from "@/api/StockOut";
import { Edit } from "@element-plus/icons-vue/dist/types";
import { bTableHeight } from "../../../composables/calcTableHeight";
import {localStorage} from "@/utils/storage";

const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(500);

const queryFormRef = ref(ElForm);
const operateFormRef = ref(ElForm);

const formDataRef = ref(ElForm);
const { proxy }: any = getCurrentInstance();

const router = useRouter();

const state: any = reactive({
  button_loading3 : false,
  button_loading2 : false,
  button_loading : false,
  buttonOut_loading : false,
  rsa: "",
  LShipRequestDetailName: '',
  LShipType: '',
  button_state: false,
  buttonOut_state: false,
  button_state2: false,
  STOCKSELECT: [],
  AleardyBooking: false,
  IFCompleteStockUp: false,//用于判断是否完成备货
  AB: '',
  commitDate:'',
  ABList: [{ value: 'A', label: 'A' }, { value: 'B', label: 'B' }],
  ENDING: '',
  INITILATION: '',
  ERPLocationList: [] as any,
  LocationList: [] as any,
  ChangeERPLocation: [],
  ChangeLocation: [],
  STOCKSELECTLIST: [] as any,
  queryParams: {
    queryId: "",
    version: "",
    params: {
      SITENAME: 'SDK',//localStorage.getItem("siteName"),
      DELIVERYTYPE: "", //移动类型
      SUPPLIERNAME: "",
      SHIPREQUESTNAME: "",
      MATERIALSPECNAME: '',
      AREANAME: '',
      MATERIALPACKING: '',
      DURABLENAME: '',
      CHARGE: '',
      ERPFACTORYNAME: '',
      ERPLOCATION: '',
      SDK_ID: '',
      PHASE: '',
      ERPFACTORY: '',
      SHIPREQUESTDETAILNAME: '',
      DESCRIPTION: '',
      CAREER_ASSISTANCE: '',
    },
  },
  RightqueryParams: {
    queryId: "",
    version: "",
    params: {
      SITENAME: 'SDK',//localStorage.getItem("siteName"),
      DELIVERYTYPE: "", //移动类型
      SUPPLIERNAME: "",
      SHIPREQUESTNAME: "",
      MATERIALSPECNAME: '',
      AREANAME: '',
      MATERIALPACKING: '',
      DURABLENAME: '',
      CHARGE: '',
      ERPFACTORYNAME: '',
      ERPLOCATION: '',
      SDK_ID: '',
      PHASE: '',
      ERPFACTORY: '',
      SHIPREQUESTDETAILNAME: '',
      CUSTOMERNO : ''
    },
  },
  ChangeParams: {
    header: {
      MESSAGENAME: '',
      EventUser: localStorage.get('userId') || '10975133',
      LANGUAGE: 'Chinese',
      Flag: 'LK'//立库标志
    },
    body: {
      SHIPREQUESTNAME: '',
      SHIPREQUESTDETAILNAME: '',
      SITENAME: 'SDK',
      MATERIALPACKINGNAME: '',
      objPara: [] as any,
    }
  },
  ReserveParams: {
    header: {
      MESSAGENAME: '',
      LANGUAGE: 'Chinese'
    },
    body: {
      SHIPREQUESTNAME: '',
      SITENAME: 'SDK',
      SHIPREQUESTTYPE: ''
    }
  },
  operateParams: {
    date: new Date(),
  },
  operateOptions: [] as any, // 操作类型
  actNoOptions: [] as any, // 抬头文本
  checkResultOptions: [
    {
      label: "OK",
      value: "OK",
    },
    {
      label: "NG",
      value: "NG",
    },
  ], // 质检结果
  loading: false,
  loading2: false,
  loadings: true,
  userList: [] as any,
  ShipList: [] as any,
  MaterialPackingList: [] as any,
  MaterialPackingUsername: [] as any,
  column1: [] as any,
  column: [] as any,
  column2: [] as any,
  column3: [] as any,
  column4: [] as any,
  LKLocalNameList: [] as any,//立库搬出库位
  LKPALLETNAMEList: [] as any,//成品批号/标签
  LKTRAYNAMEList: [] as any,//轴心RFID/托盘ID
  MaterialPackingList2 : [] as any,
});
const { LKTRAYNAMEList, LKPALLETNAMEList, LKLocalNameList, MaterialPackingUsername, MaterialPackingList, ShipList, rsa, queryParams, loading, loading2,buttonOut_loading,buttonOut_state, userList, column, column1, column2, operateParams, operateOptions, actNoOptions, checkResultOptions } = toRefs(state);
onMounted(() => {
  state.column = [
    { header: "工厂", field: "SITENAME", hide: true },
    { header: "行项", field: "SHIPREQUESTDETAILNAME", hide: true },
    { header: "发货单号", field: "SHIPREQUESTNAME", hide: false },
    { header: "发货组织", field: "ERPFACTORYDESC", hide: false },
    { header: "发货仓库", field: "ERPLOCATIONDES", hide: false },
    { header: "接收组织", field: "ERPRECEIVEFACTORYDESC", hide: false },
    { header: "接收仓库", field: "ERPRECEIVELOCATIONDES", hide: false },
    { header: "物料编号", field: "MATERIALSPECNAME", hide: false },
    { header: "品名", field: "DESC_CN", hide: false },
    // { header: "物料规格", field: "SDK_ID", hide: false },
    { header: "单位", field: "MATERIALUNIT", hide: false },
    { header: "发货类型", field: "SHIPREQUESTTYPE", hide: false },
    { header: "请求数量", field: "REQUESTQUANTITY", hide: false },
    { header: "绑定数量", field: "ASSIGNEDQUANTITY", hide: false },
    { header: "规格", field: "SDK_ID", hide: true },
    { header: "规格", field: "SPECNAME", hide: false },
    { header: "阶段", field: "PHASE", hide: false },
    { header: "业助", field: "CAREER_ASSISTANCE", hide: false },
    { header: "客户", field: "CUSTOMERNO", hide: false },
    { header: "批次", field: "CHARGE", hide: true },
    // { header: "物料组", field: "MATERIALGROUP", hide: false },
    
  ];
  state.column1 = [
    { header: "标签ID", field: "MATERIALPACKINGNAME", hide: false },
    { header: "批次", field: "CHARGE", hide: false },
    { header: "行项", field: "SHIPREQUESTDETAILNAME", hide: true },
    { header: "发货单号", field: "SHIPREQUESTNAME", hide: true },
    { header: "物料编号", field: "MATERIALSPECNAME", hide: false },
    { header: "品名", field: "DESC_CN", hide: false },
    { header: "物料规格", field: "SDK_ID", hide: true },
    { header: "SDK规格", field: "SPECNAME", hide: false },
    { header: "货位代码", field: "LOCATIONNAME", hide: false },
    { header: "货位名称", field: "LOCATIONNAMEDESC", hide: false },
    // { header: "批次", field: "MAKEDATE", hide: false },
    { header: "数量", field: "MATERIALQUANTITY", hide: false },
    { header: "单位", field: "MATERIALUNIT", hide: false },
    // { header: "移动类型", field: "CREATETIME", hide: false },
    { header: "入库日期", field: "RECEIVETIME", hide: false },
    { header: "生产日期", field: "MAKEDATE", hide: false },
    { header: "过期时间", field: "EXPIRINGDATE", hide: false },

  ];
  state.column2 = [
    { header: "标签ID", field: "MATERIALPACKINGNAME", hide: false },
    { header: "批次", field: "CHARGE", hide: false },
    { header: "行项", field: "SHIPREQUESTDETAILNAME", hide: false },
    { header: "物料编号", field: "MATERIALSPECNAME", hide: false },
    { header: "品名", field: "DESC_CN", hide: false },
    { header: "物料规格", field: "SDK_ID", hide: true },
    { header: "物料规格", field: "SPECNAME", hide: false },
    { header: "物料总数量", field: "MATERIALQUANTITY", hide: false },
    // { header: "发货数量", field: "MATERIALQUANTITY2", hide: false },
    { header: "位置", field: "LOCATIONNAME", hide: false },
    { header: "工厂", field: "SITENAME", hide: true },
    { header: "生成时间", field: "CREATETIME", hide: true },
    { header: "物料类型", field: "MATERIALTYPE", hide: false },
    { header: "物料编号", field: "MATERIALSPECNAME", hide: false },
    { header: "生产日期", field: "MAKEDATE", hide: false },
    { header: "过期时间", field: "EXPIRINGDATE", hide: false },
  ];

  var newDate = new Date();
  var year = newDate.getFullYear();
  var moth = newDate.getMonth() + 1;
  if(moth < 10)  moth = '0' + moth;
  var day = newDate.getDate();
  if(day < 10)  day = '0' + day;
  state.commitDate = year + '-' + moth + '-' + day
  updateTableHeight();
  window.addEventListener('resize', handleResize);
});

function JudgeMentERPLocation() {
 let LOCATION = state.ChangeLocation;
     if ( state.MaterialPackingList2 == null) {
       state.MaterialPackingList2 = state.MaterialPackingList
     }
  if (LOCATION != null) {
    console.log(state.MaterialPackingList.length)
    // let tem = state.MaterialPackingList.filter(item => item.LOCATIONNAME ==LOCATION)
    state.MaterialPackingList =  state.MaterialPackingList2.filter(item => item.LOCATIONNAME ==LOCATION)
    console.log(state.MaterialPackingList.length)
    // console.log(tem.length)
  }  else {

  }
}
function GetLocationListForSomeERPLocation(value: any) {
  if (!areAllNotEmpty(state.queryParams.params.ERPFACTORY)) {
    proxy.$ElMessage.warning('当前还未选择组织');
    state.ChangeERPLocation = []
    state.ERPLocationList = []
    return
  }
  if (!areAllNotEmpty(state.ChangeERPLocation)) {
    return
  }
  if (!value) {
    let ERPLOCATIONList = state.ChangeERPLocation;
    getQueryList({
      queryId: "GetLocationListForSomeERPLocation",
      version: "00001",
      params: {
        SITENAME: localStorage.get("siteName") || 'SDK',
        ERPLOCATION: ERPLOCATIONList.length ? ERPLOCATIONList.join(','): ""
      },
    })
            .then((res: any) => {
              state.LocationList = res.data;
              state.LocationList.unshift({
                STORAGENAME: ''
              });
            })
            .catch(() => { });
  }

}


function handleSelectionChange(selection: any) {
  console.log('调用了', selection)
  state.column3 = selection
}
function handleSelectionChange2(selection: any) {
  console.log('调用了', selection)
  state.column4 = selection
}
// 更新列
function updateList(col: any) {
  state.column = col;
}
function handleQuery() {

  let flag = true;
  if ((state.queryParams.params.SHIPREQUESTNAME != '') && (state.queryParams.params.SHIPREQUESTNAME != null) && (state.queryParams.params.SHIPREQUESTNAME != undefined)) {
   
    state.queryParams.queryId = 'GetShipRequestDetailList';
    state.queryParams.version = 'Z00052_NEW';
    getQueryList(state.queryParams).then((res: any) => {
      if (res.data.length > 0) {
        state.ShipList = res.data;
        if(state.ShipList.length>0)
        {
          handle(state.ShipList[0],null,null);
        }
      } else {
        // ElMessageBox.alert('搜索结果为空', '提醒框', {
        //   confirmButtonText: 'OK',
        // })
        state.queryParams.params.SHIPREQUESTNAME = ""
      }

    });
    
  } else {
    ElMessageBox.alert('搜索条件不能为空', '提醒框', {
      // if you want to disable its autofocus
      // autofocus: false,
      confirmButtonText: 'OK',
    })
  }

}
let tempRow: any = null;
let tempevent: any = null;
let tempcolumn: any = null;
function handle(row: any, event: any, column: any) {
  
  tempRow = row;
  tempevent = event;
  tempcolumn = column;
  state.queryParams.queryId = 'GetPackingRow';
  state.queryParams.version = 'ZWP007_NEW';
  state.queryParams.params.MATERIALSPECNAME = row.MATERIALSPECNAME;
  state.queryParams.params.SDK_ID = row.SDK_ID;
  state.queryParams.params.ERPLOCATION = row.ERPLOCATION;
  state.queryParams.params.ERPFACTORY = row.ERPFACTORY;
  state.queryParams.params.PHASE = row.PHASE;
  state.queryParams.params.SHIPREQUESTDETAILNAME = row.SHIPREQUESTDETAILNAME;
  state.queryParams.params.CAREER_ASSISTANCE = row.CAREER_ASSISTANCE;
  state.LShipRequestDetailName = row.SHIPREQUESTDETAILNAME
  state.LShipType = row.SHIPREQUESTTYPE
  getQueryList(state.queryParams).then((res: any) => {
    state.MaterialPackingList = res.data;
    state.MaterialPackingList2 = res.data;
  });

  state.RightqueryParams.queryId = 'GetPackingRow';
  state.RightqueryParams.version = 'Z00002_NEW';
  state.RightqueryParams.params.MATERIALSPECNAME = row.MATERIALSPECNAME;
  state.RightqueryParams.params.SHIPREQUESTNAME = row.SHIPREQUESTNAME;
  state.RightqueryParams.params.SDK_ID = row.SDK_ID;
  state.RightqueryParams.params.ERPLOCATION = row.ERPLOCATION;
  state.RightqueryParams.params.PHASE = row.PHASE;
  state.RightqueryParams.params.SHIPREQUESTDETAILNAME = row.SHIPREQUESTDETAILNAME;
  getQueryList(state.RightqueryParams).then((res: any) => {
    state.MaterialPackingUsername = res.data;
  });

  state.queryParams.queryId = 'GetLocationList';
  state.queryParams.version = 'ZWP007_NEW';
  state.queryParams.params.MATERIALSPECNAME = row.MATERIALSPECNAME;
  state.queryParams.params.SDK_ID = row.SDK_ID;
  state.queryParams.params.ERPLOCATION = row.ERPLOCATION;
  state.queryParams.params.ERPFACTORY = row.ERPFACTORY;
  state.queryParams.params.PHASE = row.PHASE;
  state.queryParams.params.SHIPREQUESTDETAILNAME = row.SHIPREQUESTDETAILNAME;
  state.queryParams.params.CAREER_ASSISTANCE = row.CAREER_ASSISTANCE;
  state.LShipRequestDetailName = row.SHIPREQUESTDETAILNAME
  state.LShipType = row.SHIPREQUESTTYPE
  getQueryList(state.queryParams).then((res: any) => {
    state.LocationList = res.data;
  });
}

//重写拣配功能。zd.2024.9.10
async function LeftIn() {


  if (state.MaterialPackingList.length > 0 && state.column4.length > 0) 
  {
    let boxId ='';
    for (const item of state.column4) {
      boxId +=(item.MATERIALPACKINGNAME+';');
    }
    
      const params = {
      materialPackingName: boxId,
      user: localStorage.get('userId'),
      shipRequestName: state.queryParams.params.SHIPREQUESTNAME,
      materialSpecName: state.queryParams.params.MATERIALSPECNAME
    };
    state.loading = true;
    AssignShipRequest(params).then((res: any) => {
      if (res.success) {
       
        handleQuery();
        state.loading = false;
      } 
      else {
        
        ElMessageBox.alert('操作失败：' + res.message, '提醒框', {
          confirmButtonText: 'OK',
        })
        state.loading = false;
      }
    }).catch((err: any) => {
      
      ElMessageBox.alert('操作失败:' + err.response.data.message, '提醒框', {
        confirmButtonText: 'OK',
      })
      state.loading = false;
    })
  }
	else {
    ElMessageBox.alert('提示框', '勾选的数据不能为空！', {
      // if you want to disable its autofocus
      // autofocus: false,
      confirmButtonText: 'OK',
    })
  }
  state.loading = false;
  // if (state.MaterialPackingList.length > 0 && state.column4.length > 0) {

  //   state.loading = true;
  //   state.ChangeParams.header.MESSAGENAME = 'AssignShipRequestToBoxForSDK';
  //   state.ChangeParams.body.SHIPREQUESTDETAILNAME = state.queryParams.params.SHIPREQUESTDETAILNAME
  //   // state.ChangeParams.body.SHIPREQUESTDETAILNAME = "0001"
  //   state.ChangeParams.body.SHIPREQUESTNAME = state.queryParams.params.SHIPREQUESTNAME
  //   state.ChangeParams.body.MATERIALQUANTITY = 0
  //   // 遍历 state.column4，将 MATERIALPACKINGNAME 添加到 packingNames 数组中
  //   state.ChangeParams.body.objPara = []
  //   for (const item of state.column4) {
  //     state.ChangeParams.body.objPara.push(item.MATERIALPACKINGNAME);
  //     state.ChangeParams.body.MATERIALQUANTITY += item.MATERIALQUANTITY;
  //   }
  //   if (state.LShipType == '4C') {
  //     let AllQty = 0;
  //     for (let i = 0; i < state.ShipList.length; i++) {
  //       if (state.ShipList[i].SHIPREQUESTDETAILNAME == state.LShipRequestDetailName) {
  //         AllQty = state.ShipList[i].REQUESTQUANTITY - state.ShipList[i].ASSIGNEDQUANTITY
  //         break
  //       }

  //     }
  //     let areadryQty = 0
  //     for (let i = 0; i < state.MaterialPackingUsername.length; i++) {
  //       areadryQty += parseFloat(state.MaterialPackingUsername[i].MATERIALQUANTITY)
  //     }
  //     console.log(AllQty, state.ChangeParams.body.MATERIALQUANTITY, areadryQty)
  //     if (AllQty < state.ChangeParams.body.MATERIALQUANTITY ) {
  //       console.log(AllQty  + "" + (state.ChangeParams.body.MATERIALQUANTITY + areadryQty))
  //       ElMessageBox.alert("该明细所需数量为" + AllQty + ",已经绑定了" + areadryQty + "现在的数量" + state.ChangeParams.body.MATERIALQUANTITY + "大于所需数量", "", {
  //         confirmButtonText: 'OK',
  //       })
  //       state.loading = false;
  //       return
  //     }
  //   }

  //   // 如果 packingNames 数组不为空，则将其转换为一个由“、”分隔的字符串
  //   if (state.ChangeParams.body.objPara.length > 0) {
  //     state.ChangeParams.body.MATERIALPACKINGNAME = state.ChangeParams.body.objPara.join(";");
  //   } else {
  //     // 如果 packingNames 为空，可以根据需要设置初始值，或者保持为空字符串
  //     state.ChangeParams.body.MATERIALPACKINGNAME = "";
  //   }
  //   await BpelEvent(state.ChangeParams).then((res: any) => {
  //     if (IFTRUE(res)) {
  //       handle(tempRow, tempevent, tempcolumn);
  //       handleQuery();
  //       state.loading = false;
  //     } else {
  //       ElMessageBox.alert(res.data.RETURNCODE + '->' + res.data.RETURNMESSAGE, '', {
  //         confirmButtonText: 'OK',
  //       })
  //       state.loading2 = false;
  //     }


  //   })
  //     .catch(() => {
  //       state.loading = false;
  //     });

  // } else {
  //   ElMessageBox.alert('提示框', '备货数据不能为空！', {
  //     // if you want to disable its autofocus
  //     // autofocus: false,
  //     confirmButtonText: 'OK',
  //   })
  // }

  // state.loading = false;

}

function clearCharge() {

  state.queryParams.params.CHARGE='';
}

async function chargeReserve() {

  
if (state.MaterialPackingList.length > 0 && state.queryParams.params.CHARGE!='' && state.queryParams.params.CHARGE != null && state.queryParams.params.CHARGE != undefined) 
{
  // let boxId ='';
  // for (const item of state.column4) {
  //   boxId +=(item.MATERIALPACKINGNAME+';');
  // }
  let boxId =state.queryParams.params.CHARGE.replace(/\n/g, ';');
    const params = {
    materialPackingName: boxId,
    user: localStorage.get('userId'),
    shipRequestName: state.queryParams.params.SHIPREQUESTNAME,
    materialSpecName: state.queryParams.params.MATERIALSPECNAME
  };
  state.loading = true;
  AssignShipRequestByCharge(params).then((res: any) => {
    if (res.success) {
     
      handleQuery();
      state.loading = false;
    } 
    else {
      
      ElMessageBox.alert('操作失败：' + res.message, '提醒框', {
        confirmButtonText: 'OK',
      })
      state.loading = false;
    }
  }).catch((err: any) => {
    
    ElMessageBox.alert('操作失败:' + err.response.data.message, '提醒框', {
      confirmButtonText: 'OK',
    })
    state.loading = false;
  })
}
else {
  ElMessageBox.alert('提示框', '指定的批次不能为空！', {
    // if you want to disable its autofocus
    // autofocus: false,
    confirmButtonText: 'OK',
  })
}
state.loading = false;


}

function UpdateQty(value : any){
  
  const params = {
    materialPackingName: value.MATERIALPACKINGNAME,
    materialQuantity2: value.MATERIALQUANTITY2,
    user: localStorage.get('userId'),
    shipRequestName: state.queryParams.params.SHIPREQUESTNAME,
    materialSpecName: state.queryParams.params.MATERIALSPECNAME
  };
  state.loading = true;
  UpdateOutQty(params).then((res: any) => {
    if (res.success) {
     
      handleQuery();
      state.loading = false;
    } 
    else {
      
      ElMessageBox.alert('操作失败：' + res.message, '提醒框', {
        confirmButtonText: 'OK',
      })
      state.loading = false;
    }
  }).catch((err: any) => {
    
    ElMessageBox.alert('操作失败:' + err.response.data.message, '提醒框', {
      confirmButtonText: 'OK',
    })
    state.loading = false;
  })
}

function selectable(row: any, index: any) {
  if (row.GROUPNO == '1')
    return true;
  else {
    return false
  }
}
function exportExcel() {
  state.button_loading3 = true;
  state.button_state3 = true;
  if ((state.queryParams.params.SHIPREQUESTNAME != '') && (state.queryParams.params.SHIPREQUESTNAME != null) && (state.queryParams.params.SHIPREQUESTNAME != undefined)) {
    getQueryList({
      queryId: "GetPackingRow",
      version: "dc001",
      params: {
        SHIPREQUESTNAME: state.queryParams.params.SHIPREQUESTNAME
      }
    }).then((res: any) => {
      if (res.data.length > 0) {
        exportDataToExcel(res.data, '备货导出' + state.queryParams.params.SHIPREQUESTNAME)
        state.button_loading3 = false;
        state.button_state3 = false;
      } else {
        proxy.$ElMessage.warning('当前查询没有数据可以导出');
        state.button_loading3 = false;
        state.button_state3 = false;
      }
    });
  } else {
    ElMessageBox.alert('导出条件不能为空', '提醒框', {
      confirmButtonText: 'OK',
    })
    state.button_loading3 = false;
    state.button_state3 = false;
  }

}

async function RightIn() {

  if (state.column3.length > 0) 
  {
    let boxId ='';
    for (const item of state.column3) {
      boxId +=(item.MATERIALPACKINGNAME+';');
    }
    
      const params = {
      materialPackingName: boxId,
      user: localStorage.get('userId'),
      shipRequestName: state.queryParams.params.SHIPREQUESTNAME,
      materialSpecName: state.queryParams.params.MATERIALSPECNAME
    };
    state.loading = true;
    DeAssignShipRequest(params).then((res: any) => {
      if (res.success) {
       
        handleQuery();
        state.loading = false;
      } 
      else {
        
        ElMessageBox.alert('操作失败：' + res.message, '提醒框', {
          confirmButtonText: 'OK',
        })
        state.loading = false;
      }
    }).catch((err: any) => {
      
      ElMessageBox.alert('操作失败:' + err.response.data.message, '提醒框', {
        confirmButtonText: 'OK',
      })
      state.loading = false;
    })
  }
	else {
    ElMessageBox.alert('提示框', '勾选的数据不能为空！', {
      // if you want to disable its autofocus
      // autofocus: false,
      confirmButtonText: 'OK',
    })
  }
  state.loading = false;
  // if (state.column3.length > 0) {
  //   state.loading2 = true;
  //   state.ChangeParams.header.MESSAGENAME = 'DeassignShipRequestFromBox';
  //   state.ChangeParams.body.SHIPREQUESTDETAILNAME = state.RightqueryParams.params.SHIPREQUESTDETAILNAME
  //   state.ChangeParams.body.SHIPREQUESTNAME = state.RightqueryParams.params.SHIPREQUESTNAME
  //   state.ChangeParams.body.MATERIALQUANTITY = 0
  //   // 遍历 state.column4，将 MATERIALPACKINGNAME 添加到 packingNames 数组中
  //   state.ChangeParams.body.objPara = []
  //   for (const item of state.column3) {
  //     state.ChangeParams.body.objPara.push(item.MATERIALPACKINGNAME);
  //     state.ChangeParams.body.MATERIALQUANTITY += item.MATERIALQUANTITY;
  //   }

  //   // 如果 packingNames 数组不为空，则将其转换为一个由“、”分隔的字符串
  //   if (state.ChangeParams.body.objPara.length > 0) {
  //     state.ChangeParams.body.MATERIALPACKINGNAME = state.ChangeParams.body.objPara.join(";");
  //   } else {
  //     // 如果 packingNames 为空，可以根据需要设置初始值，或者保持为空字符串
  //     state.ChangeParams.body.MATERIALPACKINGNAME = "";
  //   }
  //   await BpelEvent(state.ChangeParams).then((res: any) => {
  //     if (IFTRUE(res)) {
  //       handle(tempRow, tempevent, tempcolumn);
  //       handleQuery();
  //       state.loading2 = false;
  //     } else {
  //       ElMessageBox.alert(res.data.RETURNCODE + '->' + res.data.RETURNMESSAGE, '', {
  //         confirmButtonText: 'OK',
  //       })
  //       state.loading2 = false;
  //     }

  //   })
  //     .catch(() => {
  //       state.loading2 = false;
  //     });
  // } else {
  //   ElMessageBox.alert('提示框', '备货数据不能为空！', {
  //     // if you want to disable its autofocus
  //     // autofocus: false,
  //     confirmButtonText: 'OK',
  //   })
  // }

}

function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}


function handleReserve() {
  state.button_state = true;
  state.button_loading = true;
  if (state.LShipType == '4C') {
    for (let i = 0; i < state.ShipList.length; i++) {
      if (state.ShipList[i].REQUESTQUANTITY != state.ShipList[i].ASSIGNEDQUANTITY) {
        ElMessageBox.alert("该单据下明细" + state.LShipRequestDetailName + " 所需数量为" + state.ShipList[i].REQUESTQUANTITY + "绑定数量为" + state.ShipList[i].ASSIGNEDQUANTITY + ".不符合要求", "", {
          confirmButtonText: 'OK',
        })
        state.button_state = false;
        state.button_loading = false;
        return
      }
      state.button_state = false;
      state.button_loading = false;
    }
  }
  if (state.MaterialPackingUsername.length > 0) {
    state.loading = true
    state.button_state = true
    state.button_loading = true;
    state.ReserveParams.header.MESSAGENAME = 'ReserveShipRequest'
    state.ReserveParams.header.EventUser = localStorage.get('userId')
    state.ReserveParams.body.SHIPREQUESTNAME = state.queryParams.params.SHIPREQUESTNAME
    state.ReserveParams.body.SITENAME = localStorage.get("siteName") == null ? "SDK" : localStorage.get("siteName");
    BpelEvent(state.ReserveParams).then((res: any) => {
      if (IFTRUE(res)) {
        ElMessageBox.alert("备货成功", '', {
          confirmButtonText: 'OK',
        })
        handle(tempRow, tempevent, tempcolumn);
        handleQuery()
        state.IFCompleteStockUp = true
        state.loading = false
        state.button_state = false;
        state.button_loading = false;
      } else {
        ElMessageBox.alert(res.data.RETURNCODE + '->' + res.data.RETURNMESSAGE, '', {
          confirmButtonText: 'OK',
        })
        state.button_state = false;
        state.button_loading = false;
      }

    })
      .catch(() => { });
    state.loading = false;
    state.button_state = false;
    state.button_loading = false;
  } else {
    ElMessageBox.alert("请先选择需要备货的标签", '提示框', {
      confirmButtonText: 'OK',
    })
  }
  state.button_state = false;
  state.button_loading = false;
}

function handleStockOut() {

  if (state.queryParams.params.SHIPREQUESTNAME!='' && state.queryParams.params.SHIPREQUESTNAME!=null && state.queryParams.params.SHIPREQUESTNAME != undefined) 
  {
    
      const params = {
      //materialPackingName: boxId,
      user: localStorage.get('userId'),
      shipRequestName: state.queryParams.params.SHIPREQUESTNAME,
      commitDate: state.commitDate,
      //materialSpecName: state.queryParams.params.MATERIALSPECNAME
    };
    //state.loading = true;
    state.buttonOut_loading = true;
    //state.buttonOut_state = true;
    
    CompleteShipRequest(params).then((res: any) => {
      
      if (res.success) {
       
        handleQuery();
        //state.loading = false;
        state.buttonOut_loading = false;
        //state.buttonOut_state = false;
        
      } 
      else {
        
        ElMessageBox.alert('操作失败：' + res.message, '提醒框', {
          confirmButtonText: 'OK',
        })
        //state.loading = false;
        //state.buttonOut_state = false;
        state.buttonOut_loading = false;
      }
    }).catch((err: any) => {
      
      ElMessageBox.alert('操作失败:' + err.response.data.message, '提醒框', {
        confirmButtonText: 'OK',
      })
      //state.loading = false;
      //state.buttonOut_state = false;
      state.buttonOut_loading = false;
    })
  }
	else {
    ElMessageBox.alert('提示框', '请输入发货单号', {
      // if you want to disable its autofocus
      // autofocus: false,
      confirmButtonText: 'OK',
    })

    //state.loading = false;
  //state.buttonOut_state = false;
  state.buttonOut_loading = false;
  }
}


</script>

<style scoped lang="scss">
.operate-bottom {
  width: 80px;
  height: 28px;
  float: right;
  margin-top: 20px;
}

.el-form-item__content {
  display: flex;
  align-items: center;
  /* 垂直居中 */
  justify-content: center;
  /* 水平居中，如果需要的话 */
}
</style>
