<template>
  <div class="vue-element-page-wrap" ref="tableContainer">
    <el-row class="page-search" justify="space-between" align="middle">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="入库单" prop="queryParams.params">
              <el-Input v-model="state.queryParams.params.RECEIVEREQUESTNAME" placeholder="到货单" @keydown.enter.prevent = "handleQuery" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" @click="addDeliveryNote">新增到货单</el-button>
        <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">
          <span>入库单详细信息</span>
        </div>
        <div class="page-table-operateBtns">
          <el-popover :persistent="false" placement="right" popper-class="config-table-wrap" trigger="click">
            <template #reference>
              <el-button class="operateBtns-setting">
                <svg-icon icon-class="table_title" width="16px" height="16px" />
              </el-button>
            </template>
            <ConfigTable :list="column" @updateList="updateList" />
          </el-popover>
        </div>
      </div>
<!--      <el-table :height="tableHeight" border v-loading="loading" :data="state.MATERIALRECEIVEACT" highlight-current-row row-key="id"
                style="width: 100%" @row-click="handle">-->
      <el-table :height="tableHeight" border v-loading="loading" :data="state.MATERIALRECEIVEACT" highlight-current-row row-key="id"
                style="width: 100%">
        <el-table-column prop="ERPFACTORY" fixed="left" label="库存组织" width="100"></el-table-column>
        <el-table-column prop="ERPFACTORY2" label="库存组织"  width="100"></el-table-column>
<!--        <el-table-column prop="RECEIVEREQUESTNAME" label="到货单" width="100"></el-table-column>-->
<!--        <el-table-column prop="RECEIVEREQUESTDETAILNAME" label="到货单明细"  width="80"></el-table-column>-->
        <el-table-column prop="MATERIALSPECNAME" label="物料编号" width="100"></el-table-column>
        <el-table-column prop="DESC_CN" label="物料品名" width="80"></el-table-column>
        <el-table-column prop="MATERIALUNIT" label="单位" width="80"></el-table-column>
        <el-table-column prop="MATERIALUNITDESC" label="单位描述" width="80"></el-table-column>
        <el-table-column prop="DESCRPTION" label="物料规格" width="80"></el-table-column>
        <el-table-column prop="REQUESTQUANTITY" label="订单数量" width="80"></el-table-column>
        <el-table-column prop="RECEIVEDQUANTITY" 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  type =number style="width: 170px">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column prop="ERPLOCATION" 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-select v-model="scope.row.ERPLOCATION" placeholder="选择仓库" style="width: 170px"
                       default-first-option filterable @change="getStorageSpec">
              <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="ERPLOCATIONDESC" label="库位(CN)" width="180"></el-table-column>-->
        <el-table-column prop="LOCATIONNAME" 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 >
<!--            <el-select v-model="scope.row.LOCATIONNAME" placeholder="选择库位" style="width: 170px"
                       default-first-option filterable >-->
              <el-option v-for="item in state.POCreateLocationList" :key="item.VALUE" :label="item.LABEL"
                         :value="item.VALUE" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="SUPPLIERNO" label="供应商编码" width="80"></el-table-column>
        <el-table-column prop="ORDERREMARK" label="单据备注"></el-table-column>
        <el-table-column prop="OHREMARK" label="行备注"></el-table-column>
      </el-table>
    </div>
    <div class="vue-element-page-table">
      <el-row class="page-search" justify="space-between" align="middle">
        <el-form ref="operateFormRef" :model="operateParams" :inline="true">
          <el-row :gutter="20">
            <el-col :span = "4">
              <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>
            </el-col>

            <el-col :span="8">
              <el-Input v-model="state.OpCode"  :disabled = false readonly />
            </el-col>
            <el-col :span="3">
              <el-button type="primary" @click="sendToERP" :disabled="state.button_state" v-loading.fullscreen.lock="state.button_loading">入库</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
    </div>
    <drawer v-if="showDeliveryDrawer" v-model="showDeliveryDrawer" @refresh="refresh" :delivery-type="'02'"/>
  </div>
</template>

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

<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance, nextTick } from "vue";
import { ElForm, ElMessageBox, ElTable } from "element-plus";
import { BpelEvent, getQueryList } from "@/api/common";
import { useRoute } from 'vue-router'
import { localStorage } from "@/utils/storage";
import { IFTRUE, areAllNotEmpty, msToDate } from "@/utils/CommonUtil"
import { NoChargeStockIn } from '@/api/StockIn'
import {getOpCode} from "@/api/opcode";
import { bTableHeight } from "../../../composables/calcTableHeight";
import Drawer from '@/views/stockIn/delivery/drawer.vue'
import { getStoreDetail } from '@/api/delivery'
import request from '@/utils/request'

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

const formDataRef = ref(ElForm);
const { proxy }: any = getCurrentInstance();
const state = reactive({
  ERPFACTORY: '',
  orgNo:'',
  commitDate:'',
  rsa: "",
  loadings: false,
  disabledss: false,
  InputState: true,
  RealERPLocation: [] as any,//用于存储实际查询到仓库
  RealLocation: [] as any,//用于存储实际查询到库位
  POCreateLocationList: [] as any,
  UnitList: [] as any,
  ERPLocationList: [] as any,
  button_state: false,
  MATERIALRECEIVEACT: [] as any,
  ReceiveACTList: [] as any,
  showDeliveryDrawer: false,
  queryParams: {
    queryId: "",
    version: "",
    params: {
      //SITENAME: localStorage.get("siteName"),
      SITENAME: 'SDK',
      RECEIVEREQUESTNAME: "",
      deliveryType: '02'
    },
  },
  ChangeParams: {
    header: {
      MESSAGENAME: '',
      LANGUAGE: 'Chinese',
      EventUser: localStorage.get('userId')
    },
    body: {
      RECEIVETIME: '',//过账时间
      SITENAME: localStorage.get("siteName") == null ? "SDK" : localStorage.get("siteName"),
      RECEIVEACTNO: '',
      RECEIVEREQUESTNAME: '',
    }
  },
  operateParams: {
    date: new Date()
  },
  OpCode : "",
  loading: false,
  button_loading: false,
  userList: [] as any,
  column: [] as any,
});
const { ERPFACTORY, MATERIALRECEIVEACT, rsa, showDeliveryDrawer, queryParams, loading, button_loading, userList, column, operateParams } = 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.column = [
  //   { header: "库存组织", field: "ERPFACTORY", hide: true },
  //   { header: "库存组织", field: "ERPFACTORY2", hide: false },
  //   { header: "到货单", field: "RECEIVEREQUESTNAME", hide: false },
  //   { header: "到货单明细", field: "RECEIVEREQUESTDETAILNAME", hide: false },
  //   { header: "物料编号", field: "MATERIALSPECNAME", hide: false },
  //   { header: "物料品名", field: "DESC_CN", hide: false },
  //   { header: "单位", field: "MATERIALUNIT", hide: false },
  //   { header: "单位描述", field: "MATERIALUNITDESC", hide: false },
  //   { header: "规格", field: "DESCRPTION", hide: false },
  //   { header: "订单数量", field: "REQUESTQUANTITY", hide: false },
  //   { header: "实收数量", field: "RECEIVEDQUANTITY", hide: false, },
  //   { header: "仓库", field: "ERPLOCATION", hide: true, text: true },
  //   { header: "货位", field: "LOCATIONNAME", hide: true, display: true },
  //   { header: "本次接收数量", field: "ThisAcceptNumber", hide: true, time: true },
  // ];

  updateTableHeight();
  window.addEventListener('resize', handleResize);

  let pwd: any = localStorage.get('remeberPwd');
  // state.orgNo = JSON.parse(pwd).orgNo;
  state.ERPFACTORY = JSON.parse(pwd)?.orgNo;
});

//查询所有的入库单
function SelectReceiveAct() {
  state.queryParams.queryId = 'GetNormalReceiveActNoList'
  state.queryParams.version = 'H0002'
  getQueryList(state.queryParams).then((res: any) => {
    state.ReceiveACTList = res.data
  })
}

// 新增到货单
function addDeliveryNote() {
  state.showDeliveryDrawer = true
}

// 创建到货单后刷新页面
function refresh(data:any) {
  state.queryParams.params.RECEIVEREQUESTNAME = data
  state.showDeliveryDrawer = false
  handleQuery()
}

// 更新列
function updateList(col: any) {
  state.column = col;
}

function handleQuery() {
  state.InputState = true
  state.queryParams.queryId = 'GetNoBatchPOStockIn'
  state.queryParams.version = '00001'
  state.MATERIALRECEIVEACT = []
  if(state.queryParams.params.RECEIVEREQUESTNAME == ''){
    ElMessageBox.alert('输入查询条件', '提醒框', {
      confirmButtonText: 'OK',
    })
    return
  }
  getStoreDetail(state.queryParams).then((res: any) => {
    if (res.resultObj) {
      // 加载库位
      if (res.resultObj.length > 0) {
        getERPLocation(res.resultObj[0].ERPFACTORY)
        getStorageSpec(res.resultObj[0].ERPFACTORY)
      }
      state.MATERIALRECEIVEACT = res.resultObj
    } else {
      ElMessageBox.alert('查无数据', '提醒框', {
        confirmButtonText: 'OK',
      })
    }
  }).catch((error: any) => {
    ElMessageBox.alert(error.message, '提醒框', {
      confirmButtonText: 'OK',
    })
  })
}


 function sendToERP() {

  state.button_loading=true
  state.loading=true
  console.log(state.button_loading);
  console.log(state.loading);
  console.log(state.commitDate)
  if(state.commitDate == null){
    ElMessageBox.alert('过账时间不可清空', {
      confirmButtonText: 'OK',
    })
    return;
  }
  
  getOpCode (
          {
            opcode : state.OpCode,
            user: localStorage.get('userId'),
          }
  ).then((res: any) => {
    console.log(res.resultObj)
    state.OpCode = res.resultObj
    let pattern = new RegExp("[\u4E00-\u9FA5]+");
    for (let i = 0; i < state.MATERIALRECEIVEACT.length; i++) {
      console.log(areAllNotEmpty(state.MATERIALRECEIVEACT[i].LOCATIONNAME), state.RealERPLocation[i])
      if (pattern.test(state.MATERIALRECEIVEACT[i].ERPLOCATION || (!areAllNotEmpty(state.MATERIALRECEIVEACT[i].LOCATIONNAME)))) {
        state.MATERIALRECEIVEACT[i].LOCATIONNAME = state.RealLocation[i] == null ? "" : state.RealLocation[i]
        state.MATERIALRECEIVEACT[i].ERPLOCATION = state.RealERPLocation[i] == null ? "" : state.RealERPLocation[i]
      }
    }
    console.log(state.MATERIALRECEIVEACT)
     NoChargeStockIn({
      commitDate : state.commitDate,
      USER : localStorage.get("userId"),
      SITENAME: localStorage.get('siteName') || 'SDK',
      RECEIVEREQUESTNAME: state.queryParams.params.RECEIVEREQUESTNAME,
      BOXLIST: {
        ...state.MATERIALRECEIVEACT
      }
    }).then((res: any) => {
      if (res.success) {
        console.log(res.message)
        state.OpCode = "",
        ElMessageBox.alert('入库成功', '提醒框', {
          confirmButtonText: 'OK',
        })
       
        state.button_loading = false
        state.loading = false
        handleQuery()
      } else {
        ElMessageBox.alert('入库失败：' + res.message, '提醒框', {
          confirmButtonText: 'OK',
        })
        state.button_loading = false
        state.loading = false
      }
    }).catch((err: any) => {
      console.log(res.message)
      ElMessageBox.alert('入库失败' + err.response.data.message, '提醒框', {
        confirmButtonText: 'OK',
      })
      state.button_loading = false
      state.loading = false
    })
    
  })

}
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',
    })
  }

}

/**************************************************公共方法************************************************/
function formatDate(date: any) {
  var year = date.getFullYear();

  // 注意JavaScript中的月份是从0开始的，所以需要+1  
  var month = ("0" + (date.getMonth() + 1)).slice(-2);

  // 同样，日期也是从1开始的，但是我们需要检查它是否小于10，并在前面添加0（如果需要）  
  var day = ("0" + date.getDate()).slice(-2);

  // 拼接字符串  
  return year + "-" + month + "-" + day;
}
function getStorageSpec(value: any) {
  state.POCreateLocationList = []
  getQueryList({
    queryId: "GetLocationForCreatePO",
    version: "00001",
    params: {
      SITENAME: "SDK",
      ERPLOCATION: value
    } as any,
  }).then((res: any) => {
    state.POCreateLocationList = res.data

  })
}
function getERPLocation(erpfactory: any) {
  getQueryList({
    queryId: "GetERPLocationForCreatePO",
    version: "00001",
    params: {
      SITENAME: "SDK",
      ERPFACTORYNAME: erpfactory,//PO
    } as any,
  }).then((res: any) => {
    state.ERPLocationList = res.data

  })
}
</script>

<style scoped lang="scss">
.el-overlay.userRoleModel {}

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