<!--
  功能：采购退
  作者：李文虎
  邮箱：1439135148@qq.com
  时间：2024年04月25日 18:10:29
  版本：v1.0
  修改记录：
  修改内容：loading
  修改人员：
  修改时间：
-->
<template>
  <div class="vue-element-page-wrap" ref="tableContainer">
    <el-row class="page-search" justify="space-between" align="bottom">
      <el-form @submit.prevent 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.RECEIVEREQUESTNAME">
              <el-Input v-model="queryParams.params.RECEIVEREQUESTNAME" 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">
      <div class="page-table-operate">
        <div class="page-table-title">
          <div class="page-table-title-left">
            <span>采购红信息</span>
          </div>
        </div>
      </div>
      <el-table border v-loading="loading" :data="ShipList" highlight-current-row row-key="id" style="width: 100%"
        @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">
            <div class="page-table-operate">
              <div class="page-table-title">
                <div class="page-table-title-left">
                  <span>未分配标签信息</span>
                </div>
              </div>
            </div>
            <!-- v-loading="loading" -->
            <el-table :height="tableHeight" border :data="state.MaterialPackingList" highlight-current-row row-key="id"
            style="width: 100%;min-height:200px" @selection-change="handleSelectionChange2">
              <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 :disabled="loading" type="primary" @click="LeftIn"><el-icon>
              <ArrowRight />
            </el-icon></el-button>
            <!-- v-loading="loading2" -->
          <el-button :disabled="loading2" type="primary" @click="RightIn"><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>
            <!-- v-loading="loading" -->
            <el-table :height="tableHeight" border :data="state.MaterialPackingUsername" 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 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">
      <div class="page-search-btns">
        <el-button type="primary" @click="handleStockOut" :disabled="state.button_state" v-loading="state.button_loadings">出库</el-button>
      </div>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "PurReturn",
};
</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 { FirstInFirstOut, IFTRUE } from '@/utils/CommonUtil'
import { bTableHeight } from "../../../composables/calcTableHeight";

const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(440);
const queryFormRef = ref(ElForm);
const operateFormRef = ref(ElForm);

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

const router = useRouter();

const state: any = reactive({
  button_loadings : false,
  rsa: "",
  button_state: false,
  STOCKSELECT: [],
  AleardyBooking: false,
  AB: '',
  ABList: [{ value: 'A', label: 'A' }, { value: 'B', label: 'B' }],
  ENDING: '',
  INITILATION: '',
  STOCKSELECTLIST: [] as any,
  queryParams: {
    queryId: "",
    version: "",
    params: {
      SITENAME: 'SDK',//localStorage.getItem("siteName"),
      DELIVERYTYPE: "", //移动类型
      SUPPLIERNAME: "",
      RECEIVEREQUESTNAME: "",
      MATERIALSPECNAME: '',
      AREANAME: '',
      MATERIALPACKING: '',
      DURABLENAME: '',
      CHARGE: '',
      ERPFACTORYNAME: '',
      ERPLOCATION: '',
      SDK_ID: '',
      PHASE: '',
      ERPFACTORY: '',
      RECEIVEREQUESTDETAILNAME: '',
      DESCRIPTION: '',
    },
  },
  RightqueryParams: {
    queryId: "",
    version: "",
    params: {
      SITENAME: 'SDK',//localStorage.getItem("siteName"),
      DELIVERYTYPE: "", //移动类型
      SUPPLIERNAME: "",
      RECEIVEREQUESTNAME: "",
      MATERIALSPECNAME: '',
      AREANAME: '',
      MATERIALPACKING: '',
      DURABLENAME: '',
      CHARGE: '',
      ERPFACTORYNAME: '',
      ERPLOCATION: '',
      SDK_ID: '',
      PHASE: '',
      ERPFACTORY: '',
      RECEIVEREQUESTDETAILNAME: '',
    },
  },
  ChangeParams: {
    header: {
      MESSAGENAME: '',
      LANGUAGE: 'Chinese',
      Flag: 'LK'//立库标志
    },
    body: {
      RECEIVEREQUESTNAME: '',
      RECEIVEREQUESTDETAILNAME: '',
      SITENAME: 'SDK',
      MATERIALPACKINGNAME: '',
      objPara: [] as any,

    }
  },
  ReserveParams: {
    header: {
      MESSAGENAME: '',
      LANGUAGE: 'Chinese',
      EventUser: localStorage.getItem('userId') || '10975133'
    },
    body: {
      RECEIVEREQUESTNAME: '',
      SITENAME: 'SDK',
      REASONCODE: '',
      REASONCODETYPE: '',
      RECEIVEREQUESTTYPE: '45',
      RECEIVEACTNO: '',
    }
  },
  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
});
const { LKTRAYNAMEList, LKPALLETNAMEList, LKLocalNameList, MaterialPackingUsername, MaterialPackingList, ShipList, rsa, queryParams, loading, loading2, userList, column, column1, column2, operateParams, operateOptions, actNoOptions, checkResultOptions } = toRefs(state);
onMounted(() => {
  state.column = [
    { header: "工厂", field: "SITENAME", hide: false },
    { header: "行项", field: "RECEIVEREQUESTDETAILNAME", hide: false },
    { header: "红字单号", field: "RECEIVEREQUESTNAME", hide: false },
    { header: "物料编号", field: "MATERIALSPECNAME", hide: false },
    { header: "品名", field: "DESC_CN", hide: false },
    { header: "物料规格", field: "DESCRIPTION", hide: false },
    { header: "斯迪克规格", field: "SDK_ID", hide: false },
    // { header: "批次", field: "CHARGE", hide: false },
    { header: "单位", field: "MATERIALUNIT", hide: false },
    { header: "单据类型", field: "SHIPREQUESTTYPE", hide: false },
    { header: "请求数量", field: "REQUESTQUANTITY", hide: false },
    { header: "绑定数量", field: "RECEIVEDQUANTITY", hide: false },
    { header: "组织", field: "ERPFACTORY", hide: false },
    { header: "仓库", field: "ERPLOCATION", hide: false },
    // { header: "物料组", field: "MATERIALGROUP", hide: false },

  ];
  state.column1 = [
    { header: "标签ID", field: "MATERIALPACKINGNAME", hide: false },
    { header: "行项", field: "RECEIVEREQUESTDETAILNAME", hide: true },
    // { header: "行项", field: "SUPPLIERNAME", hide: false },
    { header: "批次", field: "CHARGE", hide: false },
    { header: "发货单号", field: "RECEIVEREQUESTNAME", hide: true },
    { header: "物料编号", field: "MATERIALSPECNAME", hide: false },
    { header: "中文描述", field: "DESC_CN", hide: false },
    { header: "物料规格", field: "SDK_ID", hide: false },
    { header: "位置", field: "LOCATIONNAME", hide: false },
    // { header: "批次", field: "MAKEDATE", hide: false },
    { header: "单位", field: "MATERIALUNIT", hide: false },
    // { header: "移动类型", field: "CREATETIME", hide: false },
    { header: "数量", field: "MATERIALQUANTITY", 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: "RECEIVEREQUESTDETAILNAME", hide: true },
    { header: "物料编号", field: "MATERIALSPECNAME", hide: false },
    { header: "品名", field: "DESC_CN", hide: false },
    { header: "物料规格", field: "SDK_ID", hide: false },
    { header: "物料总数量", field: "MATERIALQUANTITY", hide: false },
    { header: "位置", field: "LOCATIONNAME", hide: false },
    { header: "工厂", field: "SITENAME", hide: true },
    { header: "生成时间", field: "CREATETIME", hide: false },
    { header: "物料类型", field: "MATERIALTYPE", hide: false },
    { header: "物料编号", field: "MATERIALSPECNAME", hide: false },
    { header: "生产日期", field: "MAKEDATE", hide: false },
    { header: "过期时间", field: "EXPIRINGDATE", hide: false },
  ];
  updateTableHeight();
  window.addEventListener('resize', handleResize);
});

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.RECEIVEREQUESTNAME != '') && (state.queryParams.params.RECEIVEREQUESTNAME != null) && (state.queryParams.params.RECEIVEREQUESTNAME != undefined)) {
    state.queryParams.queryId = 'GetReceiveRequestDetailInformationRow';
    state.queryParams.version = '00001';
    getQueryList(state.queryParams).then((res: any) => {
      if (res.data.length > 0) {
        state.ShipList = res.data;
      } else {
        ElMessageBox.alert('搜索结果为空', '提醒框', {
          confirmButtonText: 'OK',
        })
      }

    });
  } 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 = 'WP009';
  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.SHIPREQUESTNAME = row.RECEIVEREQUESTNAME;
  state.queryParams.params.SHIPREQUESTDETAILNAME = row.RECEIVEREQUESTDETAILNAME;
  getQueryList(state.queryParams).then((res: any) => {
    state.MaterialPackingList = res.data;
  });

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


async function LeftIn() {
  if (state.MaterialPackingList.length > 0 && state.column4.length > 0) {

    state.loading = true;
    state.ChangeParams.header.MESSAGENAME = 'AssignReceiveRequestToBox2ForSDK';
    state.ChangeParams.body.RECEIVEREQUESTDETAILNAME = state.queryParams.params.SHIPREQUESTDETAILNAME
    // state.ChangeParams.body.RECEIVEREQUESTDETAILNAME = "0001"
    state.ChangeParams.body.RECEIVEREQUESTNAME = 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',
        })
        state.loading2 = false;
      }


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

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

  state.loading = false;

}

async function RightIn() {
  if (state.column3.length > 0) {
    state.loading2 = true;
    state.ChangeParams.header.MESSAGENAME = 'DeassignShipRequestFromBox2';
    state.ChangeParams.body.RECEIVEREQUESTDETAILNAME = state.RightqueryParams.params.RECEIVEREQUESTDETAILNAME
    state.ChangeParams.body.RECEIVEREQUESTNAME = state.RightqueryParams.params.RECEIVEREQUESTNAME
    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();
}


async function handleStockOut() {
  if (state.MaterialPackingUsername.length > 0) {
    state.loading = true;
    state.loading2 = true;
    state.button_state = true;
    state.button_loadings = true;
    state.ReserveParams.header.MESSAGENAME = 'CompleteShipRequestForPurReturn'
    state.ReserveParams.body.SITENAME = localStorage.getItem("siteName") == null ? "SDK" : localStorage.getItem("siteName");
    state.ReserveParams.body.RECEIVEREQUESTNAME = state.queryParams.params.RECEIVEREQUESTNAME
    state.ReserveParams.body.RECEIVEREQUESTNAME = state.queryParams.params.RECEIVEREQUESTNAME
    state.ReserveParams.body.RECEIVEREQUESTDETAILNAME = state.queryParams.params.SHIPREQUESTDETAILNAME
    state.ReserveParams.body.RECEIVEREQUESTDETAILTYPE = state.queryParams.params.SHIPREQUESTDETAILTYPE
    state.ReserveParams.body.MATERIALSPECNAME = state.queryParams.params.MATERIALSPECNAME
    state.ReserveParams.body.CHECKBOX = false
    state.ReserveParams.body.ACTTYPE = "STCO"
    await BpelEvent(state.ReserveParams).then((res: any) => {
      // handle(tempRow);
      // handleQuery();
      if (IFTRUE(res)) {
        state.loading = false;
        state.loading2 = false;
        ElMessageBox.alert('出库完成', '提示框', {
          confirmButtonText: 'OK',
        })
        state.button_state = false
        state.button_loadings = false;
      } else {
        ElMessageBox.alert(res.data.RETURNCODE + '->' + res.data.RETURNMESSAGE, '', {
          confirmButtonText: 'OK',
        })
        state.button_state = false
        state.button_loadings = false;
      }

    })
      .catch((error: any) => {
        ElMessageBox.alert(error, '提示框', {
          confirmButtonText: 'OK',
        })
        state.loading = false
        state.loading2 = false;
        state.button_state = false
        state.button_loadings = false;
      });
    state.loading = false;
    state.loading2 = false;
    state.button_state = false
    state.button_loadings = false;
  } else {
    ElMessageBox.alert("请先选择要采购退货的标签", '提示框', {
      confirmButtonText: 'OK',
    })
    state.button_state = false
    state.button_loadings = false;
  }
  state.button_state = false
  state.button_loadings = 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>
