<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" 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
                v-model="queryParams.params.LOCATIONNAME"
                placeholder="下拉选择货位"
                :filter-method="getLocationList"
              >
                <el-option
                  v-for="item in LocationList"
                  :key="item.STORAGENAME"
                  :label="item.DESCRIPTION"
                  :value="item.STORAGENAME"
                />
              </el-select>
            </el-form-item>
<!--            <el-form-item label="库存货位" prop="LOCATIONNAME">
              <el-select
                size="small"
                filterable
                remote
                :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.LOCATIONNAME">
              <el-Input
                v-model="queryParams.params.LOCATIONNAME"
                placeholder="请输入库位名称"
                clearable
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="6">
            <el-form-item label="物料号" prop="params.MATERIALSPECNAME">
              <el-Input
                v-model="queryParams.params.MATERIALSPECNAME"
                placeholder="请输入物料号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="批次号" prop="params.MATERIALPACKINGNAME">
              <el-Input
                v-model="queryParams.params.MATERIALPACKINGNAME"
                placeholder="请输入批次号"
                clearable
              />
            </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="SDK规格" prop="queryParams.params.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">
      <div class="page-table-operate">
        <div class="page-table-title">
          <div class="page-table-title-left">
            <span>标签信息</span>
          </div>
        </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.boxList"
        highlight-current-row
        row-key="id"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :default-sort="{ prop: 'MATERIALQUANTITY', order: 'descending' }"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="50" label="序号"> </el-table-column>
        <!--        <template v-for="(col, index) in column" :key="index">-->
        <!--          <el-table-column v-if="!col.hide" :label="col.header" show-overflow-tooltip>-->
        <!--            <template #default="scope">-->
        <!--              <span>{{ scope.row[col.field] }}</span>-->
        <!--            </template>-->
        <!--          </el-table-column>-->
        <!--        </template>-->

        <template v-for="(col, index) in 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>
              <span v-else>{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <pagination
        v-if="total > 0"
        :total="total"
        v-model:pageNumTo="queryParams.pageNum"
        v-model:pageSizeTo="queryParams.pageSize"
        @pagination="handleQuery"
        :page-sizes="[20, 50, 100, 200,500,1000]"
      />
    </div>
    <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="6">
            <!--            <el-form-item label="目的货位" prop="portFormRefData.SEARCHTYPE">-->
            <!--              <el-cascader filterable @visible-change="handleOuterClick" v-model="state.StorageSelect"-->
            <!--                :options="state.StorageSelectList" :filter-method="getStorageSelectAll"-->
            <!--                :props="{ checkStrictly: true, label: 'DESCRIPTION', value: 'STORAGENAME' }" />-->
            <!--            </el-form-item>-->
            <el-select
              v-model="state.StorageSelect"
              placeholder="目的货位"
              style="width: 170px"
              prop="portFormRefData.SEARCHTYPE"
              @visible-change="handleOuterClick"
              :options="state.StorageSelectList"
              default-first-option
              filterable
              :filter-method="getStorageSelectAll"
            >
              <el-option
                v-for="item in state.StorageSelectList"
                :key="item.STORAGENAME"
                :label="item.DESCRIPTION"
                :value="item.STORAGENAME"
              />
            </el-select>
          </el-col>
          <el-col :span="6">
            <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="6">
            <el-form-item label="备注" prop="operateParams.date">
              <el-Input v-model="state.LASTEVENTCOMMENT" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-Input v-model="state.OpCode" :disabled="false" readonly />
          </el-col>
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button
          type="primary"
          v-loading.fullscreen.lock="state.loading2"
          @click="submit"
          :disabled="state.Button_state"
          >提交</el-button
        >
      </div>
    </el-row>
  </div>
</template>

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

<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance, nextTick } from 'vue'
import { ElForm, ElMessageBox, ElTable, valueEquals } from 'element-plus'
import { BpelEvent, getQueryPageList, getQueryList } from '@/api/common'
import { changeLocation } from '@/api/StockIn'
import { getOpCode } from '@/api/opcode'
import type { CascaderProps } from 'element-plus'
import { IFTRUE } from '@/utils/CommonUtil'
import { bTableHeight } from '../../../composables/calcTableHeight'
import { getORG } from '@/api/auth'
import { search } from '@/api/wareHouse'
// import request from '@/utils/request'

const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(240)
const queryFormRef = ref(ElForm)
const operateFormRef = ref(ElForm)
const formDataRef = ref(ElForm)
const { proxy }: any = getCurrentInstance()

let id = 0
const props: CascaderProps = {
  lazy: true,
  lazyLoad(node, resolve) {
    const { level } = node
    setTimeout(() => {
      const nodes = Array.from({ length: level + 1 }).map((item) => ({
        value: ++id,
        label: `Option - ${id}`,
        leaf: level >= 2
      }))
      // Invoke `resolve` callback to return the child nodes data and indicate the loading is finished.
      resolve(nodes)
    }, 1000)
  }
}

const state = reactive({
  ERPFACTORY:'',
  OpCode: '', //过账流水
  commitDate: '',
  rsa: '',
  Button_state: false,
  loading2: false,
  ERPFactoryList: [] as any, // 组织
  ERPLocationList: [] as any, //仓库
  LocationList: [] as any, //货位
  queryParams: {
    queryId: 'GetMaterialBoxInformationRow',
    version: '00009',
    params: {
      SITENAME: 'SDK',
      MATERIALPACKINGNAME: '',
      MATERIALSPECNAME: '',
      ERPFACTORY: '',
      ERPLOCATION: '',
      LOCATIONNAME: '',
      AREANAME: '',
      STORAGEOPERATIONTYPE: 'Manual',
      DESC_CN:'',
      SPECNAME:''
    },
    pageNum: 1,
    pageSize: 10
  },
  queryParamsERPFactory: {
    queryId: 'GetErpFactoryList',
    version: 'WEB00001',
    params: {
      SITENAME: localStorage.getItem('siteName') || 'SDK'
    },
    pageNum: 1,
    pageSize: 10
  },
  queryParamsERPLocation: {
    queryId: 'GetErpLocationList',
    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
  },
  changeParams: {
    header: {
      MESSAGENAME: 'ModifyLocation',
      LANGUAGE: 'Chinese'
    },
    body: {
      BOXLIST: [] as any,
      ERPLOCATION: '',
      AREANAME: '',
      LOCATIONNAME: ''
    }
  },
  operateParams: {
    date: new Date()
  },
  operateOptions: [] as any, // 操作类型
  actNoOptions: [] as any, // 抬头文本
  checkResultOptions: [
    {
      label: 'OK',
      value: 'OK'
    },
    {
      label: 'NG',
      value: 'NG'
    }
  ], // 质检结果
  loading: false,
  boxList: [] as any,
  StorageSelectList: [] as any,
  StorageSelect: '',
  LASTEVENTCOMMENT: '',
  column: [] as any,
  StorageSelectAll: [] as any,
  multipleSelection: [] as any,
  checkboxValue: false,
  flag: true as Boolean,
  total: 0
})
const {
  ERPFACTORY,
  OpCode,
  commitDate,
  rsa,
  queryParams,
  loading,
  total,
  ERPFactoryList,
  ERPLocationList,
  LocationList,
  boxList,
  column,
  operateParams,
  operateOptions,
  actNoOptions,
  checkResultOptions
} = toRefs(state)

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);
      }
    })
  }
}

onMounted(() => {
  state.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: 'ERPLOCATION', hide: false },
    { header: '仓库名称', field: 'ERPLOCATIONDESC', hide: false },
    // { header: "库区", field: "AREANAME", hide: false },
    { header: '货位代码', field: 'LOCATIONNAME', hide: false },
    { header: '货位名称', field: 'LOCATIONNAMEDESC', hide: false },
    { header: '物料数量', field: 'MATERIALQUANTITY', hide: false },
    { header: '单位', field: 'FNAME', hide: false },
    { header: 'SDK规格', field: 'SPECNAME', hide: false },
    { header: 'Hold 状态', field: 'HOLDSTATE', hide: false },
    { header: 'Stock 状态', field: 'STOCKSTATE', hide: false },
    { header: 'Reason Code', field: 'REASONCODE', hide: true },
    { header: '品质状态', field: 'OQARESULTSTATE', hide: false },
    { header: '品质结果', field: 'PACKINGGRADE', hide: false },
    { header: '入库日期', field: 'RECEIVETIME', hide: false }
    // { header: "最后操作的注解", field: "LASTEVENTCOMMENT", hide: false },
  ]

  handleQuery()
  ERPFactoryQuery()
  updateTableHeight()
  window.addEventListener('resize', handleResize)

  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

  let pwd: any = localStorage.getItem('remeberPwd');
  state.ERPFACTORY = JSON.parse(localStorage.getItem('orgNo')) || '';
  // getStorageSpecLocationList()
})
// 更新列
function updateList(col: any) {
  state.column = col
}
function queryInfo() {
  state.queryParams.pageNum = 1
  handleQuery()
}
function handleQuery() {
  // if (state.queryParams.params.LOCATIONNAME == '' && state.queryParams.params.MATERIALSPECNAME == '' && state.queryParams.params.MATERIALPACKINGNAME == '') {
  //   ElMessageBox.alert('查询条件不为空!', '提醒框', {
  //     // if you want to disable its autofocus
  //     // autofocus: false,
  //     confirmButtonText: 'OK',
  //   })
  // } else {
  state.boxList = []
  state.queryParams.queryId = 'GetMaterialBoxInformationRow'
  state.queryParams.version = '00009_SDK'
  getQueryPageList(state.queryParams)
    .then((res: any) => {
      state.boxList = res.data.list
      state.total = res.data.total
      console.log('state.boxList' + state.boxList)
    })
    .catch((error) => {
      ElMessageBox.alert(error, '提醒框', {
        confirmButtonText: 'OK'
      })
    })
  // }
}
function changeFac(e: any) {
  // console.log(e)
  state.queryParams.params.ERPLOCATION = ''
  state.queryParamsERPLocation.params.ERPFACTORYNAME = e
  ERPLocationQuery()
}
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.ERPFactoryList.unshift({
        ERPFACTORY: ''
      })
    })
    .catch(() => {})
}
//ERP库位查询
function ERPLocationQuery() {
  getQueryList(state.queryParamsERPLocation)
    .then((res: any) => {
      state.ERPLocationList = res.data
      state.ERPLocationList.unshift({
        ENUMVALUE: ''
      })
    })
    .catch(() => {})
}
const handleSelectionChange = (val: any) => {
  state.multipleSelection = val
  console.log('state.multipleSelection', state.multipleSelection) // 打印选中行的数据
}

function handleOuterClick(isVisible: any) {
  if (isVisible == true) {
    if (state.multipleSelection.length == 0 && state.flag) {
      state.flag = false
      state.StorageSelectList = []
      ElMessageBox.alert('请先选择批次!', '提醒框', {
        // if you want to disable its autofocus
        // autofocus: false,
        confirmButtonText: 'OK'
      })
      setTimeout(() => {
        state.flag = true
      }, 2000)
      return
    }

    const firstLocation = state.multipleSelection[0].ERPLOCATION

    // 遍历数组，检查每个元素的ERPLOCATION是否与基准相同
    for (let i = 1; i < state.multipleSelection.length; i++) {
      if (state.multipleSelection[i].ERPLOCATION !== firstLocation && state.flag) {
        state.flag = false
        ElMessageBox.alert('请选择同一库位的批次!', '提醒框', {
          // if you want to disable its autofocus
          // autofocus: false,
          confirmButtonText: 'OK'
        })
        setTimeout(() => {
          state.flag = true
        }, 2000)
        return
      }
    }
    StorageList(firstLocation)
  }
}

//查询库区和库位
async function StorageList(firstLocation: any) {
  try {
    try {
      state.queryParams.queryId = 'Get2stAreaName'
      state.queryParams.version = '00003'
      state.changeParams.body.ERPLOCATION = firstLocation
      state.queryParams.params.ERPLOCATION = firstLocation
      const res = await getQueryList(state.queryParams)
      // state.StorageSelectList = res.data;
      state.StorageSelectAll = res.data
      // console.log(state.StorageSelectAll)
      getStorageSelectAll('1')
      if (state.StorageSelectAll.length == 0) {
        proxy.$ElMessage.info('目的货位为空!')
        return
      }
      // for (let i = 0; i < state.StorageSelectList.length; i++) {
      //   state.queryParams.queryId = 'Get3stStorageName';
      //   state.queryParams.version = '00001';
      //   state.queryParams.params.AREANAME = state.StorageSelectList[i].ERPLOCATION;
      //   const childrenRes = await getQueryList(state.queryParams);
      //   state.StorageSelectList[i].children = childrenRes.data;
      // }
    } 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 getStorageSelectAll(query: any) {
  console.log(':*************', query)
  // console.log("AAAAAAAAA",state.SEARCHTYPE)
  let arr = state.StorageSelectAll.filter((item: any) => {
    return item.DESCRIPTION.includes(query) || item.STORAGENAME.includes(query)
  })
  if (arr.length > 50) {
    state.StorageSelectList = arr.slice(0, 50)
  } else {
    state.StorageSelectList = arr
  }
}
async function submit() {
  state.loading2 = true
  state.Button_state = true

  if (!state.commitDate) {
    ElMessageBox.alert('过账时间不能为空!', {
      confirmButtonText: 'OK'
    })
    state.loading2 = false
    state.Button_state = false
    return
  }

  if (state.multipleSelection.length > 0 && state.StorageSelect != '') {
    // console.log("state.StorageSelect")
    //state.changeParams.body.AREANAME = state.StorageSelect[0];
    state.changeParams.body.LOCATIONNAME = state.StorageSelect
    console.log(state.StorageSelect)
    state.changeParams.body.BOXLIST = []
    state.changeParams.body.BOXLIST = JSON.parse(JSON.stringify(state.multipleSelection));
    for (let k = 0; k < state.changeParams.body.BOXLIST.length; k++) {
      // 将 BOX 对象推送到 state.changeParams.body.BOXLIST 数组中
      // state.changeParams.body.BOXLIST.push({
      //   SITENAME: state.multipleSelection[k].SITENAME,
      //   MATERIALPACKINGNAME: state.multipleSelection[k].MATERIALPACKINGNAME,
      //   LOCATIONNAME: state.multipleSelection[k].LOCATIONNAME,
      //   LASTEVENTCOMMENT: state.LASTEVENTCOMMENT,
      //   CHARGE:state.multipleSelection[k].CHARGE,
      //   SUPPLIERCHARGE:'',
      //   ErpFactory:state.ERPFACTORY,
      //   ErpLocation:state.multipleSelection[k].ERPLOCATION            
      // })
      state.changeParams.body.BOXLIST[k].PRELOCATIONNAME = state.multipleSelection[k].LOCATIONNAME
      state.changeParams.body.BOXLIST[k].LOCATIONNAME = state.StorageSelect
      state.changeParams.body.BOXLIST[k].LASTEVENTCOMMENT = state.LASTEVENTCOMMENT;
      state.changeParams.body.BOXLIST[k].ErpFactory = state.ERPFACTORY

    }

    getOpCode({
      opcode: state.OpCode,
      user: localStorage.getItem('userId')
    }).then((res: any) => {
      console.log(res.resultObj)
      state.OpCode = res.resultObj
      let params = {
        user: localStorage.getItem('userId'),
        siteName: 'SDK',
        boxList: state.changeParams.body.BOXLIST,
        commitDate: state.commitDate,
        opcode: state.OpCode
      }
      console.log('state.changeParams', state.changeParams)

      changeLocation(params).then((res: any) => {
          console.log(res)
          ElMessageBox.alert('货位移转完成', '提醒框', {
            confirmButtonText: 'OK'
          })
          state.boxList = []
          state.multipleSelection = []
          handleQuery()
          state.Button_state = false
          state.loading2 = 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
}
/*

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.StorageSelectAll = res.resultObj;
  });
}
*/

function getLocationList(query: any) {
  let arr = state.StorageSelectAll.filter((item: any) => {
    return item.DESCRIPTION.includes(query) || item.STORAGENAME.includes(query)
  })
  if (arr.length > 50) {
    state.LocationList = arr.slice(0, 50)
  } else {
    state.LocationList = arr
  }
  state.LocationList.unshift({
    ENUMVALUE: ''
  })
}
</script>

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