<!--
  辅料出库
-->
<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">
      <div class="page-table-operate">
        <div class="page-table-title">
          <div class="page-table-title-left">
            <span>发货单据信息</span>
          </div>
        </div>
      </div>
      <el-table style="width: 100%;min-height:50px"  @row-click="handle" :height="tableHeight" border v-loading="loading" :data="ShipList" highlight-current-row row-key="id">
        <el-table-column prop="SHIPREQUESTNAME" label="发货单号"  width="120"></el-table-column>
        <el-table-column prop="ERPFACTORYDESC" label="发货组织" width="220"></el-table-column>
        <el-table-column prop="ERPLOCATIONDES" label="发货货位" width="180">
          <template #default="scope">
            <el-select  v-model="scope.row.ERPLOCATION" placeholder="选择仓库" style="width: 170px" default-first-option
              @focus="getStorageSpec(scope.row.ERPLOCATION)" filterable>
              <el-option v-for="item in state.ERPLocationList" :key="item.VALUE" :label="item.LABEL" :value="item.VALUE" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="ERPLOCATIONNAMEDES" label="发货库位" width="180">
          <template #default="scope">
            <el-select v-model="scope.row.LOCATIONNAME" placeholder="选择库位" style="width: 170px"
                       @focus="getStorageSpec(scope.row.ERPLOCATION)" default-first-option filterable
                       :filter-method="locatioNFilter">
              <el-option v-for="item in state.LocationList" :key="item.VALUE" :label="item.LABEL"
                :value="item.VALUE" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="ERPRECEIVEFACTORYDESC" label="接收组织" width="220"></el-table-column>
        <el-table-column prop="ERPRECEIVELOCATIONDES" label="接收货位" width="180"></el-table-column>
        <el-table-column prop="MATERIALSPECNAME" label="物料编号" width="120"></el-table-column>
        <el-table-column prop="DESC_CN" label="品名" width="120"></el-table-column>
        <el-table-column prop="DESCRIPTION" label="物料规格" width="120"></el-table-column>
        <el-table-column prop="SDK_ID" label="SDK规格" width="120"></el-table-column>
        <el-table-column prop="PHASE" label="阶段" width="120"></el-table-column>
        <el-table-column prop="MATERIALUNIT" label="单位" width="120"></el-table-column>
        <el-table-column prop="SHIPREQUESTTYPE" label="发货类型" width="80"></el-table-column>
        <el-table-column prop="REQUESTQUANTITY" label="请求数量" width="80"></el-table-column>
        <el-table-column prop="ASSIGNEDQUANTITY" label="绑定数量"  width="80"></el-table-column>
        <el-table-column prop="THISACCEPTNUMBER" label="本次发出数量" width="180">
          <template #default="scope">
            <el-input v-model="scope.row.THISACCEPTNUMBER" min = 0 max  type =number style="width: 130px">
            </el-input>
          </template>
        </el-table-column>
      </el-table>
      <div class="page-table-operate">
        <div class="page-table-title"></div>
        <div>
          <el-button type="primary" :disabled="state.button_state" @click="cancelHandleFn">取消备货</el-button>
          <el-button type="primary" :disabled="state.button_state" @click="handleFn">确认备货</el-button>
        </div>
      </div>
        <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="state.MaterialPackingList" highlight-current-row row-key="id"
                    style="width: 100%;min-height:50px" @selection-change="handleSelectionChange2">
            <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>
    </div>
    <!-- 左右结构 -->
    <el-row class="page-search" justify="end" align="middle">
      <div class="block" style="float: left">
        <el-Input v-model="state.OpCode"  :disabled = true readonly />
      </div>
      <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="handleStockOut"  :disabled="state.button_state">出库</el-button>
      </div>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: "auxiliaryOut",
};
</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,  bpelAuxiliary,AuxiliaryReserve,AuxiliaryDessign } from '@/api/common'
import { useRouter } from "vue-router";
import { bTableHeight } from "../../../composables/calcTableHeight";
import { areAllNotEmpty } from "@/utils/CommonUtil"
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({
  MATERIALQUANTITY1:[],
  commitDate:'',
  rsa: "",
  LShipRequestDetailName: '',
  LShipType: '',
  button_state: false,
  button_state2: false,
  STOCKSELECT: [],
  AleardyBooking: false,
  IFCompleteStockUp: 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: "",
      SHIPREQUESTNAME: "",
      MATERIALSPECNAME: '',
      AREANAME: '',
      MATERIALPACKING: '',
      DURABLENAME: '',
      CHARGE: '',
      ERPFACTORYNAME: '',
      ERPLOCATION: '',
      SDK_ID: '',
      PHASE: '',
      ERPFACTORY: '',
      SHIPREQUESTDETAILNAME: '',
      DESCRIPTION: '',
    },
  },
  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: '',
      EventUser: localStorage.getItem('userId') ,
      LANGUAGE: 'Chinese',
      Flag: 'LK'//立库标志
    },
    body: {
      SHIPREQUESTNAME: '',
      SHIPREQUESTDETAILNAME: '',
      SITENAME: 'SDK',
      MATERIALPACKINGNAME: '',
      objPara: [] as any,
    }
  },
  ReserveParams: {
    user :'',
    commitDate:'',
    MaterialPackingList:[{
      materialQuantity2:'' ,
      sidInput: false,
    }] as any,
  },
  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: [{
    sdiInput: false,
  }] as any,
  MaterialPackingUsername: [] as any,
  column1: [] as any,
  column: [] as any,
  column2: [] as any,
  column3: [] as any,
  column4: [] as any,
  button_but : false
});
const {  MaterialPackingList, ShipList, rsa, queryParams, loading, loading2, userList, column, column1, column2, operateParams, operateOptions, actNoOptions, checkResultOptions } = toRefs(state);
onMounted(() => {

  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
  state.column1 = [
    { header: "标签ID", field: "MATERIALPACKINGNAME", hide: false },
    { header: "发货单号", field: "SHIPREQUESTNAME", hide: true },
    { header: "物料编号", field: "MATERIALSPECNAME", hide: false },
    { header: "品名", field: "DESC_CN", hide: false },
    { header: "物料规格", field: "SDK_ID", hide: true },
    { header: "物料规格", field: "SPECNAME", hide: false },
    { header: "组织", field: "ERPFACTORY", hide: false },
    { header: "仓库", field: "ERPLOCATION", hide: false },
    { header: "货位", field: "LOCATIONNAME", hide: false },
    { header: "发货数量", field: "MATERIALQUANTITY2", hide: false },
    { header: "单位", field: "MATERIALUNIT", hide: false },
    { header: "入库日期", field: "RECEIVETIME", hide: false },
    { header: "生产日期", field: "MAKEDATE", hide: false },
    { header: "过期时间", field: "EXPIRINGDATE", hide: false }
  ];
  updateTableHeight();
  window.addEventListener('resize', handleResize);
});

function QUANTITY1(indexSum : any) {
  if (Number(state.MaterialPackingList[indexSum].materialQuantity2) > Number(state.MaterialPackingList[indexSum]['MATERIALQUANTITY'])){
    ElMessageBox.alert('出库数量大于库存数量', '提醒框', {
      confirmButtonText: 'OK',
    })
    state.MaterialPackingList[indexSum].materialQuantity2 = '';
  } else {
    state.MaterialPackingList[indexSum]['SHIPREQUESTNAME'] = state.queryParams.params.SHIPREQUESTNAME
    state.MaterialPackingList[indexSum]['SHIPREQUESTTYPE'] = state.ShipList[0]['SHIPREQUESTTYPE']
  }
}
function handle(row: any, event: any, column: any) {
  if (areAllNotEmpty(row.ERPFACTORY)) {
    getERPLocation(row.ERPFACTORY)
  } else {
    ElMessageBox.alert("该明细下组织为空！", '警示框', {
      confirmButtonText: 'OK',
    })
  }


  if (areAllNotEmpty(row.ERPLOCATION)) {
    getStorageSpec(row.ERPLOCATION)
  } else {
    ElMessageBox.alert("该仓库下货位为空！", '警示框', {
      confirmButtonText: 'OK',
    })
  }

  state.queryParams.queryId = 'GetPackingRow'
  state.queryParams.version = 'xh002'
  state.queryParams.params.SITENAME = "SDK"
  state.queryParams.params.MATERIALSPECNAME = row.MATERIALSPECNAME
  state.queryParams.params.RECEIVEREQUESTNAME = row.SHIPREQUESTNAME
  state.MATERIALPACKINGLIST = []
  getQueryList(state.queryParams).then((res: any) => {
    console.log(res.data)
    state.MATERIALPACKINGLIST = res.data

  }).catch((error: any) => {
    ElMessageBox.alert(error.message, '提醒框', {
      confirmButtonText: 'OK',
    })
  })

}
function getStorageSpec(value: any) {
  state.AllLocationList = []
  getQueryList({
    queryId: "GetLocationForCreatePO",
    version: "00001",
    params: {
      SITENAME: "SDK",
      ERPLOCATION: value,//PO
    } as any,
  }).then((res: any) => {
    state.AllLocationList = res.data
    locatioNFilter('')
  })
}
/**
 * 货位卡顿处理
 * @param query
 */
 function locatioNFilter(query : any) {
  console.log(query)
  let arr = state.AllLocationList.filter((item : any) => {
    return (item.LABEL.includes(query) || item.VALUE.includes(query))
  })
  if (arr.length > 50) {
    state.LocationList = arr.slice(0, 50)
  } else {
    state.LocationList = arr
  }
}
function getERPLocation(erpfactory: any) {
  getQueryList({
    queryId: "GetERPLocationForCreatePO",
    version: "00001",
    params: {
      SITENAME: "SDK",
      ERPFACTORYNAME: erpfactory,//PO
    } as any,
  }).then((res: any) => {
    state.ERPLocationList = res.data

  })
}
function handleSelectionChange(selection: any) {
  // console.log('调用了1', selection)
  state.column3 = selection
}
function handleSelectionChange2(selection: any) {
  // console.log('调用了2', selection)
  state.column4 = selection
  state.ReserveParams.MaterialPackingList = selection
}
// 更新列
function updateList(col: any) {
  state.column = col;
}
function handleQuery() {
  state.ShipList = [];
  state.MaterialPackingList =[];
  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 = '00054';
    getQueryList(state.queryParams).then((res: any) => {
      if (res.data.length > 0) {
        state.ShipList = res.data;
      } else {
        ElMessageBox.alert('查无数据', '提醒框', {
        confirmButtonText: 'OK',
      })
      }

    });
  } else {
    ElMessageBox.alert('搜索条件不能为空', '提醒框', {
      confirmButtonText: 'OK',
    })
    return ;
  }

  if ((state.queryParams.params.SHIPREQUESTNAME != '') && (state.queryParams.params.SHIPREQUESTNAME != null) && (state.queryParams.params.SHIPREQUESTNAME != undefined)) {
    state.queryParams.queryId = 'GetPackingRow';
    state.queryParams.version = '00054';
    getQueryList(state.queryParams).then((res: any) => {
      if (res.data.length > 0) {
        state.MaterialPackingList = res.data;
      } else {
      }

    });
  } else {
    ElMessageBox.alert('搜索条件不能为空', '提醒框', {
      confirmButtonText: 'OK',
    })
  }
}

/**
 * 备货
 */
function handleFn () {
  if (state.ShipList.length <= 0) {
    ElMessageBox.alert('没有单据明细，请确认')
    return
  }
  state.loading = true
  state.button_state = true
  state.ReserveParams.SITENAME = localStorage.getItem("siteName") == null ? "SDK" : localStorage.getItem("siteName");
  state.ReserveParams.SHIPREQUESTNAME = state.queryParams.params.SHIPREQUESTNAME //单据
  state.ReserveParams.user = localStorage.getItem('userId')
  state.ReserveParams.boxList = state.ShipList
  AuxiliaryReserve(state.ReserveParams).then((res: any) => {
    if (res.success){
      state.button_state = false;
      state.loading = false;
      handleQuery();
    } else {
      state.button_state = false;
      state.loading = false;
      ElMessageBox.alert(res.message, '', {
        confirmButtonText: 'OK',
      })
    }
  }).catch((error: any) => {
    ElMessageBox.alert(error, '提示框', {
      confirmButtonText: 'OK',
    })
    state.loading = false
    state.button_state = true
  });
}

/**
 * 取消备货
 */
function cancelHandleFn() {
  if (state.ShipList.length <= 0) {
    ElMessageBox.alert('没有单据明细，请确认')
    return
  }
  state.loading = true
  state.button_state = true
  state.ReserveParams.SITENAME = localStorage.getItem("siteName") == null ? "SDK" : localStorage.getItem("siteName");
  state.ReserveParams.SHIPREQUESTNAME = state.queryParams.params.SHIPREQUESTNAME //单据
  state.ReserveParams.user = localStorage.getItem('userId')
  state.ReserveParams.boxList = state.ShipList
  AuxiliaryDessign(state.ReserveParams).then((res: any) => {
    if (res.success){
      state.button_state = false;
      state.loading = false;
      handleQuery();
    } else {
      state.button_state = false;
      state.loading = false;
      ElMessageBox.alert(res.message, '', {
        confirmButtonText: 'OK',
      })
    }
  }).catch((error: any) => {
    ElMessageBox.alert(error, '提示框', {
      confirmButtonText: 'OK',
    })
    state.loading = false
    state.button_state = true
  });
}

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

function handleStockOut() {
  console.log(state.commitDate)
  if(state.commitDate == null){
    ElMessageBox.alert('过账时间不可清空', {
      confirmButtonText: 'OK',
    })
    return;
  }
  if (1 == 1) {
    // console.log(state.ShipList.length)
    if (state.ShipList.length <= 0) {
      ElMessageBox.alert('没有出库明细，请确认')
      return
    }
      state.loading = true
      state.button_state = true
      state.ReserveParams.SITENAME = localStorage.getItem("siteName") == null ? "SDK" : localStorage.getItem("siteName");
      state.ReserveParams.SHIPREQUESTDETAILNAME =  state.queryParams.params.SHIPREQUESTDETAILNAME
      state.ReserveParams.SHIPREQUESTNAME = state.queryParams.params.SHIPREQUESTNAME //单据
      state.ReserveParams.SHIPREQUESTTYPE = state.ShipList[0]['SHIPREQUESTTYPE'] //发货类型
      state.ReserveParams.user = localStorage.getItem('userId')
    state.ReserveParams.commitDate = state.commitDate
      state.MaterialPackingList.key = {}
      state.ReserveParams.MaterialPackingList = state.MaterialPackingList
      bpelAuxiliary(state.ReserveParams).then((res: any) => {
        if (res.success){
          state.button_state = false;
          state.loading = false;
          handleQuery();
          ElMessageBox.alert('出库完成', '提示框', {
            confirmButtonText: 'OK',
          })
        } else {
          state.button_state = false;
          state.loading = false;
          ElMessageBox.alert(res.message, '', {
            confirmButtonText: 'OK',
          })
        }
      }).catch((error: any) => {
        ElMessageBox.alert(error, '提示框', {
          confirmButtonText: 'OK',
        })
        state.loading = false
        state.button_state = true
      });
  }
  state.button_state2 = true
  state.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>