<template>
  <div>
    <layout>
      <!-- <layout-header> -->
        <div class="gva-table-box">
			<h1 style="margin: 0%;margin-bottom: 6px;">出库报工</h1>
			<el-row :gutter="24" style="margin-bottom: 6px;">
				  <el-input v-model="add_searchInfo" placeholder="请扫描子订单编号"
				  			  @keyup.enter="add_onSubmit"
								  id="searchInput" 
				  			  style="width: 220px;height: 50px;margin-left: 10px;">
				  			  </el-input>
				  <el-button type="primary" icon="search" @click="add_onSubmit" style="height: 50px;font-size: 20px;">查询</el-button>
				  <el-button type="primary" icon="" @click="Restore_onSubmit" style="height: 50px;font-size: 20px;">恢复未出库</el-button>
				  <el-button type="primary" icon="" @click="add_Dialog" style="height: 50px;font-size: 20px;">确认出库</el-button>
			</el-row>
		</div>
      <!-- </layout-header> -->
      <layout>
        <layout-content >
          <div class="gva-table-box">
           <el-table ref="multipleTable" style="width: 100%;height: 64vh" tooltip-effect="dark"
                      :row-style="{ height: '40px' }"  :header-cell-style="{ padding: '0px' }"
                      :cell-style="{ padding: '0px' }" :header-row-style="{ height: '20px' }"
                      :data="add_tableData"  border row-key="ID" size="small"  
					  :cell-class-name="tableDataCellClass"
                      highlight-current-row="true"  @row-dblclick="add_updateCompanyFunc"
                      @row-click="add_tableRowClick" :show-overflow-tooltip="true"
                      @selection-change="handleSelectionChange">
			        <!-- <el-table-column type="selection" width="80" /> -->
              <el-table-column  sortable  align="left" label="订单编号" prop="订单编号" width="120" />
              <el-table-column  sortable  align="left" label="订单子编号" prop="子订单编号" width="140"/>
              <el-table-column  sortable  align="left" label="生产款号" prop="款号" width="220"/>
              <el-table-column  sortable  align="left" label="款式" prop="款式" width="100"/>
              <el-table-column  sortable  align="left" label="色系名称" prop="颜色" width="150"/>
			  <el-table-column  sortable  align="left" label="是否出库" prop="是否出库" width="120"/>
			  <el-table-column  sortable  align="left" label="出库时间" prop="ck_rq" width="120"/>
            </el-table>
            <div class="dialog-footer" style="text-align: left;margin-right: 60px;">
			</div>
          </div>
      </layout-content>
      </layout>
    </layout>
  </div>
</template>

<script setup>
// 全量引入格式化工具 请按需保留
import { Layout, LayoutSider, LayoutContent } from '@arco-design/web-vue';
import {ref, reactive} from 'vue'
import {getSpotList,getSpotTab} from '@/api/mes/job'
import {ElMessage} from "element-plus";
// import { get } from 'scriptjs';
defineOptions({name: 'Company'})
import { useUserStore } from '@/pinia/modules/user'
//获取用户登录信息
const userStore = useUserStore()
const _username = ref('')
_username.value = userStore.userInfo.userName + '/' + userStore.userInfo.nickName
console.log('获取用户名称',_username.value)
//全局调用获取当前日期
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要补零
const day = String(today.getDate()).padStart(2, '0');
const hours = String(today.getHours()).padStart(2, '0');
const minutes = String(today.getMinutes()).padStart(2, '0');
const seconds = String(today.getSeconds()).padStart(2, '0');
const currentDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
const currentDates = `${year}-${month}-${day}`;
//自动聚焦光标input
const getMachineMacdata = async () => {
	setTimeout(() => {
		const inputElement = document.getElementById('searchInput');
		if (inputElement) {
			inputElement.focus();		
		}
	}, 100); // 延迟100毫秒
}
getMachineMacdata();

//全局调用参数
const add_searchInfo = ref('')//搜索
const add_tableData = reactive([])//表格
const _orderid = ref('')//订单子编号
const searcs = ref('')//默认记录扫描两次出库

//表格行点击
const add_tableRowClick = async (row)=>{
//   add_searchInfo.value = row.子订单编号
	console.log(row)
	_orderid.value = row.子订单编号
}

//点击【查询】按钮
const add_onSubmit = async ()=>{
	//自动聚焦光标input
	getMachineMacdata();
	
  if(add_searchInfo.value === ''){
    const WorkListdata = [];
	searcs.value = '';
    add_tableData.splice(0,add_tableData.length,...WorkListdata);
    ElMessage({type: 'warning',message: '请扫描子订单编号' })
  }else{
	  if (add_searchInfo.value.includes('-')) {//子订单编号
		  if(searcs.value == ''){ //第一次扫码 查询数据
			  console.log("查询子订单编号数据")
			  const getSpotLists = await getSpotList({order:add_searchInfo.value,code:'出库'});//出库报工修改
			  add_tableData.splice(0,add_tableData.length,...getSpotLists.data.data);
			  add_searchInfo.value = ''
			  searcs.value = 1;
			  return;
		  }
		  if(searcs.value == 1){//第二次扫码，如果两次相同代表可以出库
			if(add_tableData[0]['子订单编号'] === add_searchInfo.value){
				console.log("出库")
				add_Dialogs();//调用出库按钮
				searcs.value = '';
			}else{
				ElMessage({type: 'warning',message: '两次扫码不一致，请重新扫描子订单出库' })
				searcs.value = '';
				const WorkListdata = [];
				add_tableData.splice(0,add_tableData.length,...WorkListdata);
				add_searchInfo.value = ''
			}
		  }
	  } else {//订单编号
			console.log("查询订单编号数据")
			const WorkListdata = [];
			searcs.value = '';
			const getSpotLists = await getSpotList({order:add_searchInfo.value,code:'出库'});
			add_tableData.splice(0,add_tableData.length,...getSpotLists.data.data);
			add_searchInfo.value = ''
	  }
    
  }
};

//确认出库按钮
const add_Dialog = async () => {
	// console.log("确认出库按钮")
	let params = {}
	if(_orderid.value === ''){
		params.order_id = add_tableData[0]['子订单编号'];
	}else{
		params.order_id = _orderid.value;
	}
	params.code = '出库';
	params.sys_id = _username.value;
	const ck_gettab = await getSpotTab(params);// 发起出库请求
	if (ck_gettab.code === 0) {// 出库成功后的处理
		searcs.value = '';
		ElMessage({ type: 'success', message: '出库成功'});
		const getSpotLists = await getSpotList({order:params.order_id,code: '出库'});// 获取并更新表格数据
		add_tableData.splice(0, add_tableData.length, ...getSpotLists.data.data);
		add_searchInfo.value = ''
	}else {
		searcs.value = '';
	    const getSpotLists = await getSpotList({order: params.order_id, code: '出库'}); // 出库失败，重新获取数据
	    add_tableData.splice(0, add_tableData.length, ...getSpotLists.data.data);
	  }
}

//确认出库按钮
const add_Dialogs = async () => {
	if(add_tableData[0]['子订单编号'] === add_searchInfo.value){
		 let params = {
		   order_id: add_searchInfo.value,
		   code: '出库',
		   sys_id: _username.value,
		 };
		 console.log(params)
			const ck_gettab = await getSpotTab(params);// 发起出库请求
			if (ck_gettab.code === 0) {// 出库成功后的处理
				 searcs.value = '';
				 ElMessage({ type: 'success', message: '出库成功' });
				 const getSpotLists = await getSpotList({ order: add_searchInfo.value, code: '出库' });// 获取并更新表格数据
				 add_tableData.splice(0, add_tableData.length, ...getSpotLists.data.data);
				 add_searchInfo.value = ''
			}else {
			 searcs.value = '';
		     const getSpotLists = await getSpotList({ order: add_searchInfo.value, code: '出库' }); // 出库失败，重新获取数据
		     add_tableData.splice(0, add_tableData.length, ...getSpotLists.data.data);
		   }
	}else{
		 ElMessage({type: 'warning',message: '两次扫码不一致，请重新扫描子订单出库' })
		 searcs.value = '';
		 const WorkListdata = [];
		 add_tableData.splice(0,add_tableData.length,...WorkListdata);
		 add_searchInfo.value = ''
	}
	return false;
	
//下面代码代表多条出库
  if (add_tableData.length > 1) {
	searcs.value = '';
    ElMessage({ type: 'warning', message: '出库出现多条数据'});
    return;
  }
  const orderData = add_tableData[0];
  if (add_tableData[0]['子订单编号'] !== add_searchInfo.value) {
	const WorkListdata = [];
	searcs.value = '';
	const getSpotLists = await getSpotList({order:add_searchInfo.value,code:'出库'});
	add_tableData.splice(0,add_tableData.length,...getSpotLists.data.data);
	return;
  }
  let params = {
    order_id: orderData['子订单编号'],
    code: '出库',
    sys_id: _username.value,
  };
  try {
    // 发起出库请求
    const ck_gettab = await getSpotTab(params);
    if (ck_gettab.code === 0) {
      // 出库成功后的处理
      add_searchInfo.value = '';
      searcs.value = '';
      ElMessage({ type: 'success', message: '出库成功' });
      // 获取并更新表格数据
      const getSpotLists = await getSpotList({ order: orderData['子订单编号'], code: '出库' });
      add_tableData.splice(0, add_tableData.length, ...getSpotLists.data.data);
    } else {
		searcs.value = '';
      // 出库失败，重新获取数据
      const getSpotLists = await getSpotList({ order: add_searchInfo.value, code: '出库' });
      add_tableData.splice(0, add_tableData.length, ...getSpotLists.data.data);
    }
  } catch (error) {
    console.error("出库请求失败", error);
    ElMessage({ type: 'error', message: '出库请求失败，请稍后重试' });
  }
};

//恢复未出库按钮
const Restore_onSubmit = async ()=>{
	if(_orderid.value === '' || _orderid.value === null){
		ElMessage({type: 'warning',message: '请点击选择恢复的子订单' })
	}else{
		let params = {}
		params.order_id = _orderid.value;
		params.code_ck_rq = currentDates;
		params.code = '恢复';
		params.sys_id = _username.value;
		const ck_gettab = await getSpotTab(params);
		if (ck_gettab.code === 0) {
		searcs.value = '';
		add_searchInfo.value = ''
		ElMessage({type: 'success',message: '恢复成功'});
		const getSpotLists = await getSpotList({order:_orderid.value,code:'出库'});
		add_tableData.splice(0,add_tableData.length,...getSpotLists.data.data);
		}
	}
	//自动聚焦光标input
	getMachineMacdata();
}

//复选框选择
const ckSelection = ref('')
const handleSelectionChange = (selection, type) => {
  const ids = selection.map(item => {
    return item.子订单编号
  })
  ckSelection.value = ids.join(',')
  console.log(ckSelection.value)
}

// =========== 分页 ===========
// 分页相关的响应式变量
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
// 分页
const handleCurrentChange = (val) => {
  page.value = val;
  _getStaffList();
};

// 修改页面容量 点击多少条/页
const handleSizeChange = (val) => {
  page.value = 10;//默认显示
  pageSize.value = val;
  _getStaffList();
};

//根据出库状态文字颜色
const tableDataCellClass = ({row, column, rowIndex, columnIndex}) =>{
  if(row['是否出库'] === '已出库'){
    return 'status-plan-usage-low';
  }
  if(row['是否出库'] === '未出库'){
    return 'statusy-plan-usage-low';
  }
}
</script>
<style scoped>
/* 根据出库状态文字颜色 */
:deep(.status-plan-usage-low div) {
  color: #8c939d  !important;
}
:deep(.statusy-plan-usage-low div) {
  color: blue !important;
}
.form-container {
  display: flex;
  flex-wrap: wrap;
}
.form-column {
  /*flex: 1;*/
  margin-right: 15px; /* 调整列之间的间距 */
}
/* 左侧输入框宽度调整 */
.form-column .el-form-item .el-input {
  width: 150px; /* 调整左侧输入框的宽度 */
}
/* 媒体查询，根据需要调整断点 */
@media screen and (max-width: 768px) {
  .form-column {
    flex: 1 0 100%; /* 在小屏幕下变成单列布局 */
    margin-right: 0;
  }
}
.JKWTree-container {
  display: flex;
}
.JKWTree-tree {
  /*width: 300px;*/
  background-color: #fff;
  padding: 10px;
  margin-right: 20px;
}
.JKWTree-tree h3 {
  font-size: 15px;
  font-weight: 700;
  margin: 10px 0;
}
.JKWTree-content {
  flex: 1;
}
/* 表格复选框大小调整 */
:deep(.el-checkbox.el-checkbox--small .el-checkbox__inner) {
    width: 45px; /* 复选框宽度 */
    height: 23px; /* 复选框高度 */
}
:deep(.el-checkbox.el-checkbox--small.is-checked .el-checkbox__inner::after) {
    transform: scale(1.2) rotate(45deg); /* 调整选中后的对勾大小 */
    top: 5%; /* 调整对勾位置 */
    left: 40%; /* 调整对勾位置 */
    width: 5px; /* 调整对勾宽度 */
    height: 9px; /* 调整对勾高度 */
}
/* 选中某行时的背景色 */
:deep(.el-table__body tr.current-row) > td {
  background: #ff80ff !important;
}
</style>
<style scoped>
:deep(.el-table td .cell) {
  line-height: 20px !important;
}
:deep(.el-tabs__header){
  margin-bottom: 0;
}
.search{
  margin-left: 0px !important;
  margin-right: 10px !important;
}
.bt{
  margin-left: 2px !important;
  padding: 3px !important;
  font-size: 12px;
}
.el-tabs__header{
  margin: 0px !important;
}
.gva-table-box{
  padding: 0px !important;
	margin-left: 5px !important;
}
.mab{
  margin-bottom: 5px;
}
/* 搜索样式 */
::v-deep .el-input__wrapper #searchInput {  
  font-size: 16px; 
}  

</style>
