<!--
  功能：功能描述  移库
  作者：Libra
  邮箱：mingxichen@163.com
  时间：2024年04月11日 11:33:18
  版本：v1.0
  修改记录：
  修改内容：
  修改人员：
  修改时间：/stocked/relocation
-->
<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" clearable placeholder="请输入移库单号" />
            </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">
      <div class="page-table-operate">
        <div class="page-table-title">
          <div class="page-table-title-left">
            <span>发货单据信息</span>
          </div>
        </div>
      </div>
      <el-table border style="min-height: 50px;" v-loading="loading" :data="state.MoveLibraryList" highlight-current-row row-key="id"
         @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>
      <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">
      <el-row>
        <el-col :span="11">
          <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>
            <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="handleSelectionChange">
              <el-table-column type="selection" width="40" />
              <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="loading3"><el-icon>
              <ArrowRight />
            </el-icon></el-button>
          <el-button type="primary" @click="RightIn" v-loading="state.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">
              <div class="page-table-title">
                <div class="page-table-title-left">
                  <span>已分配标签信息</span>
                </div>
              </div>
            </div>
            <el-table :height="tableHeight" border v-loading="state.loading" :data="state.MaterialPackingUsername" highlight-current-row
              row-key="id" style="width: 100%;min-height: 50px;" @selection-change="handleSelectionChange2">
              <el-table-column type="selection" width="40" />
              <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>
          </div>
        </el-col>
      </el-row>
    </div>

    <el-row class="page-search" justify="end" align="middle">
      <el-col :span="20">
        <el-form-item label="目的货位" prop="portFormRefData.SEARCHTYPE">
          <el-cascader @visible-change="handleOuterClick" v-model="state.StorageSelect"
            :options="state.StorageSelectList"
            :props="{ checkStrictly: true, label: 'ERPLOCATION', value: 'ERPLOCATION', children: 'children' }" />
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <div class="page-search-btns">
        <el-button type="primary" @click="handleReserve" :disabled="state.Button_state" v-loading="state.button_loading">确定</el-button>
      </div>
      </el-col>
      
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: "MoveLibrary",
};
</script>

<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance, nextTick } from "vue";
import { ElForm, ElMessageBox, ElTable } from "element-plus";
import { getQueryList, getQueryPageList, BpelEvent } from "@/api/common";
import { useRouter } from "vue-router";
import { waitForDebugger } from "inspector";
import { FirstInFirstOut, IFTRUE } from "@/utils/CommonUtil"
import { bTableHeight } from "../../../composables/calcTableHeight";

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

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

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

const router = useRouter();

const state = reactive({
  button_loading :false,
  rsa: "",
  Button_state: false,
  total: 0,
  total2: 0,
  BoxList: [] as any,
  firstLocation: '',
  MaterialPackingList: [] as any,
  MaterialPackingUsername: [] as any,
  StorageSelect: [] as any,
  StorageSelectList: [] as any,
  queryParams: {
    queryId: "",
    version: "",
    params: {
      SITENAME: 'SDK',
      AREANAME: '',
      SHIPREQUESTNAME: "",
      RECEIVEACTNO: "",
      DELIVERYTYPE: "", //移动类型
      SUPPLIERNAME: "",
      //下面是handle查询参数
      MATERIALSPECNAME: "",
      ERPLOCATION: '',
      ERPFACTORY: '',
      SHIPREQUESTDETAILNAME: '',
    }, pageNum: 1,
    pageSize: 12
  },
  RightqueryParams: {
    queryId: "",
    version: "",
    params: {
      SITENAME: 'SDK',//localStorage.getItem("siteName"),
      DELIVERYTYPE: "", //移动类型
      SUPPLIERNAME: "",
      SHIPREQUESTNAME: "",
      MATERIALSPECNAME: '',
      AREANAME: '',
      MATERIALPACKING: '',
      DURABLENAME: '',
      CHARGE: '',
      ERPFACTORYNAME: '',
      ERPLOCATION: '',
      SDK_ID: '',
      PHASE: '',
      ERPFACTORY: '',
      SHIPREQUESTDETAILNAME: '',
    },
  },
  ChangeParams: {
    header: {
      MESSAGENAME: '',
      LANGUAGE: 'Chinese',
      Flag: 'LK',//立库标志
      EVENTUSER: ''
    },
    body: {
      SHIPREQUESTNAME: '',
      SHIPREQUESTDETAILNAME: '',
      SITENAME: 'SDK',
      MATERIALPACKINGNAME: '',
      MATERIALQUANTITY: 0,
      AREANAME: '',
      LOCATIONNAME: '',
      BOXList: [] as any,
      objPara: [] as any,
      ERPLOCATION: '',
      INERPLOCATION: '',
    }
  },
  operateParams: {
    date: new Date(),
  },
  operateOptions: [] as any, // 操作类型
  actNoOptions: [] as any, // 抬头文本
  checkResultOptions: [
    {
      label: "OK",
      value: "OK",
    },
    {
      label: "NG",
      value: "NG",
    },
  ], // 质检结果
  loading: false,
  loading2: false,
  loading3: false, //左箭头loading flag
  column1: [] as any,
  column: [] as any,
  column2: [] as any,
  MoveLibraryList: [] as any,//column对应的数据
  waitAssignmentList: [] as any,//column1对应的数据
  AssignmentList: [] as any,//column2对应的数据
  LeftSelection: [],//左边选择的未分配数据
  RightSelection: [],//右边选择的分配数据
  column3: [] as any,
  column4: [] as any,
  column5: [] as any,

});
const { rsa, queryParams, loading3, loading, column, column1, column2, operateParams, operateOptions, actNoOptions, checkResultOptions } = toRefs(state);

onMounted(() => {
  state.column = [
    { header: "工厂", field: "SITENAME", hide: false },
    { header: "转库单号", field: "SHIPREQUESTNAME", hide: false },
    { header: "行项", field: "SHIPREQUESTDETAILNAME", hide: false },
    { header: "库存组织", field: "ERPFACTORYNAME", hide: false },
    { header: "单据类型", field: "SHIPREQUESTTYPE", hide: false },
    { header: "转入仓库", field: "INERPLOCATION", hide: false },
    { header: "数量", field: "REQUESTQUANTITY", hide: false },
    { header: "单位", field: "UNIT", hide: false },
    { header: "物料编码", field: "MATERIALSPECNAME", hide: false },
    { header: "物料名(中文)", field: "DESC_EN", hide: false },
    { header: "阶段", field: "PHASE", hide: false },
    { header: "SDK规格", field: "SPECNAME", hide: false },
    { header: "仓库", field: "ERPLOCATION", hide: false },
  ];
  state.column1 = [
    { header: "工厂", field: "SITENAME", hide: false },
    { header: "标签编号", field: "MATERIALPACKINGNAME", hide: false },
    { header: "物料编号", field: "MATERIALSPECNAME", hide: false },
    { header: "物料名(中文)", field: "DESC_EN", hide: false },
    { header: "数量", field: "REQUESTQUANTITY", hide: false },
    { header: "单位", field: "UNIT", hide: false },
    { header: "位置", field: "STORAGENAME", hide: false },
    { header: "库区", field: "AREANAME", hide: false },
    { header: "仓库", field: "ERPFACTORYNAME", hide: false },
  ];
  state.column2 = [
    { header: "工厂", field: "SITENAME", hide: false },
    { header: "标签编号", field: "MATERIALPACKINGNAME", hide: false },
    { header: "物料编号", field: "MATERIALSPECNAME", hide: false },
    { header: "物料名(中文)", field: "DESC_EN", hide: false },
    { header: "数量", field: "REQUESTQUANTITY", hide: false },
    { header: "单位", field: "UNIT", hide: false },
    { header: "位置", field: "STORAGENAME", hide: false },
    { header: "库区", field: "AREANAME", hide: false },
    { header: "仓库", field: "ERPFACTORYNAME", hide: false },
  ];

  updateTableHeight();
  window.addEventListener('resize', handleResize);
});
// 更新列
function updateList(col: any) {
  state.column = col;
}
async function handleQuery() {
  if ((state.queryParams.params.SHIPREQUESTNAME != '') && (state.queryParams.params.SHIPREQUESTNAME != null) && state.queryParams.params.SHIPREQUESTNAME != undefined) {
    state.queryParams.queryId = 'GetMessageForMove';
    state.queryParams.version = '00001';
    state.MoveLibraryList = []
    await getQueryPageList(state.queryParams).then((res: any) => {
      console.log(res)
      console.log(res.data)
      console.log(res.data.list)
      if(res.data.list.length==0){
        ElMessageBox.alert('查无数据！', '提醒框', {
          confirmButtonText: 'OK',
        })
      } else {
        state.MoveLibraryList = res.data.list;
        state.total = res.data.total;
      }
    }).catch((error: any) => {
      ElMessageBox.alert('系统内部错误，请找IT！', '提醒框', {
        confirmButtonText: 'OK',
      })
    })
  } else {
    ElMessageBox.alert('查询条件不为空！', '提醒框', {
      // if you want to disable its autofocus
      // autofocus: false,
      confirmButtonText: 'OK',
    })
  }

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

async function handleReserve() {
  state.loading = true
  state.button_loading = true
  state.BoxList = []
  state.Button_state = true
  if (state.column3.length > 0 || state.column4.length > 0) {
    state.ChangeParams.header.EVENTUSER = localStorage.getItem('userId') || '10975133'
    state.ChangeParams.header.MESSAGENAME = 'ModifyERPLocation'
    state.ChangeParams.body.AREANAME = state.StorageSelect[0];
    state.ChangeParams.body.LOCATIONNAME = state.StorageSelect[1];
    for (let item = 0; item < state.column3.length; item++) {
      state.BoxList.push({ "BoxL": state.column3[item].MATERIALPACKINGNAME })
    }
    state.ChangeParams.body.BOXList = state.BoxList
    await BpelEvent(state.ChangeParams).then((res: any) => {
      state.Button_state = false
      state.button_loading = false
    }).catch((error: any) => {
      ElMessageBox.alert(error, '提醒框', {
        confirmButtonText: 'OK',
      })
      state.Button_state = false
      state.button_loading = false
    })
  } else {
    ElMessageBox.alert('请按照规范操作', '提醒框', {
      confirmButtonText: 'OK',
    })
    state.Button_state = false
    state.button_loading = false
  }
  state.loading = false
  state.Button_state = false
  state.button_loading = false
}

function handleSelectionChange(selection: any) {
  state.column4 = selection
}
function handleSelectionChange2(selection: any) {
  state.column3 = selection
}





async function LeftIn() {
  if (state.MaterialPackingList.length > 0 && state.column4.length > 0) {
    if (FirstInFirstOut(state.MaterialPackingList, state.column4)) {
      state.loading3 = 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;
      }
      // 如果 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',
          })
        }

      })
        .catch(() => {
          state.loading3 = false;
        });
    } else {
      ElMessageBox.alert('不符合先进先出', '提示框', {
        // if you want to disable its autofocus
        // autofocus: false,
        confirmButtonText: 'OK',
      })

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

  state.loading3 = false;

}

async function RightIn() {
  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) => {
      handle(tempRow, tempevent, tempcolumn);
      handleQuery();
      state.loading2 = false;
    })
      .catch(() => {
        state.loading2 = false;
      });
  } 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;
async function handle(row: any, event: any, column: any) {
  tempRow = row;
  tempevent = event;
  tempcolumn = column;
  state.queryParams.queryId = 'GetPackingRow';
  state.queryParams.version = 'WP008';
  state.queryParams.params.MATERIALSPECNAME = row.MATERIALSPECNAME;
  state.queryParams.params.ERPLOCATION = row.ERPLOCATION;
  state.queryParams.params.ERPFACTORY = row.ERPFACTORYNAME;
  state.queryParams.params.SHIPREQUESTDETAILNAME = row.SHIPREQUESTDETAILNAME
  state.ChangeParams.body.SHIPREQUESTNAME = row.SHIPREQUESTNAME
  state.ChangeParams.body.SHIPREQUESTDETAILNAME = row.SHIPREQUESTDETAILNAME
  state.ChangeParams.body.ERPLOCATION = row.ERPLOCATION
  state.ChangeParams.body.INERPLOCATION = row.INERPLOCATION


  if(await getQueryList(state.queryParams).then((res: any) => {
    if(res.data.length == 0 ){
      ElMessageBox.alert('查无数据', '提示框！', {
        confirmButtonText: 'OK',
      })
      return true;
    } else {
      state.MaterialPackingList = res.data;
      return false;
    }
  })){
    return
  }


  state.RightqueryParams.queryId = 'GetPackingRow';
  state.RightqueryParams.version = '00002';
  state.RightqueryParams.params.MATERIALSPECNAME = row.MATERIALSPECNAME;
  state.RightqueryParams.params.SHIPREQUESTNAME = row.SHIPREQUESTNAME;
  state.RightqueryParams.params.SHIPREQUESTDETAILNAME = row.SHIPREQUESTDETAILNAME;
  await getQueryList(state.RightqueryParams).then((res: any) => {
    if(res.data.length == 0 ){
      ElMessageBox.alert('查无数据', '提示框！', {
        confirmButtonText: 'OK',
      })
      return
    } else {
      state.MaterialPackingUsername = res.data;
    }
  });
  //查询库位需要
  state.firstLocation = row.ERPLOCATION
}
function handleOuterClick() {
  StorageList(state.firstLocation)
}

async function StorageList(firstLocation: any) {
  try {
    try {
      state.queryParams.queryId = 'Get2stAreaName';
      state.queryParams.version = '00002';
      state.queryParams.params.ERPLOCATION = firstLocation;
      const res = await getQueryList(state.queryParams);
      state.StorageSelectList = res.data;
      if (state.StorageSelectList.length == 0) {
        proxy.$ElMessage.info('目的货位为空!');
        return;
      }
      for (let i = 0; i < state.StorageSelectList.length; i++) {
        state.queryParams.queryId = 'Get3stStorageName';
        state.queryParams.version = '00002';
        state.queryParams.params.AREANAME = state.StorageSelectList[i].ERPLOCATION;
        const childrenRes = await getQueryList(state.queryParams);
        state.StorageSelectList[i].children = childrenRes.data;
      }
    } catch (error) {
      console.error(`Error fetching children for item `, error);
      // 处理错误，可能设置一些默认值或标记该项为出错  
    }

    console.log("StorageSelectList", state.StorageSelectList);
  } catch (error) {
    console.error('Error fetching initial data', error);
    // 处理错误，可能重置 state 或进行其他恢复操作  
  }
}

</script>

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