<!--
  功能：功能描述  优先级调整
  作者：Libra
  邮箱：mingxichen@163.com
  时间：2024年04月12日 09:54:29
  版本：v1.0
  修改记录：
  修改内容：
  修改人员：LIWENHU
  修改时间：2024/04/15 10:26:12
-->
<template>
  <div class="vue-element-page-wrap" ref="tableContainer">
    <el-row class="page-search" justify="space-between" align="middle">
      <el-form ref="queryFormRef" :model="state" :inline="true">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="批次" prop="CHARGE">
              <el-Input v-model="queryParams.params.CHARGE" clearable placeholder="请输入批次" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="物料号" prop="state.queryParams.params">
              <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
                clearable
                filterable
                v-model="queryParams.params.sdk_id"
                placeholder="选择SDK规格"
                @click="getMATERIALSPECNAME"
                :filter-method="locatioNFilter"
              >
                <!--                       @change="GetERPLocationForList">-->
                <el-option
                  v-for="item in state.sdkList"
                  :key="item.text"
                  :label="item.text"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="库区" prop="state.queryParams.params">
              <el-select
                v-model="state.queryParams.params.AREANAME"
                placeholder="请选择库区"
                @change="getoutPort"
                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="5">
            <el-form-item label="出库单" prop="state.queryParams.params">
              <el-Input
                v-model="queryParams.params.RECEIVEREQUESTNAME"
                placeholder="请输入出库单"
                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>
          <el-checkbox
            v-model="state.AVG_checkbox"
            label="是否使用AVG"
            size="smaller"
            @change="AVG_Change"
            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>
      <el-table
        :height="tableHeight"
        border
        v-loading.fullscreen.lock="state.loading"
        :data="state.TaskAREANAMELIST"
        highlight-current-row
        row-key="id"
        height="620px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" />
        <template v-for="(col, index) in palletTableConfig.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="state.total > 0"
        :total="state.total"
        v-model:pageNumTo="state.queryParams.pageNum"
        v-model:pageSizeTo="state.queryParams.pageSize"
        @pagination="handleQuery"
      />
    </div>

    <div class="vue-element-page-table flex">
      <div>
        <el-row class="page-search" justify="space-between" align="middle">
          <el-col :span="6">
            <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>
          <div class="page-search-btns">
            <el-button
              type="primary"
              @click="submit"
              :disabled="state.button_state"
              v-loading="state.loadings"
              >确认</el-button
            >
          </div>
        </el-row>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
export default {
  name: 'MaturationLibrary'
}
</script>
<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance, nextTick } from 'vue'
import { ElForm, ElMessageBox, ElTable } from 'element-plus'
import { getQueryList, BpelEvent, getQueryPageList } from '@/api/common'
import { IFTRUE } from '@/utils/CommonUtil'
import { getSdkList } from '@/api/label'
import {
  AutoStockOut,
  GetLiberaryBaeIn,
  getoutPortList,
  MatuStockOutEvent
} from '@/api/buildWareHouse'
import { bTableHeight } from '../../../composables/calcTableHeight'

const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(220)

const queryFormRef = ref(ElForm)
const portFormRef = ref(ElForm)
const state = reactive({
  //搜索类型
  sdkList: [] as any,
  sdkListAll: [] as any,
  SEARCHTYPE: '1',
  INITILATION: '',
  INITILATIONLIST: [] as any,
  ENDING: '',
  ENDINGLIST: [] as any,
  AB: '',
  ABSLIST: [
    {
      text: 'A轴',
      value: 'A'
    },
    {
      text: 'B轴',
      value: 'B'
    }
  ] as any,
  AVG_checkbox: false,
  outPortList: [{ PORTNO: '', PORTNAME: '' }],
  outPort: '',
  button_state: false,
  loadings: false,
  loading: false,
  total: 0,
  queryParams: {
    queryId: '',
    version: '',
    params: {
      AREANAME: '' as any,
      DESCRIPTION: '',
      MATERIALSPECNAME: '',
      SHIPREQUESTNAME: '',
      RECEIVEREQUESTNAME: '',
      sdk_id: '',
      CHARGE: ''
    },
    pageNum: 1,
    pageSize: 10
  },
  ChangeParams: {
    userId: localStorage.getItem('userId'),
    SITENAME: localStorage.getItem('SITENAME') || 'SDK',
    MATERIALPACKINGNAME: [] as any, //标签号
    MATERIALSPECNAME: '' //物料号
  },
  AREANAMELIST: [{ value: '', label: '' }],
  TaskAREANAMELIST: [],
  TransportTaskChoose: [] as any
})

const value1 = ref(true)
const {
  SEARCHTYPE,
  queryParams,
  sdkList,
  sdkListAll,
  AREANAMELIST,
  TransportTaskChoose,
  loading,
  button_state,
  loadings
} = toRefs(state)
const portFormRefData = ref({
  FIRSTORDER: '',
  FIRSTORDERLIST: [
    { value: 'Normal', label: '正常' },
    { value: 'Prior', label: '优先' },
    { value: 'Cancel', label: '取消' },
    { value: 'Pause', label: '暂停' }
  ],
  STOCKSELECT: [],
  STOCKSELECTLIST: [
    {
      value: '1',
      label: 'TYPE1',
      children: [
        { value: '1-1', label: 'TYPE1-1' },
        { value: '1-2', label: 'TYPE1-2' }
      ]
    },
    {
      value: '2',
      label: 'TYPE2',
      children: [
        { value: '2-1', label: 'TYPE2-1' },
        { value: '2-2', label: 'TYPE2-2' }
      ]
    }
  ]
})

const palletTableConfig = ref({
  isAll: false,
  data: [],
  column: [
    // { header: "标签", field: "MATERIALPACKINGNAME", hide: false },
    { header: '批次', field: 'CHARGE', hide: false },
    // { header: "熟化入库时间", field: "MATURATIONTIME", hide: false },
    // { header: "熟化周期", field: "MATURATIONTIME", hide: false },
    // { header: "预计熟化出库", field: "PREMATURATIONOUTTIME", hide: false },
    { header: '物料号', field: 'MATERIALSPECNAME', hide: false },
    { header: '品名', field: 'DESC_CN', hide: false },
    // { header: "规格", field: "SPECNAME", hide: false },
    { header: 'SDK规格', field: 'SPECNAME', hide: false },
    { header: '实际规格', field: 'TRUEGG', hide: false },
    // { header: "单位", field: "FNAME", hide: false },
    { header: '库区', field: 'AREANAME', hide: false },
    // { header: "立体库货架", field: "SHELFNAME", hide: false },
    // { header: "组织", field: "ORGNAME", hide: false },
    { header: '仓库', field: 'ERPLOCATION', hide: false },
    { header: '货位', field: 'LOCATIONNAME', hide: false },
    // { header: "数量", field: "MATERIALQUANTITY", hide: false },
    // { header: "单位", field: "UNIT", 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: 'MATERIALQUANTITY', hide: false }
  ]
})

onMounted(() => {
  handQuery()
  QueryAREANAME()
  GetLiberaryIn()
  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 AVG_Change() {
  console.log(state.AVG_checkbox)
}
function getoutPort() {
  handleQuery()
  getoutPortList({ AREANAME: state.queryParams.params.AREANAME }).then((res: any) => {
    console.log(res)
    state.outPortList = []
    state.outPortList = res.resultObj
  })
}
//选择搬送任务
function handleSelectionChange(selection: any) {
  console.log('调用了', selection)
  state.TransportTaskChoose = selection
}
//根据库区、料号查任务
const handleQuery = () => {
  state.queryParams.queryId = 'GetAREANAMEList_1'
  state.queryParams.version = '00051'
  state.queryParams.params.sdk_id =
    state.queryParams.params.sdk_id == undefined ? '' : state.queryParams.params.sdk_id
  getQueryPageList(state.queryParams)
    .then((res: any) => {
      console.log(res)
      if (res.data.list.length == 0) {
        state.TaskAREANAMELIST = []

        if (!state.queryParams.params.AREANAME) {
          ElMessageBox.alert('请选择库区查询', '提醒框', {
            confirmButtonText: 'OK'
          })
        } else {
          ElMessageBox.alert('查无数据', '提醒框', {
            confirmButtonText: 'OK'
          })
        }
      } else {
        state.TaskAREANAMELIST = []
        state.TaskAREANAMELIST = res.data.list
        state.total = res.data.total
      }
    })
    .catch(() => {})
}
//查询库区
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(() => {})
}
//查询任务
function QueryAREANAME() {
  state.queryParams.queryId = 'GetAREANAMEList_1'
  state.queryParams.version = '00005'
  getQueryPageList(state.queryParams)
    .then((res: any) => {
      console.log(res.data)
      state.TaskAREANAMELIST = res.data.list
      state.total = res.data.total
    })
    .catch((error: any) => {
      ElMessageBox.alert(error, '提醒框', {
        confirmButtonText: 'OK'
      })
    })
}
//确认提交按钮
function submit() {
  try {
    // state.loading = true;
    state.button_state = true
    state.loadings = true
    if (state.outPort == '') {
      ElMessageBox.alert('选择出货口', '提醒框', {
        confirmButtonText: 'OK'
      })
      // state.loading = false
      state.button_state = false
      state.loadings = false
      return
    }
    if (state.AVG_checkbox) {
      if (state.ENDING == '') {
        ElMessageBox.alert('选择目的点', '提醒框', {
          confirmButtonText: 'OK'
        })
        state.button_state = false
        state.loadings = false
        return
      } else if (state.INITILATION == '') {
        ElMessageBox.alert('选择起始点', '提醒框', {
          confirmButtonText: 'OK'
        })
        state.button_state = false
        state.loadings = false
        return
      } else if (state.AB == '') {
        ElMessageBox.alert('选择AB轴', '提醒框', {
          confirmButtonText: 'OK'
        })
        state.button_state = false
        state.loadings = false
        return
      } else if (state.INITILATION == state.ENDING) {
        ElMessageBox.alert('起始点和目标点不能一致', '提醒框', {
          confirmButtonText: 'OK'
        })
        state.button_state = false
        state.loadings = false
        return
      }
    }
    var userid = localStorage.getItem('userId')
    if (state.TransportTaskChoose.length > 0) {
      var ISAGV = state.AVG_checkbox ? 'TRUE' : 'FALSE'
      var MATERIALPACKINGNAMELIST = state.TransportTaskChoose.map((res: any) => {
        res.AREANAME = state.queryParams.params.AREANAME
        res.FLAG = 'OUT'
        res.OUTDESTINATION = state.queryParams.params.AREANAME
        res.ISAGV = ISAGV
        res.INITILATION = state.INITILATION
        res.ENDING = state.ENDING
        res.AB = state.AB
        res.TRANSPORTCOMMANDTYPE = 'OUT'
        res.PORT = state.outPort
        res.DURABLENAME = res.TRAYNAME
        return res
      })
      AutoStockOut({
        userId: userid,
        SITENAME: 'SDK',
        AREANAME: state.queryParams.params.AREANAME,
        aimAreaName: '',
        outProt: '',
        erpLocation: '',
        erpFactory: '',
        locationName: '',
        barCode: '',
        shipRequestName: '',
        MATERIALPACKINGNAME: MATERIALPACKINGNAMELIST
      })
        .then((res: any) => {
          console.log(res)
          if (res.success) {
            state.loading = false
            state.button_state = false
            state.loadings = false
            ElMessageBox.alert('出库成功', '提示框', {
              confirmButtonText: 'OK'
            })
            QueryAREANAME()
          } else {
            ElMessageBox.alert(res.message, '提示框', {
              confirmButtonText: 'OK'
            })
            state.button_state = false
            state.loadings = false
          }
        })
        .catch((err: any) => {
          ElMessageBox.alert('操作失败' + err, '提醒框', {
            confirmButtonText: 'OK'
          })
        })
      // try {
      //     state.loading = true
      //     state.button_state = true
      //     state.loadings = true;
      //     state.ChangeParams.MATERIALPACKINGNAME = [];
      //     for (const item of state.TransportTaskChoose) {
      //         state.ChangeParams.MATERIALPACKINGNAME.push({ ...item });
      //     }
      //     await MatuStockOutEvent(state.ChangeParams).then((res: any) => {
      //         if (IFTRUE(res)) {
      //             QueryAREANAME()
      //             state.loading = false;
      //             state.button_state = false
      //             state.loadings = false;
      //         } else {
      //             ElMessageBox.alert(res.data.message, '', {
      //                 confirmButtonText: 'OK',
      //             })
      //             state.button_state = false
      //             state.loadings = false;
      //         }
      //
      //     })
      //         .catch((error) => {
      //             ElMessageBox.alert(error, '提醒框', {
      //                 confirmButtonText: 'OK',
      //             })
      //             QueryAREANAME()
      //             state.button_state = false
      //             state.loadings = false;
      //         });
      //
      // } catch (error) {
      //     ElMessageBox.alert("运行错误", '提醒框', {
      //         confirmButtonText: 'OK',
      //     })
      //     state.button_state = false
      //     state.loadings = false;
      // } finally {
      //     state.loading = false
      //     state.button_state = false
      //     state.loadings = false;
      // }
    } else {
      ElMessageBox.alert('请先选择任务', '提示框', {
        confirmButtonText: 'OK'
      })
      state.button_state = false
      state.loadings = false
    }
    state.button_state = false
    state.loadings = false
  } catch (error) {
    ElMessageBox.alert('运行错误', '提醒框', {
      confirmButtonText: 'OK'
    })
    state.button_state = false
    state.loadings = false
  } finally {
    state.loading = false
    state.button_state = false
    state.loadings = false
  }
}
</script>

<style scoped>
.flex {
  display: flex;
}

.flex > div {
  flex: 1;
}
</style>
