<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="ERPFACTORY">
              <el-select
                filterable
                v-model="queryParams.params.ERPFACTORY"
                placeholder="下拉选择组织"
                @change="changeFac"
                size="small"
              >
                <el-option
                  v-for="item in ERPFactoryList"
                  :key="item.ERPFACTORY"
                  :label="item.DESCRIPTION"
                  :value="item.ERPFACTORY"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="库存仓库" prop="ERPLOCATION">
              <el-select
                size="small"
                filterable
                v-model="queryParams.params.ERPLOCATION"
                placeholder="下拉选择仓库"
                @change="changeERPLocation"
              >
                <el-option
                  v-for="item in ERPLocationList"
                  :key="item.ENUMVALUE"
                  :label="item.DESCRIPTION"
                  :value="item.ENUMVALUE"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="库存货位" prop="LOCATIONNAME">
              <el-select
                size="small"
                filterable
                :remote-method="handleInput"
                v-model="queryParams.params.LOCATIONNAME"
                placeholder="下拉选择货位"
              >
                <el-option
                  v-for="item in LocationList"
                  :key="item.storageName"
                  :label="item.storageName"
                  :value="item.storageName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物料编号" prop="params.MATERIALSPECNAME">
              <el-Input
                v-model="queryParams.params.MATERIALSPECNAME"
                clearable
                placeholder="请输入物料编号"
              />
            </el-form-item> </el-col
          ><el-col :span="6">
            <el-form-item label="批次" prop="params.CHARGE">
              <el-Input
                v-model="queryParams.params.CHARGE"
                clearable
                placeholder="请输入批次"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="品名" prop="queryParams.params">
              <el-Input v-model="queryParams.params.DESC_CN" placeholder="品名" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注" prop="queryParams.REMARK">
              <el-Input v-model="queryParams.params.REMARK" placeholder="备注" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务" prop="queryParams.SALESPERSON">
              <el-Input v-model="queryParams.params.SALESPERSON" placeholder="业务" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="SDK规格" prop="queryParams.SPECNAME">
              <el-Input v-model="queryParams.params.SPECNAME" placeholder="SDK规格" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" @click="queryInfo">搜索</el-button>
      </div>
    </el-row>
    <!-- 左右结构 -->
    <div class="vue-element-page-table">
      <el-row>
        <el-col :span="24">
          <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>
                <el-tag size="large" style="margin-left: 30px;" type="success">累计个数：{{ GSSUM }}</el-tag>
                <el-tag size="large" style="margin-left: 20px;" type="success">累计数量：{{ BQSUM }}</el-tag> 
              </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="materialTableConfig.column" @updateList="updateList" />
                </el-popover>
              </div>
            </div>
            <!-- show-summary
              :summary-method="getSummaries" -->
            <el-table
              border
              v-loading="loading"
              :data="state.MaterialPackingList"
              highlight-current-row
              :row-key="getRKey"
              ref="tableRef"
              :height="tableHeight"
              @cell-mouse-enter="handleCellMouseEnter"
              style="width: 100%"
              :default-sort="{ prop: 'MATERIALQUANTITY', order: 'descending' }"
              @selection-change="handleSelectionChange"
            >
              <el-table-column :reserve-selection="true" type="selection" width="40" />
              <el-table-column type="index" width="50" label="序号"> </el-table-column>
              <template v-for="(col, index) in materialTableConfig.column" :key="index">
                <el-table-column
                  v-if="!col.hide"
                  :label="col.header"
                  :prop="col.field"
                  show-overflow-tooltip
                  :sort-orders="['descending', 'ascending']"
                  :sortable="true"
                  align="center"
                >
                  <template #default="scope">
                    <span v-if="col.field === 'status'">
                      <span v-if="scope.row[col.field]" class="table-status-active">启用</span>
                      <span v-else class="table-status-inActive">禁用</span>
                    </span>
                    <el-Input
                      v-else-if="col.field === 'SPLITQUANTITY'"
                      v-model="scope.row[col.field]"
                      placeholder="请输入拆分数量"
                      clearable
                      @input="changeNum(scope.row)"
                    />
                    <span v-else>{{ 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"
              :page-sizes="[20, 50, 100, 200,500,1000]"
              @pagination="handleQuery"
            />
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="vue-element-page-table">
      <el-row class="page-search" align="middle" :gutter="20">
        <el-col :span="4" style="padding-top: 12px">
            <el-form-item label="目的组织" prop="ERPFACTORY">
              <el-select
                filterable
                v-model="queryParams.params.destinationErpFactory"
                placeholder="下拉选择组织"
                size="small"
                @change="changeSpcERPFactory"
              >
                <el-option
                  v-for="item in state.spcERPFactoryList"
                  :key="item.ERPFACTORY"
                  :label="item.DESCRIPTION"
                  :value="item.ERPFACTORY"
                />
              </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="4" style="padding-top: 12px">
          <el-form-item label="目的仓库" prop="ERPLOCATION">
            <el-select
              size="small"
              filterable
              @change="changeLocW"
              @blur="focusLocW"
              v-model="desParams.params.ERPLOCATION"
              placeholder="下拉选择仓库"
            >
              <el-option
                v-for="item in locDecList1"
                :key="item.ENUMVALUE"
                :label="item.DESCRIPTION"
                :value="item.ENUMVALUE"
              />
            </el-select>
            <!-- <el-cascader style="wid" @change="changeCascade" ref="warehouseRef" v-model="state.StorageSelect" :options="state.StorageSelectList" clearable filterable :props="props" /> -->
          </el-form-item>
        </el-col>
        <el-col :span="4" style="padding-top: 12px">
          <el-form-item label="目的货位" prop="LOCATIONNAME">
            <el-select
              size="small"
              filterable
              v-model="desParams.params.LOCATIONNAME"
              default-first-option
              placeholder="下拉选择货位"
              :filter-method="getlocDec"
            >
              <el-option
                v-for="item in locDecList2"
                :key="item.VALUE"
                :label="item.LABEL"
                :value="item.VALUE"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4" style="padding-top: 12px">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="REMARK" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
        <el-col :span="4" style="padding-top: 12px" :offset="4">
          <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>
        </el-col>
        <el-col :span="2">
          <div class="page-search-btns" style="float: right">
            <el-button
              v-loading="state.loading2"
              type="primary"
              @click="submit"
              :disabled="state.Button_state"
              >确定</el-button
            >
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

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

<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance, nextTick } from 'vue'
import { ElForm, ElMessageBox, ElTable, CascaderProps } from 'element-plus'
import { getQueryList, getQueryPageList, BpelEvent } from '@/api/common'
import { CommitMove } from '@/api/StockIn'
import { h } from 'vue'
import type { VNode } from 'vue'

import { useRouter } from 'vue-router'
import { IFTRUE } from '@/utils/CommonUtil'
import { bTableHeight } from '../../../composables/calcTableHeight'
import { getORG } from '@/api/auth'
import { cals } from '@/utils/cal'
import { search } from '@/api/wareHouse'
// import request from '@/utils/request'

const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(330)
const queryFormRef = ref(ElForm)
const { proxy }: any = getCurrentInstance()
const tableRef = ref<InstanceType<typeof ElTable>>()

const router = useRouter()
const warehouseRef = ref()
const materialTableConfig = ref({
  loading: false,
  column: [] as any,
  data: []
})
const state = reactive({
  REMARK:'',
  BQSUM: 0,
  GSSUM: 0,
  commitDate: '',
  ERPFactoryList: [] as any, // 组织
  ERPLocationList: [] as any, //仓库
  LocationList: [] as any, //货位
  spcERPFactoryList: [] as any, 
  rsa: '',
  Button_state: false,
  total: 0,
  total2: 0,
  BoxList: [] as any,
  firstLocation: '',
  MaterialPackingList: [] as any,
  MaterialPackingUsername: [] as any,
  Storage1Select: [] as any,
  Storage1SelectList: [] as any,
  StorageSelect: [] as any,
  StorageSelectList: [] as any,
  locDecList1: [] as any,
  locDecList2: [] as any,
  orgNo:"",
  queryParams: {
    queryId: '',
    version: '',
    params: {
      SITENAME: 'SDK',
      MATERIALSPECNAME: '',
      ERPLOCATION: '',
      ERPFACTORY: '',
      destinationErpFactory: '',
      LOCATIONNAME: '',
      CHARGE: '',
      DESC_CN:'',
      REMARK:'',
      SALESPERSON: '',
      SPECNAME:''
    },
    pageNum: 1,
    pageSize: 10
  },
  desParams: {
    queryId: '',
    version: '',
    params: {
      SITENAME: 'SDK',
      LOCATIONNAME: '',
      ERPLOCATION: ''
    },
    pageNum: 1,
    pageSize: 10
  },
  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: 'ModifyLocation',
      LANGUAGE: 'Chinese'
    },
    body: {
      BOXLIST: [] as any,
      SITENAME: 'SDK',
      AREANAME: '',
      LOCATIONNAME: '',
      ERPLOCATION: ''
    }
  },
  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,
  locDecListAll: [] as any,
  queryParamsERPFactory: {
    queryId: 'GetErpFactoryList',
    version: 'WEB00001',
    params: {
      SITENAME: localStorage.getItem('siteName') || 'SDK'
    },
    pageNum: 1,
    pageSize: 10
  },
  queryParamsERPLocation: {
    queryId: 'GetErpLocationList2',
    version: 'WEB00001',
    params: {
      SITENAME: localStorage.getItem('siteName') || 'SDK',
      ERPFACTORYNAME: ''
    },
    pageNum: 1,
    pageSize: 10
  },
  queryParamsLocation: {
    queryId: 'GetLocationList',
    version: 'WEB00001',
    params: {
      SITENAME: localStorage.getItem('siteName') || 'SDK',
      ERPLOCATION: ''
    },
    pageNum: 1,
    pageSize: 10
  }
})
const {
  REMARK,
  GSSUM,
  BQSUM,
  Button_state,
  StorageSelectList,
  StorageSelect,
  ERPFactoryList,
  ERPLocationList,
  LocationList,
  desParams,
  queryParams,
  loading3,
  loading,
  column,
  column1,
  column2,
  locDecList1,
  locDecList2,
  orgNo
} = 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
  materialTableConfig.value.column = [
    { header: '工厂', field: 'SITENAME', hide: true },
    { header: '标签编号', field: 'MATERIALPACKINGNAME', hide: false },
    { header: '批号', field: 'CHARGE', hide: false },
    { header: '物料编号', field: 'MATERIALSPECNAME', hide: false },
    { header: '品名', field: 'DESC_CN', hide: false },
    { header: '数量', field: 'MATERIALQUANTITY', hide: false },
    { header: '拆分数量', field: 'SPLITQUANTITY', hide: false,with:300 },
    { header: '单位', field: 'FNAME', hide: false },
    { header: 'SDK规格', field: 'SPECNAME', hide: false },
    { header: 'Hold 状态', field: 'HOLDSTATE', hide: false },
    { header: '品质状态', field: 'OQARESULTSTATE', hide: false },
    { header: '品质结果', field: 'PACKINGGRADE', hide: false },
    { header: '入库日期', field: 'SHIPTIME', hide: false },
    { header: '仓库编码', field: 'ERPLOCATION', hide: false },
    { header: '仓库名称', field: 'ERPLOCATIONDESC', hide: false },
    { header: '货位编码', field: 'LOCATIONNAME', hide: false },
    { header: '货位名称', field: 'LOCATIONNAMEDESC', hide: false },
    { header: '业务', field: 'SALESPERSON', hide: false },
    { header: '备注', field: 'REMARK', hide: false }
  ]
  let pwd: any = localStorage.getItem('remeberPwd')
  if(pwd) {
    state.orgNo = JSON.parse(pwd).orgNo;
    state.queryParams.params.ERPFACTORY = state.orgNo
  }
  
  // state.queryParams.params.ERPFACTORY = JSON.parse(pwd).orgNo;
  // state.queryParamsERPLocation.params.ERPFACTORYNAME = JSON.parse(pwd).orgNo;
  ERPFactoryQuery()
  // ERPLocationQuery()
  queryInfo()

  updateTableHeight()
  window.addEventListener('resize', handleResize)
  // getStorageSpecLocationList()
})

function handleInput(val: any) {
  let index = [1, 3, 4, 7, 8]
  if (index.indexOf(val.length) > -1) {
    state.LocationList = []
    search({
      storageName: val,
      orgNo: JSON.parse(localStorage.getItem('orgNo'))
    }).then((res:any) => {
      if (res.resultObj) {
        state.LocationList = res.resultObj
      } else {
        proxy.$ElMessage.warning(res.message);
      }
    })
  }
}

function getRKey(row: any) {
  // console.log(row.CHARGE)
  return row.CHARGE
}

const getSummaries = (param: any) => {
  const { columns, data } = param
  console.log(columns, data)
  const sums: (string | VNode)[] = []
  columns.forEach((column: any, index: any) => {
    if (index === 0) {
      sums[index] = h('div', { style: { textDecoration: 'underline' } }, ['合计'])
      return
    }
    console.log(column.property)
    if (column.property == 'MATERIALQUANTITY') {
      const values = data.map((item: any) => Number(item[column.property]))
      if (!values.every((value: any) => Number.isNaN(value))) {
        sums[index] = `${values.reduce((prev: any, curr: any) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)}`
      } else {
        console.log(index)
        if (index == 2) {
          sums[index] = ''
        } else {
          sums[index] = ''
        }
      }
    }
  })

  return sums
}

function handleCellMouseEnter(row: any, column: any, cell: any, event: any) {
  // console.log(row, column, cell, event);
  if (column.type === 'selection' && event.shiftKey) {
    // 且按着 shift 键 则勾选这一行
    tableRef.value!.toggleRowSelection(row, true)
  }
}

function handleOuter2Click() {
  Storage2List(state.queryParams.params.ERPLOCATION)
}
async function Storage2List(firstLocation: any) {
  try {
    try {
      state.queryParams.queryId = 'Get2stAreaName'
      state.queryParams.version = '00003'
      state.queryParams.params.ERPLOCATION = firstLocation
      const res = await getQueryList(state.queryParams)
      state.Storage1SelectList = res.data
      if (state.Storage1SelectList.length == 0) {
        proxy.$ElMessage.info('目的货位为空!')
        return
      }
    } 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 或进行其他恢复操作
  }
}
function changeFac(e: any) {
   console.log(e)
  state.queryParams.params.ERPLOCATION = ''
  state.queryParamsERPLocation.params.ERPFACTORYNAME = e

  state.queryParams.params.destinationErpFactory = ''
  state.queryParams.params.destinationErpFactory = e
  state.spcERPFactoryList = [] as any
  ERPLocationQuery()
  if(e == "1010" || e == "1020" || e == "1200") {
    state.spcERPFactoryList =  state.ERPFactoryList.filter((item: any) => 
      (item.ERPFACTORY === "1010" || item.ERPFACTORY === "1020" || item.ERPFACTORY === "1200")
    )
  }else {
    state.spcERPFactoryList =  state.ERPFactoryList.filter((item: any) =>
      (item.ERPFACTORY === e)
    )
  }
  changeSpcERPFactory(e)
}
function changeERPLocation(e: any) {
  // console.log(e)
  state.queryParams.params.LOCATIONNAME = ''
  state.queryParamsLocation.params.ERPLOCATION = e
  // LocationQuery()
}
//货位查询
function LocationQuery() {
  getQueryList(state.queryParamsLocation)
    .then((res: any) => {
      state.LocationList = res.data
      state.LocationList.unshift({
        ENUMVALUE: ''
      })
    })
    .catch(() => {})
}
//ERP工厂查询
function ERPFactoryQuery() {
  getORG({ orgNo: null })
    .then((res: any) => {
      state.ERPFactoryList = res.resultObj
      //state.spcERPFactoryList = res.resultObj
      state.ERPFactoryList.unshift({
        ERPFACTORY: ''
      })
      if(state.queryParams.params.ERPFACTORY == "1010" || state.queryParams.params.ERPFACTORY == "1020" || state.queryParams.params.ERPFACTORY == "1200") {
        state.spcERPFactoryList =  state.ERPFactoryList.filter((item: any) =>
          (item.ERPFACTORY === "1010" || item.ERPFACTORY === "1020" || item.ERPFACTORY === "1200")
        )
      }else {
        state.spcERPFactoryList =  state.ERPFactoryList.filter((item: any) =>
          (item.ERPFACTORY === state.queryParams.params.ERPFACTORY)
        )
      }
      changeSpcERPFactory(state.queryParams.params.ERPFACTORY)
      state.queryParams.params.destinationErpFactory = state.queryParams.params.ERPFACTORY
    })
    .catch(() => {})
}
//ERP库位查询
function ERPLocationQuery() {
  getQueryList(state.queryParamsERPLocation)
    .then((res: any) => {
      state.ERPLocationList = res.data
      state.ERPLocationList.unshift({
        ENUMVALUE: ''
      })
    })
    .catch(() => {})
}
// 更新列
const updateList = (col: any) => {
  materialTableConfig.value.column = col
}
function queryInfo() {
  state.queryParams.pageNum = 1
  if(!state.queryParams.params.ERPFACTORY) {
    ElMessageBox.alert('请选择库存组织！', '提醒框', {
      confirmButtonText: 'OK'
    })
  }

  handleQuery()
}
async function handleQuery() {
  state.MaterialPackingUsername = []
  // if (state.queryParams.params.ERPFACTORY) {
  state.queryParams.queryId = 'GetPackingNo'
  state.queryParams.version = 'WP0010'
  state.MoveLibraryList = []
  await getQueryPageList(state.queryParams)
    .then((res: any) => {
      // console.log(res)
      if (res.data.list.length == 0) {
        state.MaterialPackingList = []
        state.total = 0
        ElMessageBox.alert('查无数据！', '提醒框', {
          confirmButtonText: 'OK'
        })
      } else {
        let arr = [...res.data.list]
        state.MaterialPackingList = arr
        arr.map((val:any)=> val.SPLITQUANTITY = val.MATERIALQUANTITY)
        state.MaterialPackingList = arr
        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 changeCascade(e: any) {
  console.log(888, e)
}
const props: CascaderProps = {
  lazy: true,
  async lazyLoad(node, resolve) {
    // console.log(66,node, resolve)
    const { level, value } = node
    if (state.column4.length > 0 && level) {
      const childrenRes = await getQueryList({
        queryId: 'Get2stAreaName',
        version: '00002',
        params: {
          ERPLOCATION: value,
          SITENAME: 'SDK'
        },
        pageNum: 1,
        pageSize: 10
      })
      state.locDecList2 = childrenRes.data || []
      const nodes = state.locDecList2.map((item: any) => ({
        value: item.ERPLOCATION,
        label: item.ERPLOCATION,
        leaf: level < 3
      }))
      resolve(nodes)
    }
  }
}
function resetQuery() {
  queryFormRef.value.resetFields()
  handleQuery()
}
function focusLocW() {
  // console.log(111,state.column4)
  if (!state.column4.length) {
    ElMessageBox.alert('请选择标签信息', '提醒框', {
      confirmButtonText: 'OK'
    })
    return
  }
}
async function changeLocW() {
  state.desParams.params.LOCATIONNAME = ''
  await getQueryList({
    queryId: 'GetLocationForCreatePO',
    version: '00001',
    params: {
      ERPLOCATION: state.desParams.params.ERPLOCATION,
      SITENAME: 'SDK'
    }
  }).then((res: any) => {
    state.locDecListAll = res.data
    getlocDec('')
  })
  // state.locDecList2 = childrenRes
  // state.locDecListAll = childrenRes/
  // getlocDec('')
  // console.log(state.locDecListAll)
}
function getlocDec(query: any) {
  // console.log(query)
  let arr = state.locDecListAll.filter((item: any) => {
    return item.LABEL.includes(query) || item.VALUE.includes(query)
  })
  // console.log(arr)
  if (arr.length > 50) {
    state.locDecList2 = arr.slice(0, 50)
  } else {
    state.locDecList2 = arr
  }
}
function changeNum(row: any) {
  console.log(row)
  let sumList = [...state.column4];
  state.BQSUM = 0
  state.BQSUM = sumList.reduce((accumulator, currentValue) => {
    console.log(accumulator, currentValue)
     return (cals.add(accumulator,currentValue.SPLITQUANTITY)).toNumber();
  }, 0)
}
function handleSelectionChange(selection: any) {
  console.log(selection)
  state.column4 = selection
  let sumList = [...state.column4];
  state.BQSUM = 0
  state.BQSUM = sumList.reduce((accumulator, currentValue) => {
    console.log(accumulator, currentValue)
     return (cals.add(accumulator,currentValue.SPLITQUANTITY)).toNumber();
  }, 0)
  state.GSSUM = sumList.length
 
  if (state.column4.length > 0) {
    StorageList(state.column4[0].ERPFACTORY)
  }
  state.locDecList1 = []
  state.locDecList2 = []
  // else {
  //   ElMessageBox.alert('请选择标签信息', '提醒框', {
  //     confirmButtonText: 'OK'
  //   })
  // }
  async function StorageList(firstLocation: any) {
    try {
      try {
        const res = await getQueryList({
          queryId: 'GetErpLocationList',
          version: 'WEB00001',
          params: {
            ERPFACTORYNAME: firstLocation,
            SITENAME: 'SDK'
          },
          pageNum: 1,
          pageSize: 10
        })
        state.locDecList1 = res.data
        if (state.locDecList1.length == 0) {
          proxy.$ElMessage.info('目的仓库为空!')
          return
        }
        const nodes = state.locDecList1.map((item: any) => ({
          value: item.ENUMVALUE,
          label: item.DESCRIPTION,
          leaf: 0
        }))
        state.StorageSelectList = nodes
      } 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 或进行其他恢复操作
    }
  }
}
async function LeftIn() {
  state.MaterialPackingUsername = state.column4
  console.log(state.MaterialPackingUsername)
}
function handleOuterClick() {}
// function handle() {
//   state.queryParams.queryId = 'GetPackingNo'
//   state.queryParams.version = 'WP009'
//   // state.queryParams.params.AREANAME = state.StorageSelect[0] || ''
//   state.queryParams.params.LOCATIONNAME = state.StorageSelect[0] || ''
//   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.SHIPREQUESTNAME
//   // state.RightqueryParams.params.SHIPREQUESTDETAILNAME = row.SHIPREQUESTDETAILNAME
//   getQueryList(state.RightqueryParams).then((res: any) => {
//     state.MaterialPackingUsername = res.data
//   })
//   //查询库位需要
//   // state.firstLocation = row.ERPLOCATION
// }

async function handleReserve() {
  state.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[0]
    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
      })
      .catch((error: any) => {
        ElMessageBox.alert(error, '提醒框', {
          confirmButtonText: 'OK'
        })
        state.Button_state = false
      })
  } else {
    ElMessageBox.alert('请按照规范操作', '提醒框', {
      confirmButtonText: 'OK'
    })
    state.Button_state = false
  }
}
function splitOpen() {
  let BoxListInfo = JSON.parse(JSON.stringify(state.column4))
 
  
}
async function submit() {
  console.log(state.column4)
  if (state.commitDate == null) {
    ElMessageBox.alert('过账时间不可清空', {
      confirmButtonText: 'OK'
    })
    return
  }
  state.Button_state = true
  state.loading2 = true
  if (
    state.column4.length > 0 &&
    // state.desParams.params.LOCATIONNAME &&
    state.desParams.params.ERPLOCATION
  ) {
    // console.log("state.StorageSelect")
    // state.ChangeParams.body.LOCATIONNAME= state.desParams.params.LOCATIONNAME,
    // state.ChangeParams.body.ERPLOCATION= state.desParams.params.ERPLOCATION
    // // console.log(state.StorageSelect)
    // state.ChangeParams.body.BOXLIST = [];
    // for (let k = 0; k < state.column4.length; k++) {
    //   // 将 BOX 对象推送到 state.changeParams.body.BOXLIST 数组中
    //   let obj:any = {
    //     SITENAME : state.column4[k].SITENAME,
    //     MATERIALPACKINGNAME: state.column4[k].MATERIALPACKINGNAME,
    //     LOCATIONNAME: state.column4[k].LOCATIONNAME,
    //     LASTEVENTCOMMENT: "",
    //   }
    //   console.log('obj',obj)
    //   state.ChangeParams.body.BOXLIST.push(obj);
    // }

    // await BpelEvent(state.ChangeParams).then((res: any) => {
    //   if (IFTRUE(res)) {
    //     ElMessageBox.alert('货位移转完成', '提醒框', {
    //       confirmButtonText: 'OK',
    //     })
    //     handleQuery();
    //     state.Button_state = false
    //   } else {
    //     ElMessageBox.alert(res.data.RETURNCODE + '->' + res.data.RETURNMESSAGE, '', {
    //       confirmButtonText: 'OK',
    //     })
    //     handleQuery();
    //     state.Button_state = false
    //   }
    //   state.loading2 = false
    // }).catch((error: any) => {
    //   ElMessageBox.alert(error, '提醒框', {
    //     confirmButtonText: 'OK',
    //   })
    //   state.loading2 = false
    //   state.Button_state = false
    // })

    let BoxListInfo = JSON.parse(JSON.stringify(state.column4))
    // for (let k = 0; k < BoxListInfo.length; k++) {
    //   BoxListInfo[k].AIMERPLOCATION = state.desParams.params.ERPLOCATION
    //   BoxListInfo[k].AIMLOCATIONNAME = state.desParams.params.LOCATIONNAME
    //   BoxListInfo[k].AIMERPFACTORY = BoxListInfo[k].ERPFACTORY
    // }

    BoxListInfo.map((row: any) =>  {
      if(row.SPLITQUANTITY != row.MATERIALQUANTITY && row.SPLITQUANTITY) {
        let rowList = row.MATERIALPACKINGNAME?.split('|');
        console.log(rowList,rowList[rowList.length-1])
        // let splitNumber = (cals.sub(rowList[rowList.length-1],row.SPLITQUANTITY)).toNumber();
        let splitNumber = (cals.sub(row.MATERIALQUANTITY,row.SPLITQUANTITY)).toNumber();
        let rowNewList = [...rowList];
        //新标签1
        rowNewList[rowNewList.length-1] = splitNumber
        let splitPackingName1 = rowNewList.join('|');

        //新标签2
        rowNewList[rowNewList.length-1] = row.SPLITQUANTITY;
        let splitPackingName2 = rowNewList.join('|');
        // 拆分标签1
        row.MATERIALPACKINGNAME1 = splitPackingName1;
        row.MATERIALQUANTITY1 = splitNumber;
        // 拆分标签2
        row.MATERIALPACKINGNAME2 = splitPackingName2;
        row.MATERIALQUANTITY2 = Number(row.SPLITQUANTITY);
      }else {
        row.MATERIALPACKINGNAME1 = ""
        row.MATERIALQUANTITY1 = ""
        row.MATERIALPACKINGNAME2 = ""
        row.MATERIALQUANTITY2 = ""
      }

      row.AIMERPLOCATION = state.desParams.params.ERPLOCATION
      row.AIMLOCATIONNAME = state.desParams.params.LOCATIONNAME
      //row.AIMERPFACTORY = row.ERPFACTORY
      row.AIMERPFACTORY = state.queryParams.params.destinationErpFactory
    })

    console.log('BoxListInfo',BoxListInfo)

    CommitMove({
      body: BoxListInfo,
      time: state.commitDate,
      user: localStorage.getItem('userId'),
      remark:state.REMARK
    })
      .then((res: any) => {
        if (res?.success) {
          ElMessageBox.alert(res?.message, '提醒框', {
            confirmButtonText: 'OK'
          })
          if (state.column4.length > 0) {
            tableRef.value!.clearSelection()
            state.column4 = []
          }
          state.MaterialPackingList = []
          handleQuery()
          state.MaterialPackingUsername = []
        } else {
          ElMessageBox.alert(res?.message, '提醒框', {
            confirmButtonText: 'OK'
          })
        }

        state.loading2 = false
        state.Button_state = false
      })
      .catch((error: any) => {
        console.log(error)
        ElMessageBox.alert(error?.response?.data?.message || error?.message, '提醒框', {
          confirmButtonText: 'OK'
        })
        state.loading2 = false
        state.Button_state = false
      })
  } else {
    ElMessageBox.alert('请先选择需要移动的标签和仓库', '提醒框', {
      // if you want to disable its autofocus
      // autofocus: false,
      confirmButtonText: 'OK'
    })
    state.Button_state = false
    state.loading2 = false
  }
  // state.loading2 = false
  state.Button_state = false
}
/*

async function getStorageSpecLocationList() {
  let erpLocation = JSON.parse(localStorage.getItem('orgNo'));
  request({
    url: '/api/api/storage/getLocationNameForERPLocation',
    method: 'post',
    data: {
      erpLocation: erpLocation,
      SITENAME: 'SDK',
    },
  }).then((res: any) => {
    state.locDecListAll = res.resultObj;
  });
}
*/

function changeSpcERPFactory(e: any) {
  state.locDecList1 = [] as any
  getQueryList({
    queryId: 'GetErpLocationList',
    version: 'WEB00001',
    params: {
      SITENAME: localStorage.getItem('siteName') || 'SDK',
      ERPFACTORYNAME: e
    },
    pageNum: 1,
    pageSize: 10
  })
    .then((res: any) => {
      state.locDecList1 = res.data
     /* state.ERPLocationList.unshift({
        ENUMVALUE: ''
      })*/
    })
    .catch(() => {})
}
</script>

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