<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="12">
          <el-col :span="4">
            <el-form-item label="库区" prop="state.queryParams.params">
              <el-select v-model="state.queryParams.params.AREANAME" placeholder="请选择库区" style="width: 240px" @change="updataAREANAME">
                <el-option v-for="item in state.AREANAMELIST" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物料号" prop="params.MATERIALSPECNAME">
              <el-Input @change="getSdkInfo" v-model="queryParams.params.MATERIALSPECNAME" placeholder="请输入物料号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="SDK规格" prop="SENDORDERNO" >
            <el-select filterable v-model="queryParams.params.sdk_id" placeholder="选择SDK规格" clearable @click="getMATERIALSPECNAME"  :filter-method="locatioNFilter">
              <!--                       @change="GetERPLocationForList">-->
              <el-option v-for="item in state.sdkList" :key="item.text" :label="item.text" lwhlslsk
                        :value="item.value" />
            </el-select>
          </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>
          <el-checkbox v-model="state.AVG_checkbox" label="是否使用AVG" size="smaller" style="margin-left: 20px"/>
          <el-form-item label="起始点" prop="state.queryParams.params" v-if="state.AVG_checkbox">
            <el-select v-model="state.INITILATION" placeholder="请选择起始点"  style="width: 240px;margin-left: 20px">
              <el-option v-for="item in state.INITILATIONLIST" :key="item.VALUE" :label="item.LABEL" :value="item.VALUE" />
            </el-select>
          </el-form-item>
          <el-form-item label="目标点" prop="state.queryParams.params"  v-if="state.AVG_checkbox">
            <el-select v-model="state.ENDING" placeholder="请选择目标点"  style="width: 240px">
              <el-option v-for="item in state.ENDINGLIST" :key="item.VALUE" :label="item.LABEL" :value="item.VALUE" />
            </el-select>
          </el-form-item>
          <el-form-item label="AB轴" prop="state.queryParams.params" v-if="state.AVG_checkbox">
            <el-select v-model="state.AB" placeholder="请选择AB轴"  style="width: 240px">
              <el-option v-for="item in state.ABSLIST" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </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" v-loading="loading" :data="state.boxList"   row-key="id" border size="mini" fit highlight-current-row height="610"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" />
        <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>
      </el-table>
      <pagination v-if="total > 0" :total="total" v-model:pageNumTo="queryParams.pageNum"
        v-model:pageSizeTo="queryParams.pageSize" @pagination="handleQuery" />
    </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="4">
            <el-form-item label="目标库区" prop="state.queryParams.params">
              <el-select v-model="state.StorageSelect" placeholder="请选择库区" style="width: 240px">
                <el-option v-for="item in state.AREANAMELIST" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="备注" prop="operateParams.date">
              <el-Input v-model="state.LASTEVENTCOMMENT" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="原库区出货口" prop="state.queryParams.params">
              <el-select v-model="state.outPort" placeholder="请选择出货口"  style="width: 240px">
                <el-option v-for="item in state.outPortList" :key="item.PORTNO" :label="item.PORTNAME"   :value="item.PORTNO" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" v-loading="state.loading2" @click="submit"  :disabled="state.button_state">提交</el-button>
      </div>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: "locationMove",
};
</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 type { CascaderProps } from 'element-plus'
import { IFTRUE, areAllNotEmpty } from "@/utils/CommonUtil";
import { BuildWareMove, GetLiberaryBaeIn, getoutPortList } from '@/api/buildWareHouse'
import { bTableHeight } from "../../../composables/calcTableHeight";
import { getSdkList } from '@/api/label'
const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(200);

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({
  sdkList: [] as any,
  sdkListAll:[] as any,
  outPort : '',
  outPortList : [] as any,
  INITILATION : '',
  ENDING : '',
  AB : '',
  ABSLIST : [
    {
      text : "A轴",
      value : "A"
    },
    {
      text : "B轴",
      value : "B"
    }
  ] as any,
  ENDINGLIST : [] as any,
  INITILATIONLIST : [] as any,
  AVG_checkbox : false,
  rsa: "",
  button_state: false,
  loading2: false,
  StorageSelect: '',
  queryParams: {
    queryId: "GetMaterialBoxInformationRow",
    version: "00009",
    params: {
      SITENAME: 'SDK',
      MATERIALPACKINGNAME: "",
      LOCATIONNAME: "",
      MATERIALSPECNAME: "",
      ERPLOCATION: "",
      AREANAME: "",
      STORAGEOPERATIONTYPE: "Manual",
      DESCRIPTION: '',
      sdk_id:''
    },
    pageNum: 1,
    pageSize: 10
  },
  changeParams: {
    MESSAGENAME: "ModifyLocation",
    LANGUAGE: "Chinese",
    MATERIALPACKINGNAME: [] as any,
    AREANAME: "",
    userId: localStorage.getItem('userId') || '10975133',
    SITENAME: localStorage.getItem('SITENAME') || "SDK",
    INITILATION: '',
    ENDING: '',
    AB: '',
  },
  operateParams: {
    date: new Date(),
    IFUserAGV: '不使用AGV',
  },
  operateOptions: [] as any, // 操作类型
  actNoOptions: [] as any, // 抬头文本
  checkTypeOption: [
    {
      label: "使用AGV",
      value: "使用AGV",
    },
    {
      label: "不使用AGV",
      value: "不使用AGV",
    }
  ],
  ABList: [{ value: 'A', label: 'A' }, { value: 'B', label: 'B' }],
  STOCKSELECTLIST: [] as any,
  loading: false,
  boxList: [] as any,
  StorageSelectList: [] as any,
  //StorageSelect: [] as any,
  LASTEVENTCOMMENT: "",
  column: [] as any,
  multipleSelection: [] as any,
  checkboxValue: false,
  flag: true as Boolean,
  total: 0,
  AREANAMELIST: [
    { value: '', label: '' },
  ] as any,
});
const { sdkList,sdkListAll,rsa, queryParams, loading, total, boxList, column, operateParams, operateOptions, actNoOptions } = toRefs(state);

onMounted(() => {
  state.column = [
    // { header: "标签", field: "MATERIALPACKINGNAME", hide: false },
    // { header: "批次", field: "CHARGE", hide: false },
    // // { header: "载具", field: "DURABLENAME", hide: false },
    // { header: "熟化入库时间", field: "MATURATIONTIME", hide: false },
    // { header: "料号", field: "MATERIALSPECNAME", hide: false },
    // { header: "品名", field: "CN_MATERIALSPECNAME", hide: false },
    // { header: "SDK规则", field: "SPECNAME", hide: false },
    // { header: "单位", field: "FNAME", hide: false },
    // { header: "库区", field: "CN_AREANAME", hide: false },
    // { header: "库区", field: "AREANAME", hide: true },
    // { header: "组织", field: "ORGNAME", hide: false },
    // { header: "组织", field: "ORGNO", hide: true },
    // { header: "仓库", field: "CN_ERPLOCATION", hide: false },
    // { header: "仓库", field: "ERPLOCATION", hide: true },
    // { header: "货位", field: "CN_LOCATIONNAME", hide: false },
    // { header: "数量", field: "MATERIALQUANTITY", hide: false },
    // { header: "搬送类型", field: "TRANSPORTCOMMANDTYPE", hide: true },
    // { header: "托盘/管芯", field: "TRAYNAME", hide: false },
    // { header: "立体货架", field: "SHELFNAME", hide: false },
    // { header: "宽幅", field: "WIDTH", hide: false },
    // { header: "直径", field: "DIAMETER", hide: false },
    // { header: "偏移量", field: "DEVIATION", hide: false },
    // { header: "重量", field: "WEIGHT", hide: false },
    // { header: "生产线", field: "PRODUCTLINE", hide: false },


    { header: "批次", field: "CHARGE", hide: false },
    { header: "物料号", field: "MATERIALSPECNAME", hide: false },
    { header: "品名", field: "CN_MATERIALSPECNAME", hide: false },
    { header: "SDK规格", field: "SPECNAME", hide: false },
    { header: "库区", field: "AREANAME", hide: false },
    { header: "仓库", field: "CN_ERPLOCATION", hide: false },
    { header: "货位", field: "CN_LOCATIONNAME", hide: false },
    { header: "托盘/管芯", field: "TRAYNAME", hide: false },
    { header: "立体货架", field: "SHELFNAME", hide: false },
    { header: "宽幅", field: "WIDTH", hide: false },
    { header: "直径", field: "DIAMETER", hide: false },
    { header: "偏移量", field: "DEVIATION", hide: false },
    { header: "重量", field: "WEIGHT", hide: false },
    { header: "生产线", field: "PRODUCTLINE", hide: false },
    { header: "系统数量", field: "MATERIALQUANTITY", hide: false },
  ];
  handQuery()
  GetLiberaryIn()
  //handleQuery();
  updateTableHeight();
  window.addEventListener('resize', handleResize);
});
function getMATERIALSPECNAME() {
  if(!state.queryParams.params.MATERIALSPECNAME){
    ElMessageBox.alert('请输入料号', {
      confirmButtonText: 'OK'
    })
    return ;
  }
}
function getSdkInfo () {
  state.sdkList = []
  getSdkList({materialSpecName:state.queryParams.params.MATERIALSPECNAME}).then((res: any) => {
      state.sdkListAll = res.resultObj;
      locatioNFilter('')
    })
    .catch(() => { });
}
function locatioNFilter(query : any) {
    console.log(query)
  let arr = state.sdkListAll.filter((item : any) => {
    return (item.text.includes(query) || item.value.includes(query))
  })
  if (arr.length > 50) {
    state.sdkList = arr.slice(0, 50)
  } else {
    state.sdkList = arr
  }
}
function queryInfo() {
  state.queryParams.pageNum = 1
  handleQuery()
}
function GetLiberaryIn() {
  GetLiberaryBaeIn({}).then((res: any) => {
    state.INITILATIONLIST = res.resultObj;
    state.ENDINGLIST = res.resultObj;
  })
    .catch(() => { });
}
function updataAREANAME() {
  state.boxList = [];
  state.total = 0;
  handleQuery();
  getoutPortList( {AREANAME : state.queryParams.params.AREANAME}).then((res : any) =>{
    console.log(res);
    state.outPortList = []
    state.outPortList = res.resultObj;
  })
}
// 更新列
function updateList(col: any) {
  state.column = col;
}
function handleQuery() {
  state.queryParams.queryId = 'GetAREANAMEList_1'
  state.queryParams.version = '00007'
  state.queryParams.params.sdk_id = state.queryParams.params.sdk_id == undefined ? '' : state.queryParams.params.sdk_id
  state.boxList = []
  getQueryPageList(state.queryParams)
    .then((res: any) => {
      if(res.data.list.length == 0){
        ElMessageBox.alert('查无数据', '提醒框', {
          confirmButtonText: 'OK',
        })
        return
      } else {
        state.boxList = res.data.list;
        state.total = res.data.total;
        console.log("state.boxList" + state.boxList);
      }
    })
    .catch((error) => {
      ElMessageBox.alert(error, '提醒框', {
        confirmButtonText: 'OK',
      })

    });
}

const handleSelectionChange = (val: any) => {
  state.multipleSelection = val;
  console.log("state.multipleSelection", state.multipleSelection); // 打印选中行的数据   
};

function submit() {
  if (state.multipleSelection.length > 0 && state.StorageSelect != '') {
    if(state.StorageSelect == state.queryParams.params.AREANAME){
      ElMessageBox.alert('目标库区和当前库区不可一致', '提示框', {
        confirmButtonText: 'OK',
      })
      return;
    }
    if(state.AVG_checkbox){
      if(!areAllNotEmpty(state.AB,state.INITILATION,state.INITILATION)){
        ElMessageBox.alert('使用AGV搬送就必须选择起始地、目的地、A|B轴', '提示框', {
          confirmButtonText: 'OK',
        })
        return;
      }
    }
    if(state.outPort == ''){
      ElMessageBox.alert('选择出库口', '提示框', {
        confirmButtonText: 'OK',
      })
      return;
    }
    state.loading2 = true
    state.button_state = true
    state.changeParams.AREANAME = state.StorageSelect;
    state.changeParams.MATERIALPACKINGNAME = [];
    for (let k = 0; k < state.multipleSelection.length; k++) {
      // 将 BOX 对象推送到 state.changeParams.body.BOXLIST 数组中  
      state.changeParams.MATERIALPACKINGNAME.push({
        ...state.multipleSelection[k]
      });
    }
    state.changeParams.AB = state.AB
    state.changeParams.ENDING = state.ENDING
    state.changeParams.INITILATION = state.INITILATION
    BuildWareMove(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
    })

    // if (state.operateParams.IFUserAGV == '使用AGV') {
      // if (!areAllNotEmpty(state.AB, state.INITILATION, state.INITILATION)) {
      //   ElMessageBox.alert('使用AGV搬送就必须选择起始地、目的地、A|B轴', '提示框', {
      //     confirmButtonText: 'OK',
      //   })
      //   state.loading2 = false
      //   state.button_state = false
      //   return
      // } else {
      //   state.changeParams.AB = state.AB[0].toString()
      //   state.changeParams.ENDING = state.ENDING[0].toString()
      //   state.changeParams.INITILATION = state.INITILATION[0].toString()
    //     await BuildWareMove(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
    //     })
    //   }
    // } else {
    //   await BuildWareMove(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
    //   })
    // }
  } 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
}
//查询库区
const handQuery = () => {
  state.queryParams.queryId = 'GetAREANAMEList'
  state.queryParams.version = '00001'
  state.AREANAMELIST = [{ value: '', label: '' },];
  getQueryList(state.queryParams)
    .then((res: any) => {
      for (let i = 0; i < res.data.length; i++) {
        state.AREANAMELIST.push({ label: res.data[i].DESCRIPTION, value: res.data[i].AREANAME });
      }
    })
    .catch(() => { });
}
</script>

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