<template>
	<div class="page-container column-container">
		<!-- 搜索区 -->
		<el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true" style="margin-right: 0px">
			<el-form-item label="单据号：" prop="formCode">
				<el-input v-model="queryParams.formCode" placeholder="请输入单据号" style="width: 144px" clearable />
			</el-form-item>
			<el-form-item label="表单日期：" prop="startTime">
				<el-date-picker
					v-model="queryParams.formStartDate"
					type="date"
					style="width: 144px"
					value-format="YYYY-MM-DD"
					placeholder="选择起始日期"
					clearable
				/>
				<span style="margin: 0 4px">~</span>
				<el-date-picker
					v-model="queryParams.endTime"
					type="date"
					style="width: 144px"
					value-format="YYYY-MM-DD"
					placeholder="选择结束日期"
					clearable
				/>
			</el-form-item>
			<el-form-item label="批次号：">
				<el-input
					placeholder="请输入关键字"
					v-model.trim="queryParams.lotCode"
					@keydown.enter.prevent
					clearable
					style="width: 130px"
				/>
			</el-form-item>
			<el-form-item label="产品描述：">
				<el-input
					placeholder="请输入关键字"
					v-model.trim="queryParams.productDescription"
					@keydown.enter.prevent
					clearable
					style="width: 130px"
				/>
			</el-form-item>
			<el-form-item style="margin-left: 0">
				<el-button type="info" icon="Search" @click="getList">搜索 </el-button>
			</el-form-item>
		</el-form>
		<div class="el-table-container">
			<div class="el-table-inner-container">
				<el-table
					ref="dataTable"
					:data="dataList"
					:span-method="rowSpanMethod"
					v-loading="loading"
					highlight-current-row
					border
					height="100%"
				>
					<el-table-column label="外协单号" align="center" prop="formCode" width="120" />
					<el-table-column label="外协日期" align="center" prop="formDate" width="120" />
					<el-table-column label="批次号" align="center" prop="lotCode" width="120" />
					<el-table-column label="产品描述" align="center" prop="productDescription" />
					<el-table-column label="产品数量" align="center" prop="productNum" width="80" />
					<el-table-column label="工序名称" align="center" prop="processAlias" width="80" />
					<el-table-column label="工序序号" align="center" prop="processStepNumber" width="80" />
					<el-table-column label="投产数" align="center" prop="productionNum" width="120">
						<template #default="scope">
							<el-input-number
								v-if="scope.row.editStatus"
								v-model="scope.row.productionNum"
								:min="1"
								controls-position="right"
								style="width: 100%"
							/>
							<span v-else>{{ scope.row.productionNum }}</span>
						</template>
					</el-table-column>
					<el-table-column label="合格数" align="center" prop="qualifiedNum" width="120">
						<template #default="scope">
							<el-input-number
								v-if="scope.row.editStatus"
								v-model="scope.row.qualifiedNum"
								:min="1"
								controls-position="right"
								style="width: 100%"
								@change="handleChangeloss(scope.row)"
							/>
							<span v-else>{{ scope.row.qualifiedNum }}</span>
						</template>
					</el-table-column>
					<el-table-column label="料损率" align="center" prop="loss" width="120">
						<template #default="scope">
							<span v-if="scope.row.loss > scope.row.lossLimit" style="color: red">{{ scope.row.loss }}</span>
							<span v-else>{{ scope.row.loss }}</span>
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center" width="104">
						<template #default="scope">
							<template v-if="scope.row.editStatus">
								<el-button type="success" icon="Finished" circle @click="handleSaveRow(scope.row)" />
								<el-button type="danger" icon="Close" circle @click="handleCancelRow(scope.row)" />
							</template>
							<el-button v-else type="primary" icon="Bell" @click="handleStartReport(scope.row)">报工</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</div>
		<!-- 分页 -->
		<pagination
			v-show="total > 0"
			:total="total"
			v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize"
			@pagination="getList"
		/>
	</div>
</template>

<script setup>
import { listProcess,editOutsourcedOrderDetailProcess } from '@/api/business/outsourcedOrderDetailProcess.js'
const { proxy } = getCurrentInstance()

/** 生产批次 */
const dataList = ref([])
const dataTable = ref(null)
const currentDaywork = ref({})
const spanProps = ref([])
const loading = ref(false)
const total = ref(0)
// 用于计算合并行的计数器
const spanArr = ref([])
/** 查询对象 */
const queryParams = ref({
	formCode: '',
	formStartDate: null,
	formEndDate: null,
	lotCode: '',
	productDescription: '',
	pageNum: 1,
	pageSize: 10
})

/***********************  工段相关事件  ****************************/
const getList = () => {
	loading.value = true
	listProcess(queryParams.value).then((res) => {
		dataList.value = res.rows
		total.value = res.total
		loading.value = false
		if (dataList.value.length > 0) {
			// getSpanArr(dataList.value, 'formCode')
			// getSpanArr(dataList.value, 'formDate')
			// getSpanArr(dataList.value, 'lotCode')
			// getSpanArr(dataList.value, 'productDescription')
			spanProps.value = ['formCode', 'formDate','lotCode','productDescription'];
			spanPropGroup(dataList.value)
		}
	})
}
const handleChangeloss = (row) => {
	let percent = (row.productionNum - row.qualifiedNum)/row.productionNum * 100; 
        row.loss = Math.ceil(percent * 100) / 100; 
}
const handleSaveRow = (row) => {
	var flag = true
	if(row.productionNum < row.qualifiedNum) {
		flag = false
		proxy.$modal.msgError('合格数不能大于投产数')
	}else {
		var tempList = dataList.value.filter(item => {
			return item.detailId ==row.detailId
		})
		var index = tempList.indexOf(row)
			if(index>0 && row.productionNum > tempList[index-1].qualifiedNum) {
				flag = false
				proxy.$modal.msgError('投产数不能大于上一道序合格数')
		}
	}
	if(flag) {
		editOutsourcedOrderDetailProcess(row).then((res) => {
		if(res.code == 200) {
			row.editStatus = false
			proxy.$modal.msgSuccess('报工成功')
			getList()		
		}
	})
	}
}
const handleCancelRow = (row) => {
	row.editStatus = false
	getList()
}
const handleStartReport = (row) => {
	//如果收回单已经被审核，则不能让他报工
	if(row.status == 1) {
		proxy.$modal.msgError('该外协单已被审核，不能再报工')
	}else{
	let tempList = dataList.value.filter(item => {
			return item.detailId ==row.detailId
		})
	let index = tempList.indexOf(row)
		if(index > 0) {
			//判断如果上一道序没有报工，不允许报此道序
			if(tempList[index-1].productionNum == 0) {
				proxy.$modal.msgError('上一道序未报工，不允许报此道序')
			}else {
				row.editStatus = true
				row.productionNum = tempList[index-1].qualifiedNum
			}		 	
		}else {
			row.editStatus = true
			row.productionNum = row.productNum
		}
	}
		
}

 
let rowSpansMap = new Map(); //存需要开始合并的行号，向下合并多少行

const spanPropGroup = (data) => {
  let oldRow = null; //需要合并的行
  rowSpansMap = new Map(); //重置Map
  oldRow = data[0]; //默认第0行为需要合并的行
  rowSpansMap.set(0, 1); //第0行，向下合并一行(其实就是自己单独一行)
  let spanRow = 0; //记录需要开始合并的行号
  for (let i = 1; i < data.length; i++) {
    const item = data[i];
    let isSame = true;
    //遍历需要判断的属性判断对应值是否全部相等
    for (let j = 0; j < spanProps.value.length; j++) {
      const prop = spanProps.value[j];
      //只要有一个属性值不相等则记录新的需要合并的行号
      if (item[prop] != oldRow[prop]) {
        oldRow = item;
        rowSpansMap.set(i, 1);
        spanRow = i;
        isSame = false;
        break;
      }
    }
    //如果所有属性值相同则所需要合并的行数+1
    if (isSame) {
      let span = rowSpansMap.get(spanRow);
      rowSpansMap.set(spanRow, span + 1);
    }
  }
};
 
const rowSpanMethod =({ row, column, rowIndex, columnIndex }) => {
  //采样值5-9列所对应的行不需要合并
  if (columnIndex != 5 && columnIndex != 6 && columnIndex != 7 && columnIndex != 8 && columnIndex != 9 && columnIndex != 10) {
    //根据当前行号从map中获取开始合并的行根据当前行号从map中获取开始合并的行号，向下合并多少行
    const span = rowSpansMap.get(rowIndex);
    if (span != null) {
      return {
        rowspan: span, //向下合并span行
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
};
// const rowSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
// 	if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4) {
// 		const _row = spanArr.value[rowIndex]
// 		const _col = _row > 0 ? 1 : 0
// 		return {
// 			rowspan: _row,
// 			colspan: _col
// 		}
// 	}
// }

// // groupBy 数组
// const groupBy = (data, params) => {
// 	const groups = {}
// 	data.forEach((v) => {
// 		const group = JSON.stringify(v[params])
// 		groups[group] = groups[group] || []
// 		groups[group].push(v)
// 	})
// 	return Object.values(groups)
// }

// // 计算 数据合并 索引
// const getSpanArr = (data, params) => {
// 	// 接收重构数组
// 	let arr = []

// 	// 设置索引
// 	let pos = 0

// 	// 控制合并的数组
// 	spanArr.value = []

// 	// arr 处理
// 	groupBy(data, params).map((v) => (arr = arr.concat(v)))

// 	arr.map((res) => {
// 		data.shift()
// 		data.push(res)
// 	})

// 	// spanArr 处理
// 	const redata = arr.map((v) => v[params])
// 	redata.reduce((old, cur, i) => {
// 		if (i === 0) {
// 			spanArr.value.push(1)
// 			pos = 0
// 		} else {
// 			if (cur === old) {
// 				spanArr.value[pos] += 1
// 				spanArr.value.push(0)
// 			} else {
// 				spanArr.value.push(1)
// 				pos = i
// 			}
// 		}
// 		return cur
// 	}, {})
// }

onMounted(() => {
	getList()
})
</script>
<style scoped>
.el-form--inline .el-form-item {
	margin-right: 20px;
}
</style>
