<template>
  <div class="page-horizontal-wrap">
    <div class="page-left-container">
      <div class="left-form-container" style="min-height: 150px">
        <el-form ref="formDataRef" label-position="left" label-width="120px" :model="formData">
          <el-form-item label="库存组织" prop="ERPFACTORY">
            <el-select
              filterable
              v-model="formData.ERPFACTORY"
              placeholder="下拉选择组织"
              @change="changeFac"
              size="default"
            >
              <el-option
                v-for="item in ERPFactoryList"
                :key="item.ENUMVALUE"
                :label="item.DESCRIPTION"
                :value="item.ENUMVALUE"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="库存仓库" prop="ERPLOCATION">
            <el-select size="default" filterable v-model="formData.ERPLOCATION" placeholder="下拉选择仓库">
              <el-option
                v-for="item in ERPLocationList"
                :key="item.ENUMVALUE"
                :label="item.DESCRIPTION"
                :value="item.ENUMVALUE"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="目的货位" prop="SEARCHTYPE">
            <el-cascader
              @visible-change="handleOuterClick"
              v-model="state.StorageSelect"
              :options="state.StorageSelectList"
              style="width: 300px;"
              :props="{
                checkStrictly: true,
                label: 'DESCRIPTION',
                value: 'STORAGENAME',
                children: 'children'
              }"
            />
          </el-form-item>
        </el-form>
        <el-form
          ref="queryParamRef"
          label-position="left"
          label-width="120px"
          :model="queryParam"
          :rules="rules_assigned"
        >
          <el-form-item label="扫描条码" prop="MATERIALPACKINGNAME">
            <el-input
              v-model="queryParam.MATERIALPACKINGNAME"
              placeholder="请扫描条码"
              @keydown.enter.prevent="getBatch"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="vue-element-page-wrap" ref="tableContainer">
      <div class="vue-element-page-table">
        <div class="page-table-operate">
          <span>BOX明细</span>
        </div>
        <el-table
          border
          v-loading="undistributed_loading"
          :data="undistributed_list"
          height="300"
          highlight-current-row
          row-key="id"
          @row-click="getBoxList"
        >
          <template v-for="(col, index) in undistributed_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-slot:empty>
            <svg-icon icon-class="noData" width="160px" height="160px" />
          </template>
        </el-table>
      </div>
      <div class="vue-element-page-table">
        <div class="page-table-operate">
          <span>标签明细</span>
        </div>
        <el-table
          border
          v-loading="assigned_loading"
          :data="assigned_list"
          height="300"
          highlight-current-row
          row-key="id"
          @row-click="slectItem"
        >
          <template v-for="(col, index) in assigned_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-slot:empty>
            <svg-icon icon-class="noData" width="160px" height="160px" />
          </template>
        </el-table>
      </div>
      <el-row class="page-search" justify="end" align="middle">
        <div class="page-search-btns">
          <el-button
            type="primary"
            v-loading="state.loading"
            @click="handleReserve"
            :disabled="state.Button_state"
            >确定</el-button
          >
        </div>
      </el-row>
      <!-- assigned_list -->
    </div>
  </div>
</template>
<script lang="ts">
export default {
  name: 'SaleReturnStockIn'
}
</script>
<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance } from 'vue'
import { ElForm, ElMessageBox, ElMessage } from 'element-plus'
import { BpelEvent, getQueryList } from '@/api/common'
import { getBarCode, QTRCommit } from '@/api/StockIn'
import { error } from 'console';
// import { Header } from "element-plus/es/components/table-v2/src/components";

const { proxy }: any = getCurrentInstance()

const formDataRef = ref(ElForm)
const queryParamRef = ref(ElForm)
const state = reactive({
  ERPFactoryList: [] as any, // 组织
  ERPLocationList: [] as any,
  Button_state: false,
  firstLocation: '',
  loading: false,
  StorageSelect: [] as any,
  StorageSelectList: [] as any,
  formData: {
    ERPFACTORY: '', //组织
    ERPLOCATION: '', // 仓库
    SHIPREQUESTNAME: '',
    SHIPREQUESTSTATE: '',
    ERPRECEIVELOCATION: '',
    CUSTOMERNAME: '',
    ToSHIPREQUEST: '',
    ToSHIPREQUESTDetail: '',
    MaterialPackingList: []
  },
  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
  },
  queryParams: {
    queryId: '',
    version: '',
    params: {
      SITENAME: 'SDK',
      AREANAME: '',
      SHIPREQUESTNAME: '',
      //下面是handle查询参数
      MATERIALSPECNAME: '',
      ERPLOCATION: '',
      ERPFACTORY: '',
      SHIPREQUESTDETAILNAME: ''
    },
    pageNum: 1,
    pageSize: 12
  },
  queryParam: {
    MATERIALPACKINGNAME: ''
  },
  rules_assigned: {
    // ERPFACTORY: [{ required: true, message: '请选择库存组织', trigger: 'change' }],
    // ERPLOCATION: [{ required: true, message: '请选择库存仓库', trigger: 'change' }],
    // SEARCHTYPE: [{ required: true, message: '请选择目的货位', trigger: 'change' }],
    MATERIALPACKINGNAME: [{ required: true, message: '请输入批号', trigger: 'change' }]
  },
  // 未分配
  undistributed_list: [] as any,
  undistributed_loading: false,
  undistributed_column: [] as any,

  assigned_list: [] as any,
  assigned_loading: false as any,
  assigned_column: [] as any,
  // 当前选中项
  rowItem: null as any,
  ThisFlag: false, //用于判断是否相同
  ThatFlag: false
})
const {
  ERPFactoryList,
  ERPLocationList,
  formData,
  queryParam,
  undistributed_column,
  undistributed_list,
  undistributed_loading,
  assigned_list,
  assigned_loading,
  assigned_column,
  rules_assigned
} = toRefs(state)

onMounted(() => {
  state.undistributed_column = [
    {
      header: '料号',
      field: 'MATERIALSPECNAME',
      width: '100px',
      hide: false
    },
    {
      header: '品名',
      field: 'DESC_CN',
      width: '100px',
      hide: false
    },
    {
      header: '规格',
      field: 'SDK_ID',
      width: '100px',
      hide: false
    },
    {
      header: '行号',
      field: 'SHIPREQUESTDETAILNAME',
      width: '100px',
      hide: false
    },
    {
      header: '阶段',
      field: 'PHASE',
      width: '100px',
      hide: false
    },
    {
      header: '批次',
      field: 'CHARGE',
      width: '100px',
      hide: false
    }
  ]
  state.assigned_column = [
    {
      header: '标签',
      field: 'MATERIALPACKINGNAME',
      width: '100px',
      hide: false
    },
    {
      header: '批次',
      field: 'CHARGE',
      width: '100px',
      hide: false
    },
    {
      header: '阶段',
      field: 'PHASE',
      width: '100px',
      hide: false
    },
    {
      header: '数量',
      field: 'MATERIALQUANTITY',
      width: '100px',
      hide: false
    },
    {
      header: '库位',
      field: 'ERPLOCATION',
      width: '100px',
      hide: false
    },
    {
      header: '货位',
      field: 'LOCATIONNAME',
      width: '100px',
      hide: false
    },
    {
      header: 'SDK规格',
      field: 'SPECNAME',
      width: '100px',
      hide: false
    }
  ]
  ERPFactoryQuery()
})

/*****************************************************下面方法******************************************/
//ERP工厂查询
function ERPFactoryQuery() {
  getQueryList(state.queryParamsERPFactory)
    .then((res: any) => {
      state.ERPFactoryList = res.data
      state.ERPFactoryList.unshift({
        ENUMVALUE: ''
      })
    })
    .catch(() => {})
}
function changeFac(e: any) {
  // console.log(e)
  state.queryParamsERPLocation.params.ERPFACTORYNAME = e
  ERPLocationQuery()
}
//ERP库位查询
function ERPLocationQuery() {
  getQueryList(state.queryParamsERPLocation)
    .then((res: any) => {
      state.ERPLocationList = res.data
      state.ERPLocationList.unshift({
        ENUMVALUE: ''
      })
    })
    .catch(() => {})
}
function handleReserve() {
  QTRCommit({
    boxList: state.assigned_list,
    user: localStorage.getItem('userId')
  }).then((res: any) => {
    if(res.success) {
      ElMessage({
        message: "操作成功",
        type: 'success',
      })
    }
  }).catch((error) => {
    ElMessage.error(error)
  })
}

function getBoxList() {
  let queryParam = {
    queryId: 'GetSaleRetuenList',
    version: '00001',
    params: {
      SITENAME: localStorage.getItem('SITENAME') || 'SDK',
      SHIPREQUESTNAME: state.formData.SHIPREQUESTNAME, //预留单
      SHIPREQUESTTYPE: '4C'
    }
  }
  getQueryList(queryParam)
    .then((res: any) => {
      state.formData.CUSTOMERNAME = res.data[0].CUSTOMERNAME
      state.formData.ERPFACTORYNAME = res.data[0].ERPFACTORY
      state.formData.ERPRECEIVELOCATION = res.data[0].ERPLOCATION
      state.formData.SHIPREQUESTSTATE = res.data[0].SHIPREQUESTSTATE
      console.log(res.data)
    })
    .catch((error: any) => {
      ElMessageBox.alert(error, '提示框', {
        confirmButtonText: 'OK'
      })
    })
  getDetailList()
}

function handleOuterClick() {
  StorageList(state.formData.ERPLOCATION)
}

async function StorageList(firstLocation: any) {
  try {
    try {
      state.queryParams.queryId = 'Get2stAreaName'
      state.queryParams.version = '00003'
      state.queryParams.params.ERPLOCATION = firstLocation
      const res = await getQueryList(state.queryParams)
      state.StorageSelectList = res.data
      if (state.StorageSelectList.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 getDetailList() {
  let queryParam = {
    queryId: 'GetSaleReturnDetail',
    version: '00001',
    params: {
      SITENAME: localStorage.getItem('SITENAME') || 'SDK',
      SHIPREQUESTNAME: state.formData.SHIPREQUESTNAME //预留单
    }
  }
  getQueryList(queryParam)
    .then((res: any) => {
      state.undistributed_list = res.data
    })
    .catch((error: any) => {
      ElMessageBox.alert(error, '提示框', {
        confirmButtonText: 'OK'
      })
    })
}
/**
 * 行点击
 * */
function slectItem(row: any) {
  state.rowItem = row
}
function getBatch() {
  if (
    state.assigned_list.some(
      (item: any) => item.MATERIALPACKINGNAME === state.queryParam.MATERIALPACKINGNAME
    )
  ) {
    ElMessage.error('已经扫描了该条码!')
    return
  }
  if (
    state.queryParam.MATERIALPACKINGNAME &&
    state.StorageSelect[0] &&
    state.formData.ERPFACTORY &&
    state.formData.ERPLOCATION
  ) {
    getBarCode({
      MATERIALPACKINGNAME: state.queryParam.MATERIALPACKINGNAME,
      LocationName: state.StorageSelect[0],
      ErpFactory: state.formData.ERPFACTORY,
      ErpLocation: state.formData.ERPLOCATION,
      CREATEUSER: localStorage.getItem('userId'),
      siteName: 'SDK'
    }).then((res: any) => {
      console.log(res, 'data')
      state.undistributed_list = res.resultObj
      state.assigned_list.push(res.resultObj[0])
    })
  } else {
    ElMessage.error('库存组织、库存仓库、目的货位不能为空!')
  }
}
</script>

<style scoped>
.page-horizontal-wrap {
  display: flex;
  width: 100%;
  height: 100%;

  .page-left-container {
    width: 360px;
    height: 100%;
    background: #ffffff;
    border: 1px solid #dbdee3;
    box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    margin-right: 6px;
    padding: 10px;
    display: flex;
    flex-direction: column;

    :deep(.el-form-item) {
      margin-bottom: 20px;
    }

    .page-left-container-head {
      display: flex;
      justify-content: space-between;

      .page-form-title {
        font-size: 14px;
        color: #000000;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-weight: bold;
        margin-bottom: 10px;

        .el-icon {
          cursor: pointer;
        }
      }
    }
  }

  .vue-element-page-wrap {
    flex: 1;
  }
}
</style>
