<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>
<!--      <el-table class="info-table" border v-loading="loading" :data="state.MATERIALRECEIVEACT" highlight-current-row row-key="id" @row-click="handle">-->
      <el-table class="info-table" border v-loading="loading" :data="state.MATERIALRECEIVEACT"
                highlight-current-row row-key="id" @row-click="handle">
        <el-table-column prop="MATERIALSPECNAME" fixed="left" label="料号" width="100" />
        <el-table-column prop="ERPFACTORY" label="组织" width="100" />
        <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-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="REQUESTQUANTITY" label="订单数量" width="100" />
        <el-table-column prop="RECEIVEDQUANTITY" label="已接收数量" width="100" />
        <el-table-column prop="STOCKINQTY" label="已入库数量" width="100" />
        <el-table-column prop="CREATEQTY" label="本次创建数量" width="100" />
        <el-table-column prop="MINUSQTY" label="剩余数量" width="100" />
        <el-table-column prop="DESC_CN" label="品名" width="280" />
        <el-table-column prop="DESCRIPTION" label="物料规格" width="100" />
        <el-table-column prop="SDK_ID" label="斯迪克规格ID" v-if="false" width="80" />
        <el-table-column prop="SPECNAME" label="斯迪克规格" width="100" />
        <el-table-column prop="PHASE" label="阶段" width="80" />
        <el-table-column prop="MAKEDATE" label="生产日期" width="120">
          <template #default="scope">
            <el-date-picker v-model="scope.row['MAKEDATE']" type="date" style="width: 110px"
                            placeholder="请选择时间" :size="'small'" v-if="scope.row['REPLACED_VALUE'] != '未定义'" />
          </template>
        </el-table-column>
        <el-table-column prop="RECEIVETIME" label="接收日期" width="120">
          <template #default="scope">
            <el-date-picker v-model="scope.row['RECEIVETIME']" type="date" style="width: 110px"
                            placeholder="请选择时间" :size="'small'" v-if="scope.row['REPLACED_VALUE'] != '未定义'" />
          </template>
        </el-table-column>
        <el-table-column prop="MATERIALUNITDESC" label="单位" width="50" />
        <el-table-column prop="FUNIT" label="辅助单位" v-if="false" width="50" />
        <el-table-column prop="FUNITDESC" label="辅助单位" width="50" />
        <el-table-column prop="UNIT_RATES" label="换算率" width="50" />
        <el-table-column prop="IS_BATCH" label="启用批次" width="80" />
        <el-table-column prop="IQCFLAG" label="启用质检" width="80" />
        <el-table-column prop="REPLACED_VALUE" label="有效期管理方式" width="150" />
        <el-table-column prop="SUPPLIERNO" label="供应商" width="180" />
        <el-table-column prop="REMARK" label="备注" width="180" />
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-button @click="createBox(scope.row)" type="text" size="small">创建批次</el-button>
            <el-button @click="deleteBox(scope.row)" type="text" size="small">删除批次</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="vue-element-page-table">
      <div class="page-table-operate">
        <div class="page-table-title">
          <span>批次信息</span>
        </div>
      </div>
      <el-table class="charge-table" :height="tableHeight" :data="state.MATERIALPACKINGLIST" border >
<!--        <el-table-column prop="SEQ" label="序号" fixed="left" width="100" />-->
        <el-table-column prop="CHARGE" label="批次" fixed="left" width="180" />
        <el-table-column prop="MATERIALSPECNAME" fixed="left" label="料号" width="100" />
        <el-table-column prop="ERPFACTROY" label="组织" v-if="false" width="180" />
        <el-table-column prop="ERPFACTROYDESC" label="组织(CN)" width="220" />
        <el-table-column prop="RECEIVEREQUESTNAME" label="单号" width="120" />
        <el-table-column prop="MATERIALPACKINGNAME" label="标签" fixed="left" v-if="false" width="180" />
        <el-table-column prop="DESC_CN" label="品名" width="280" />
        <el-table-column prop="DESCRIPTION" label="物料规格" width="180" />
        <el-table-column prop="TRUEGG" label="实际规格" width="150" />
        <el-table-column prop="SDK_ID" label="斯迪克规格ID" v-if="false" width="80" />
        <el-table-column prop="SPECNAME" label="斯迪克规格" width="180" />
        <el-table-column prop="PHASE" label="阶段" width="80" />
        <el-table-column prop="ERPLOCATION" label="库位" v-if="false" width="180" />
        <el-table-column prop="ERPLOCATIONDESC" label="库位(CN)" width="180" />
        <el-table-column prop="LOCATIONNAME" label="货位" v-if="false" width="180" />
        <el-table-column prop="LOCATIONNAMEDESC" label="货位(CN)" width="180" />
        <el-table-column prop="MATERIALQUANTITY" label="数量" width="50" />
        <el-table-column prop="UNIT" label="单位" width="50" />
        <el-table-column prop="SUPPLIERNO" label="供应商" width="180" />
        <el-table-column prop="REMARK" label="备注" width="180" />
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-button @click="deleteThisBox(scope.row)" type="text" size="small"
              >删除本批次
            </el-button>
          </template>
        </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="选择打印机" v-model="state.PRINTNAME">
                <el-select v-model="state.PRINTNAME" placeholder="请选择打印机" style="width: 240px">
                  <el-option v-for="item in state.PRINTLIST" :key="item.VALUE" :label="item.LABEL" :value="item.VALUE" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <el-button type="primary" @click="print" :disabled="state.button_print" v-loading="state.loadings">打印</el-button>
            </el-col>
            <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="state.button_loading">入库</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
    </div>
    <div style="width: 300px">
      <el-drawer v-model="boxDrawer" title="创建标签" size="300px">
        <el-form :model="state.createBoxForm" :rules="rules" ref="state.createBoxForm">
          <el-form-item label="订单数量" prop="state.createBoxForm.REQUESTQUANTITY">
            <span>{{ state.createBoxForm.REQUESTQUANTITY }}</span>
          </el-form-item>
          <el-form-item label="已收数量" prop="state.createBoxForm.RECEIVEDQUANTITY">
            <span>{{ state.createBoxForm.RECEIVEDQUANTITY }}</span>
          </el-form-item>
          <el-form-item label="实收数量" prop="state.createBoxForm.RECEIVEDQUANTITY2">
            <span>{{ state.createBoxForm.RECEIVEDQUANTITY2 }}</span>
          </el-form-item>
          <el-form-item label="剩余数量" prop="state.createBoxForm.MINUSQTY">
            <span>{{ state.createBoxForm.MINUSQTY }}</span>
          </el-form-item>
          <el-form-item label="实际规格" prop="state.createBoxForm.TrueGG">
            <el-Input v-model="state.createBoxForm.TrueGG" placeholder="实际规格" clearable @input="InputNumber" />
          </el-form-item>
          <el-form-item label="标签个数" prop="state.createBoxForm.MATERIALQUANTITY">
            <el-Input v-model="state.createBoxForm.MATERIALQUANTITY" placeholder="标签个数"
                      type="number" min="0" clearable @input="InputNumber3" />
          </el-form-item>
          <el-form-item label="单个标签物料数量" prop="state.createBoxForm.MATERIALCREATEQUANTITY">
            <el-Input v-model="state.createBoxForm.MATERIALCREATEQUANTITY" placeholder="单个标签物料数量"
                      type="number" min="0" @input="InputNumber2" clearable />
          </el-form-item>
          <el-form-item label="辅单位" prop="funit">
            <el-select v-model="state.createBoxForm.FUNIT" placeholder="辅单位" style="width: 240px"
                       :disabled="state.unitAble" filterable default-first-option>
              <el-option v-for="item in state.UnitList" :key="item.VALUE" :label="item.LABEL" :value="item.VALUE" />
            </el-select>
          </el-form-item>
          <el-form-item label="转换系数" prop="state.createBoxForm.UNIT_RATES">
            <el-Input v-model="state.createBoxForm.UNIT_RATES" placeholder="转换系数" :disabled="true" @keyUpEvent="handleQuery" />
          </el-form-item>
          <el-form-item label="辅数量" prop="state.createBoxForm.FQTY">
            <el-Input v-model="state.createBoxForm.FQTY" placeholder="辅数量" clearable type="number" min="0" @keyUpEvent="handleQuery" />
          </el-form-item>
          <el-form-item label="备注" prop="state.createBoxForm.Remark">
            <el-Input v-model="state.createBoxForm.Remark" placeholder="备注信息..." clearable @keyUpEvent="handleQuery" />
          </el-form-item>
          <div class="page-search-btns">
            <el-button type="primary" @click="commitBox" :disabled="state.button_state2" v-loading="state.button_loading2">提交</el-button>
          </div>
        </el-form>
      </el-drawer>
    </div>
    <drawer v-if="showDeliveryDrawer" v-model="showDeliveryDrawer" @refresh="refresh" :delivery-type="'01'"/>
  </div>
</template>

<script lang="ts">
export default {
  name: 'StockInByCharge'
}
</script>

<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs } from 'vue'
import { ElForm, ElMessageBox, ElTable } from 'element-plus'
import { getQueryList } from '@/api/common'
import { getStoreDetail } from '@/api/delivery'
import { localStorage } from '@/utils/storage'
import { areAllNotEmpty, msToDate } from '@/utils/CommonUtil'
import {
  CreateBox,
  DeleteTrackOutBox,
  PurInSendERPByCharge,
  DeleteTrackOutThisBox
} from '@/api/StockIn'
import { getOpCode } from '@/api/opcode'
import { printLabel } from '@/api/label'
import { bTableHeight } from '@/composables/calcTableHeight'
import { cals } from '@/utils/cal'
import Drawer from '@/views/stockIn/delivery/drawer.vue'

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

const state = reactive({
  button_loading: false,
  button_loading2: false,
  MATERIALPACKINGLISTS: {},
  boxDrawer: false,
  showDeliveryDrawer: false,
  direction: 'ltr',
  rsa: '',
  loadings: false,
  button_print: false,
  disabledss: false,
  InputState: true,
  RealERPLocation: [] as any, // 用于存储实际查询到仓库
  RealLocation: [] as any, // 用于存储实际查询到库位
  MATERIALPACKINGLIST: [] as any,
  POCreateLocationList: [] as any,
  LocationList: [] as any, // 货位集合
  AllLocationList: [] as any, // 所有货位集合
  UnitList: [] as any,
  ERPLocationList: [] as any,
  button_state: false,
  button_state2: false,
  MATERIALRECEIVEACT: [] as any,
  ReceiveACTList: [] as any,
  createBoxForm: {},
  unitAble: false,
  commitDate: '',
  defaultDate: '',
  PRINTLIST: [] as any, // 打印机
  PRINTNAME: '',
  queryParams: {
    queryId: '',
    version: '',
    params: {
      SITENAME: 'SDK',
      RECEIVEREQUESTNAME: '',
      MATERIALSPECNAME: ''
    }
  },
  operateParams: {
    date: new Date()
  },
  stockInloadings: true,
  loading: false,
  userList: [] as any,
  column: [] as any,
  rules: {
    MATERIALQUANTITY: [
      { required: true, message: '请输入数字', trigger: 'blur' },
      { type: 'number', message: '输入内容不是有效的数字', trigger: 'blur' }
    ],
    MATERIALCREATEQUANTITY: [
      { required: true, message: '请输入数字', trigger: 'blur' },
      { type: 'number', message: '输入内容不是有效的数字', trigger: 'blur' }
    ]
  },
  OpCode: '' // 过账流水
})
onMounted(() => {
  getPRINTLIST()
})
const { queryParams, loading, operateParams, boxDrawer, showDeliveryDrawer, rules } = toRefs(state)

onMounted(() => {
  getMaterialUnit()
  var getTime = new Date().getTime() //获取到当前时间戳
  var time = new Date(getTime) //创建一个日期对象
  state.createBoxForm.MAKEDATE = nowDate(time)
  console.log('MAKEDATE', state.createBoxForm.MAKEDATE)
  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 addDeliveryNote() {
  state.showDeliveryDrawer = true
}

// 辅数量更新
function updateFnumber() {
  console.log('我来了' + state.createBoxForm.UNIT_RATES)
  let fz = 0
  let fm = 0
  if (state.createBoxForm.UNIT_RATES != null && state.createBoxForm.UNIT_RATES != '') {
    const match = state.createBoxForm.UNIT_RATES.match(/^(-?\d+(\.\d+)?)\/(-?\d+(\.\d+)?)$/)
    if (!match) {
      console.log('字符串不是有效的分数格式')
      return
    }
    fz = Number(state.createBoxForm.UNIT_RATES.split('\/')[0]) // 分子
    fm = Number(state.createBoxForm.UNIT_RATES.split('\/')[1]) // 分母
  }
  state.createBoxForm.FQTY = cals
    .div(state.createBoxForm.MATERIALCREATEQUANTITY, cals.div(fz, fm).toNumber())
    .toNumber()
}

function getPRINTLIST() {
  getQueryList({
    queryId: 'getPRINTLIST',
    version: '00001',
    params: {}
  }).then((res: any) => {
    state.PRINTLIST = res.data
  })
}

function InputNumber() {
  if (state.createBoxForm != 'KG') {
    let arrs2 = state.createBoxForm.TrueGG.toString().split('*')
    arrs2[0] = arrs2[0].replace('mm', '')
    arrs2[1] = arrs2[1].replace('m', '')
    arrs2[0] = cals.div(arrs2[0], 1000).toNumber()
    arrs2[1] = arrs2[1] ? arrs2[1] : 0
    state.createBoxForm.MATERIALCREATEQUANTITY = cals.mul(arrs2[1], arrs2[0]).toNumber() //单个标签数量
    let sums = cals
      .div(state.createBoxForm.RECEIVEDQUANTITY2, state.createBoxForm.MATERIALCREATEQUANTITY)
      .toNumber()
    state.createBoxForm.MATERIALQUANTITY = Math.ceil(sums) //标签个数
  }
  if (Number(state.createBoxForm.MATERIALQUANTITY) >= 0) {
    state.createBoxForm.RECEIVEDQUANTITY2 =
      cals
        .mul(state.createBoxForm.MATERIALCREATEQUANTITY, state.createBoxForm.MATERIALQUANTITY)
        .toNumber() || 0
    state.createBoxForm.MINUSQTY =
      cals
        .subMore(
          state.createBoxForm.REQUESTQUANTITY,
          state.createBoxForm.RECEIVEDQUANTITY,
          state.createBoxForm.RECEIVEDQUANTITY2
        )
        .toNumber() || 0
    updateFnumber()
  }
}

function InputNumber2() {
  if (Number(state.createBoxForm.MATERIALCREATEQUANTITY) >= 0) {
    state.createBoxForm.RECEIVEDQUANTITY2 = cals
      .mul(state.createBoxForm.MATERIALCREATEQUANTITY, state.createBoxForm.MATERIALQUANTITY)
      .toNumber()
    state.createBoxForm.MINUSQTY = cals
      .subMore(
        state.createBoxForm.REQUESTQUANTITY,
        state.createBoxForm.RECEIVEDQUANTITY,
        state.createBoxForm.RECEIVEDQUANTITY2
      )
      .toNumber()
    updateFnumber()
  }
}

function InputNumber3() {
  if (Number(state.createBoxForm.MATERIALQUANTITY) >= 0) {
    console.log(state.createBoxForm.MATERIALCREATEQUANTITY, state.createBoxForm.MATERIALQUANTITY)
    state.createBoxForm.RECEIVEDQUANTITY2 = cals
      .mul(state.createBoxForm.MATERIALCREATEQUANTITY, state.createBoxForm.MATERIALQUANTITY)
      .toNumber()
    state.createBoxForm.MINUSQTY = cals
      .subMore(
        state.createBoxForm.REQUESTQUANTITY,
        state.createBoxForm.RECEIVEDQUANTITY,
        state.createBoxForm.RECEIVEDQUANTITY2
      )
      .toNumber()
    updateFnumber()
  }
}

function nowDate(time: any) {
  var year = time.getFullYear() // 年
  var month = (time.getMonth() + 1).toString().padStart(2, '0') // 月
  var date = time.getDate().toString().padStart(2, '0') // 日
  var hour = time.getHours().toString().padStart(2, '0') // 时
  var minute = time.getMinutes().toString().padStart(2, '0') // 分
  var second = time.getSeconds().toString().padStart(2, '0') // 秒
  return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second
}

function print() {
  if (state.PRINTNAME == null || state.PRINTNAME == '') {
    ElMessageBox.alert('请选择打印机', {
      confirmButtonText: 'OK'
    })
    return
  }
  if (state.MATERIALPACKINGLIST.length == 0) {
    ElMessageBox.alert('打印清单为空', {
      confirmButtonText: 'OK'
    })
    return
  }
  let PRINT = {
    LIST: state.MATERIALPACKINGLIST,
    PRINTNAME: state.PRINTNAME,
    USER: localStorage.get('userId')
  }
  state.button_print = true
  state.loadings = true
  printLabel(PRINT)
    .then((res: any) => {
      console.log('PRINT', res)
    })
    .catch(() => {
      state.button_print = false
      state.loadings = false
    })
  state.button_print = false
  state.loadings = false
  ElMessageBox.alert('标签打印成功', {
    confirmButtonText: 'OK'
  })
}

function getMaterialUnit() {
  getQueryList({
    queryId: 'GetMaterialUnit',
    version: '00001',
    params: {
      SITENAME: 'SDK'
    } as any
  }).then((res: any) => {
    state.UnitList = res.data
  })
}

function createBox(row: any) {
  if (row.MAKEDATE == null || row.MAKEDATE == '') {
    ElMessageBox.alert('制造日期不能为空', {
      confirmButtonText: 'OK'
    })
    return
  }
  if (row.ERPFACTORY == null || row.ERPFACTORY == '') {
    ElMessageBox.alert('组织不能为空', {
      confirmButtonText: 'OK'
    })
    return
  }
  if (row.ERPLOCATION == null || row.ERPLOCATION == '') {
    ElMessageBox.alert('仓库不能为空', {
      confirmButtonText: 'OK'
    })
    return
  }
  state.boxDrawer = true
  state.createBoxForm = row
  if (row.MATERIALSPECNAME.startsWith('3') || row.MATERIALSPECNAME.startsWith('4')) {
    state.createBoxForm.TrueGG = row.SPECNAME
  } else {
    state.createBoxForm.TrueGG = row.DESCRIPTION
  }

  state.createBoxForm.Remark = row.REMARK
  state.createBoxForm.MINUSQTY = row.MINUSQTY
  state.createBoxForm.RECEIVEDQUANTITY2 = 0
  state.createBoxForm.MATERIALQUANTITY = 0
  state.createBoxForm.MATERIALCREATEQUANTITY = 0
  state.createBoxForm.FUNIT = row.FUNIT
  if (row.FUNIT == '' || row.FUNIT == null) {
    state.unitAble = false
  } else {
    state.unitAble = true
  }
  // console.log(parseFloat(row.REQUESTQUANTITY), parseFloat(row.RECEIVEDQUANTITY))
  state.createBoxForm.MINUSQTY = cals.sub(row.REQUESTQUANTITY, row.RECEIVEDQUANTITY).toNumber()
  console.log(row)
}

function deleteBox(row) {
  console.log(state.createBoxForm)
  state.loadings = true
  state.button_state = true
  state.createBoxForm.MAKEDATE = msToDate(state.createBoxForm.MAKEDATE).hasTime
  console.log(state.createBoxForm.MAKEDATE)
  state.createBoxForm = row
  DeleteTrackOutBox({
    materialreceiveAct: state.createBoxForm,
    user: localStorage.get('userId')
  })
    .then((res: any) => {
      if (res.success) {
        ElMessageBox.alert('解绑成功', '提醒框', {
          confirmButtonText: 'OK'
        })
        handleQuery()
        state.InputState = false
        state.loadings = false
        state.button_state = false
      } else {
        ElMessageBox.alert('解绑失败：' + res.data.message, '提醒框', {
          confirmButtonText: 'OK'
        })
        state.loadings = false
        state.button_state = false
      }
    })
    .catch((err: any) => {
      ElMessageBox.alert('解绑失败' + err, '提醒框', {
        confirmButtonText: 'OK'
      })
      state.loadings = false
      state.button_state = false
    })
  state.loadings = false
  state.button_state = false
}

// 删除一行的标签
function deleteThisBox(row) {
  console.log(row)
  state.loadings = true
  state.button_state = true
  DeleteTrackOutThisBox({
    materialreceiveAct: row,
    user: localStorage.get('userId')
  })
    .then((res: any) => {
      if (res.success) {
        ElMessageBox.alert('解绑成功', '提醒框', {
          confirmButtonText: 'OK'
        })
        handleQuery()
        state.InputState = false
        state.loadings = false
        state.button_state = false
      } else {
        ElMessageBox.alert('解绑失败：' + res.data.message, '提醒框', {
          confirmButtonText: 'OK'
        })
        state.loadings = false
        state.button_state = false
      }
    })
    .catch((err: any) => {
      ElMessageBox.alert('解绑失败' + err, '提醒框', {
        confirmButtonText: 'OK'
      })
      state.loadings = false
      state.button_state = false
    })
  state.loadings = false
  state.button_state = false
}

// 创建box
function commitBox() {
  if (state.createBoxForm.MINUSQTY < 0) {
    ElMessageBox.alert('创建失败,剩余数量不足以创建批次')
    return
  }
  state.button_loading2 = true
  state.button_state2 = true
  var getTime = new Date().getTime() // 获取到当前时间戳
  state.createBoxForm.MAKEDATE = msToDate(state.createBoxForm.MAKEDATE).hasTime
  CreateBox({
    siteName: 'SDK',
    materialreceiveAct: state.createBoxForm,
    user: localStorage.get('userId'),
    receiveRequestName: state.queryParams.params.RECEIVEREQUESTNAME
  })
    .then((res: any) => {
      state.MATERIALPACKINGLISTS = ''
      if (res.success) {
        state.MATERIALPACKINGLISTS = res.resultObj.materialreceiveAct
        state.createBoxForm.RECEIVEDQUANTITY = cals
          .add(state.createBoxForm.RECEIVEDQUANTITY2, state.createBoxForm.RECEIVEDQUANTITY)
          .toNumber()
        ElMessageBox.alert('创建成功', '提醒框', {
          confirmButtonText: 'OK'
        })
        handleQuery()
        state.InputState = false
        state.button_loading2 = false
        state.button_state2 = false
      } else {
        ElMessageBox.alert('创建失败：' + res.message, '提醒框', {
          confirmButtonText: 'OK'
        })
        state.button_loading2 = false
        state.button_state2 = false
      }
    })
    .catch((err: any) => {
      ElMessageBox.alert('创建失败' + err, '提醒框', {
        confirmButtonText: 'OK'
      })
      state.button_loading2 = false
      state.button_state2 = false
    })
  state.loadings = false
}

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

// 查询
function handleQuery() {
  // state.queryParams.queryId = 'GetInvoiceDetailInformationRow'
  // state.queryParams.version = 'Z10006_SAP'
  // state.queryParams.queryId = 'GetPackingRow'
  // state.queryParams.version = 'xh002'
  state.InputState = true
  state.MATERIALRECEIVEACT = []
  state.MATERIALPACKINGLIST = []
  state.queryParams.params.SITENAME = 'SDK'
  state.queryParams.params.MATERIALSPECNAME = ''
  // 提醒
  if (state.queryParams.params.RECEIVEREQUESTNAME == '') {
    ElMessageBox.alert('输入查询条件', '提醒框', {
      confirmButtonText: 'OK'
    })
    return
  }
  getStoreDetail(state.queryParams).then((res: any)=> {
    if (res.resultObj) {
      state.MATERIALPACKINGLIST = res.resultObj.storeCharge
      state.MATERIALRECEIVEACT = res.resultObj.storeDetail
      if (state.MATERIALPACKINGLISTS != '') {
        for (const element of state.MATERIALRECEIVEACT) {
          if (
            element.MATERIALSPECNAME == state.MATERIALPACKINGLISTS.MATERIALSPECNAME &&
            element.DESC_CN == state.MATERIALPACKINGLISTS.DESC_CN
          ) {
            element.ERPLOCATION = state.MATERIALPACKINGLISTS.ERPLOCATION
            element.ERPLOCATION2 = state.MATERIALPACKINGLISTS.ERPLOCATION2
            element.LOCATIONNAME = state.MATERIALPACKINGLISTS.LOCATIONNAME
            element.LOCATIONNAME2 = state.MATERIALPACKINGLISTS.LOCATIONNAME2
          }
        }
        state.MATERIALPACKINGLISTS
      }
    } else {
      ElMessageBox.alert(res.message, '提醒框', {
        confirmButtonText: 'OK'
      })
    }
  }).catch((error: any) => {
    ElMessageBox.alert(error.message, '提醒框', {
      confirmButtonText: 'OK'
    })
  })
}

async function sendToERP() {
  state.button_state = true
  state.button_loading = true
  console.log(state.button_state)
  console.log(state.commitDate)
  if (state.commitDate == null) {
    ElMessageBox.alert('过账时间不可清空', {
      confirmButtonText: 'OK'
    })
    state.loadings = false
    state.button_state = false
    state.button_loading = false
    return
  }
  getOpCode({
    opcode: state.OpCode,
    user: localStorage.get('userId')
  }).then((res: any) => {
    console.log(res.resultObj)
    state.OpCode = res.resultObj
    if (state.MATERIALPACKINGLIST == null || state.MATERIALPACKINGLIST.length < 1) {
      ElMessageBox.alert('待提交信息不能为空', {
        confirmButtonText: 'OK'
      })
      state.loadings = false
      state.button_state = false
      state.button_loading = false
      return
    }
    PurInSendERPByCharge({
      // materialreceiveAct: state.MATERIALPACKINGLIST[0],
      siteName: 'SDK',
      receiveRequestName: state.queryParams.params.RECEIVEREQUESTNAME,
      user: localStorage.get('userId'),
      commitDate: state.commitDate,
      opcode: state.OpCode
    })
      .then((res: any) => {
        console.log(res)
        if (res.success) {
          ;(state.OpCode = ''),
            ElMessageBox.alert('入库成功', '提醒框', {
              confirmButtonText: 'OK'
            })
          handleQuery()
          state.InputState = false
          state.loadings = false
          state.button_state = false
          state.button_loading = false
        } else {
          ElMessageBox.alert('入库失败：' + res.message, '提醒框', {
            confirmButtonText: 'OK'
          })
          state.loadings = false
          state.button_state = false
          state.button_loading = false
        }
      })
      .catch((err: any) => {
        ElMessageBox.alert('入库失败' + err, '提醒框', {
          confirmButtonText: 'OK'
        })
        state.loadings = false
        state.button_state = false
        state.button_loading = false
      })
    state.loadings = false
    state.button_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'
    })
  }
  state.queryParams.queryId = 'GetPackingRow'
  state.queryParams.version = 'xh002'
  state.queryParams.params.SITENAME = 'SDK'
  state.queryParams.params.MATERIALSPECNAME = row.MATERIALSPECNAME
  state.MATERIALPACKINGLIST = []
  getQueryList(state.queryParams)
    .then((res: any) => {
      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
    this.locatioNFilter('')
  })
}

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">
.info-table {
  width: 100%;
  min-height: 100px;
  height: 260px;
}

.charge-table {
  width: 100%;
  min-height: 100px;
}
</style>
