<template>
	<el-drawer title="外协单信息" :with-header="false" v-model="visible" direction="rtl" size="100%">
		<div class="form-container column-container">
			<div class="form-btns-container">
				<span class="title-label">
					<el-icon><Document /></el-icon>
					<span>收回明细</span>
				</span>
				<!-- <el-button-group>
					<el-button v-if="editStatus" type="primary" icon="Finished" :loading="isSubmitting" @click="submitForm"> 保存 </el-button>
					<el-button v-else type="primary" icon="Finished" @click="cancel"> 确定 </el-button>
				</el-button-group> -->

				<div class="close-btn" @click="cancel">
					<i class="fa fa-times" aria-hidden="true" />
					<!-- <span>关闭</span> -->
				</div>
			</div>
			<el-form ref="formRef" class="master-container" :model="form" v-loading="loading" label-width="120px">
				<el-row :gutter="20">
					<el-col :span="6">
						<el-form-item label="收回日期" prop="formDate">
							<el-date-picker
							    v-if="editStatus"
								v-model="form.formDate"
								type="date"
								:clearable="false"
								value-format="YYYY-MM-DD"
								style="width: 100%"
							>
							</el-date-picker>
							<el-input v-model="form.formDate" v-else readonly />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<!-- 渲染数据区 -->
			<div class="el-table-container">
				<div class="el-table-inner-container">
					<el-table v-loading="loading" :data="receiptDetailList" size="small" border height="100%" :span-method="rowSpanMethod">
						<el-table-column label="行号" type="index" align="center" width="48" />
						<el-table-column label="批次号" align="center" prop="lotCode" width="104" />
						<el-table-column label="产品描述" align="center" prop="productDescription" width="320" />
						<el-table-column label="外协数量" align="center" prop="productNum" width="96" />
						<el-table-column
							label ='原箱号'
							align="center"
							prop="originalCarrier"
							width="320"
						/>
						<el-table-column
							label="新箱号"
							align="center"
							prop="newCarrier"
							width="320"
						/>
						<el-table-column label="外协工序" align="center" prop="processAlias" width="150" />
						<el-table-column label="收回数量" align="center" prop="receiptNum" width="104"/>
						<el-table-column label="备注" align="center" prop="remark">
							<template #default="scope">
								<el-input v-model="scope.row.remark" v-if="editStatus" />
								<el-input v-model="scope.row.remark" v-else readonly />
							</template>
						</el-table-column>
						<el-table-column label="操作" align="center" width="104">
							<el-button :disabled="!editStatus"  type="primary" :loading="isSubmitting" icon="Bell" @click="handleAddReceiptDetail()">收回</el-button>
					</el-table-column>
					</el-table>
				</div>
			</div>
		</div>
	</el-drawer>
</template>
<script setup>
import {getOrderDetailProcess} from '@/api/business/outsourcedOrderDetailProcess'
import {addReceiptDetail,getReturnReceiptDetail} from '@/api/business/returnReceiptDetail'
import { getTenant } from '@/utils/auth'
const emit = defineEmits(['handleSaveSuccess'])
const { proxy } = getCurrentInstance()
/** 表单抽屉 页变量 */
const loading = ref(false)
const visible = ref(false)
const editStatus = ref(true)
const detailInfo = ref({})
const isSubmitting = ref(false)
const spanProps = ref([])
const receiptDetailList = ref([])
const webHost = import.meta.env.VITE_APP_BASE_API
const form = ref({})

/****************************  方法区  ****************************/
/** 打开抽屉 */
const open = (row) => {
	reset()
	visible.value = true
    detailInfo.value = row
	//没有发出收回单
	if (row.returnReceiptDetailList.length ==0) {
		loading.value = true
		getOrderDetailProcess(row).then((response) => {
			receiptDetailList.value = response.data
			loading.value = false
			spanProps.value = ['lotCode','productDescription','productNum','originalCarrier','newCarrier'];
			spanPropGroup(receiptDetailList.value)
		})
	}
	else {
		console.log(row)
		getReturnReceiptDetail({id:row.id}).then(res => {
			receiptDetailList.value = res.data
			loading.value = false
			spanProps.value = ['lotCode','productDescription','productNum','originalCarrier','newCarrier'];
			spanPropGroup(receiptDetailList.value)
		})
	}
}

/** 取消按钮 */
const cancel = () => {
	visible.value = false
}

/***************************** 外协明细对话框相关 *****************************/
	/** 表单重置 */
const reset = () => {
	form.value = {
		formDate: proxy.parseTime(new Date(), '{y}-{m}-{d}'),
	}
	proxy.resetForm('formRef')
}
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 != 6 && columnIndex != 7 && columnIndex != 8) {
    //根据当前行号从map中获取开始合并的行根据当前行号从map中获取开始合并的行号，向下合并多少行
    const span = rowSpansMap.get(rowIndex);
    if (span != null) {
      return {
        rowspan: span, //向下合并span行
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
};
/** 提交按钮 */
function handleAddReceiptDetail() {
	proxy.$refs['formRef'].validate((valid) => {
		if (valid) {
			if(isSubmitting.value) {
				return
			}
			isSubmitting.value = true	
			if(detailInfo.value.returnReceiptDetailList.length ==0) {
				let detailList = []
				for(let i = 0;i<receiptDetailList.value.length;i++) {
					const newDetail = {
					outsourceDetailId: receiptDetailList.value[i].detailId,
					productDescription:  receiptDetailList.value[i].productDescription,
					lotCode: receiptDetailList.value[i].lotCode,
					lotId:receiptDetailList.value[i].lotId,
					dayworkId: receiptDetailList.value[i].dayworkId,
					productId: receiptDetailList.value[i].productId,
					productNum: receiptDetailList.value[i].productNum,
					receiptNum: receiptDetailList.value[i].receiptNum,
					originalCarrier: receiptDetailList.value[i].originalCarrier,
					originalCarrierCount: receiptDetailList.value[i].originalCarrierCount,
					newCarrier:receiptDetailList.value[i].newCarrier,
					newCarrierCount:receiptDetailList.value[i].newCarrierCount,
					remark: receiptDetailList.value[i].remark,
					technologicalProcessId:receiptDetailList.value[i].technologicalProcessId,
					technologyVersion:receiptDetailList.value[i].technologyVersion,
					technologicalProcessDetailId:receiptDetailList.value[i].technologicalProcessDetailId,
					processId:receiptDetailList.value[i].processId,
					processAlias:receiptDetailList.value[i].processAlias,
					processCode:receiptDetailList.value[i].processCode,
					processStepNumber:receiptDetailList.value[i].processStepNumber,
					formDate:form.value.formDate,
					supplierId:receiptDetailList.value[i].supplierId,
					supplierName:receiptDetailList.value[i].supplierName
			}
					detailList.push(newDetail)
				}
				console.log(detailList)
				addReceiptDetail(detailList).then((response) => {
					proxy.$modal.msgSuccess('添加成功')
					isSubmitting.value = false;
					visible.value = false
					emit('handleSaveSuccess')
				})
			}else {
				addReceiptDetail(receiptDetailList.value).then((response) => {
					proxy.$modal.msgSuccess('添加成功')
					isSubmitting.value = false;
					visible.value = false
					emit('handleSaveSuccess')
				})
			}
		}
	})
}

/** 暴露给父组件的方法 */
defineExpose({
	open
})
</script>
