<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  type="primary" icon="Finished" :loading="isSubmitting" @click="submitForm('save')"> 保存 </el-button>
					<el-button v-if="form.status == 1" type="danger" icon="Close" @click="submitForm('notCheck')"> 审核不通过 </el-button>
					<el-button v-else type="success" icon="Check" @click="submitForm('saveAndCheck')"> 保存并审核通过 </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-col :span="6">
						<el-form-item label="外协商名称" prop="supplierName">
							<el-input v-if="editStatus" v-model="form.supplierName" readonly placeholder="请输入外协商名称">
								<template #append>
									<el-button icon="Search" @click="handleShowDialogSuppliers" />
								</template>
							</el-input>
							<span v-else>{{ form.supplierName }}</span>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
				<!-- 渲染数据区 -->
				<div class="form-details-btns-container">
				<el-button type="primary" icon="Plus" v-if="form.supplierName!=''" :disabled="!editStatus"  @click="handleShowDialogOutSourceDetails"> 添加收回明细 </el-button>
			</div>
			<!-- 渲染数据区 -->
			<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="auditNum" width="104">
							<template #default="scope">
								<el-input-number
									v-model="scope.row.auditNum"
									:min="0"
									controls-position="right"
									style="text-align: center"
								/>
							</template>
						</el-table-column>
						<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="100">
							<template #default="scope">
						<el-button
							icon="delete"
							link
							type="danger"
							@click="handleDelReturnReceiveDetail(scope.row)"
							>删除
						</el-button>
					</template>
					</el-table-column>
					</el-table>
				</div>
			</div>			
		</div>
		<!-- 收回明细选择 -->
		<dialog-outsource-details
			ref="dialogOutsourceDetailsRef"
			:multiple-selected="handleMultipleSelectedOutsourceDetails"
		/>
		<!-- 外协商选择 -->
		<dialog-suppliers ref="dialogSuppliersRef" :single-selected="handleSingleSelectedSuppliers" />
	</el-drawer>
</template>
<script setup>
import {getOrderDetailProcess} from '@/api/business/outsourcedOrderDetailProcess'
import {saveOrUpdateDetail,getReturnReceiptDetail} from '@/api/business/returnReceiptDetail'
import { getTenant } from '@/utils/auth'
import dialogOutsourceDetails from './DialogOutsourceDetails'
import dialogSuppliers from './DialogSuppliers'
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
	//外协商填写完收回明细
		editStatus.value = false
		if(row.returnReceiptDetailList.length>0) {
		getReturnReceiptDetail({id:row.id}).then(res => {
			loading.value = true
			receiptDetailList.value = res.data
			form.value.supplierName = receiptDetailList.value[0].supplierName
			form.value.formDate = receiptDetailList.value[0].formDate
			form.value.status = receiptDetailList.value[0].status
			loading.value = false
			spanProps.value = ['lotCode','productDescription','productNum','originalCarrier','newCarrier'];
			spanPropGroup(receiptDetailList.value)
		})
	}else{
		editStatus.value = true
		getOrderDetailProcess(row).then((response) => {
			loading.value = true
			receiptDetailList.value = response.data
			form.value.supplierName = receiptDetailList.value[0].supplierName
			form.value.formDate = receiptDetailList.value[0].formDate
			form.value.status = receiptDetailList.value[0].status
			loading.value = false
			spanProps.value = ['lotCode','productDescription','productNum','originalCarrier','newCarrier'];
			spanPropGroup(receiptDetailList.value)
		})
		
	}
}

/** 取消按钮 */
const cancel = () => {
	visible.value = false
}
/***************************** 外协商对话框相关 *****************************/
//打开外协商选择对话框
const handleShowDialogSuppliers = () => {
	proxy.$refs.dialogSuppliersRef.open()
}
//外协商选择带回
const handleSingleSelectedSuppliers = (selection) => {
	console.log(selection)
	//如果收回明细已存在，切换外协商名字，删除添加的收回明细
	if(selection.id != form.value.supplierId && receiptDetailList.value.length>0) {
		receiptDetailList.value = []
	}
	form.value.supplierId = selection.id
	form.value.supplierName = selection.name
}

/***************************** 外协明细对话框相关 *****************************/
// 打开外协明细选择对话框
const handleShowDialogOutSourceDetails = () => {
	var info = {} 
	info.outsourceDetailIds = receiptDetailList.value.length>0?receiptDetailList.value.map((item) => item.outsourceDetailId):[]
	info.supplierId = form.value.supplierId
	proxy.$refs.dialogOutsourceDetailsRef.open(info)
}
// 外协明细选择带回
const handleMultipleSelectedOutsourceDetails = (selection) => {
	console.log(selection)
	for(let i = 0;i<selection.length;i++) {
		for(let j = 0;j<selection[i].processes.length;j++) {
			const newDetail = {
				outsourceDetailId: selection[i].processes.detailId,
					productDescription: selection[i].processes.productDescription,
					lotCode: selection[i].processes.lotCode,
					lotId:selection[i].processes.lotId,
					dayworkId:selection[i].processes.dayworkId,
					productId: selection[i].processes.productId,
					productNum: selection[i].processes.productNum,
					receiptNum: selection[i].processes.receiptNum,
					originalCarrier: selection[i].processes.originalCarrier,
					originalCarrierCount: selection[i].processes.originalCarrierCount,
					newCarrier:selection[i].processes.newCarrier,
					newCarrierCount:selection[i].processes.newCarrierCount,
					remark: selection[i].processes.detailRemark,
					technologicalProcessId:selection[i].processes.technologicalProcessId,
					technologyVersion:selection[i].processes.technologyVersion,
					technologicalProcessDetailId:selection[i].processes.technologicalProcessDetailId,
					processId:selection[i].processes.processId,
					processAlias:selection[i].processes.processAlias,
					processCode:selection[i].processes.processCode,
					processStepNumber:selection[i].processes.processStepNumber,
					formDate:form.value.formDate,
					status:0,
					supplierId:selection[i].processes.supplierId,
					supplierName:selection[i].processes.supplierName
			}
		    receiptDetailList.value.push(newDetail)
		}
		console.log(receiptDetailList.value)
		}
}
	/** 表单重置 */
const reset = () => {
	form.value = {
		formDate: proxy.parseTime(new Date(), '{y}-{m}-{d}'),
		supplierId: '0',
		supplierName: '',
		status:0
	}
	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  && columnIndex != 9) {
    //根据当前行号从map中获取开始合并的行根据当前行号从map中获取开始合并的行号，向下合并多少行
    const span = rowSpansMap.get(rowIndex);
    if (span != null) {
      return {
        rowspan: span, //向下合并span行
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
};
/** 提交按钮 */
function submitForm(data) {
	proxy.$refs['formRef'].validate((valid) => {
		if (valid) {
			var flag = true;
			if(isSubmitting.value) {
				return
			}
			isSubmitting.value = true	
			//数据从发出工序明细取得，处理数据
			if(editStatus) {
				var 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)
				}
			}
			if(!detailInfo.value || (detailInfo.value.returnReceiptDetailList.length ==0&&receiptDetailList.length == 0)) {
				proxy.$modal.msgError('明细不能为空')
				flag = false
				isSubmitting.value = false
			}
			for(var i=0;i< receiptDetailList.value.length;i++) {
					//审核不通过
				if(data =='notCheck') {
					receiptDetailList.value[i].status = 0
				}
				//审核通过
				if(data =='saveAndCheck') {
					receiptDetailList.value[i].status = 1
				}
					//外协没填收回数量，第一行工序确定数量不能超过产品数量，第二行工序确定数量不能超过上一道序的确定数量
					var index = receiptDetailList.value.indexOf(receiptDetailList.value[i])
					if(index>0 && receiptDetailList.value[i].auditNum >receiptDetailList.value[index-1].auditNum) {
						flag = false
						isSubmitting.value = false
						proxy.$modal.msgError('第' + (i + 1) +'行确定数量不能超过上一道序的确定数量')
					}
			    if(receiptDetailList.value[i].auditNum > receiptDetailList.value[i].productNum) {
					flag = false
					isSubmitting.value = false
					proxy.$modal.msgError('第' + (i + 1) + '行确定数量不能大于产品数量' + receiptDetailList.value[i].productNum)
			}
				if(receiptDetailList.value[i].auditNum == 0) {
					flag = false
					isSubmitting.value = false;
					proxy.$modal
						.confirm("第" + (i+1) + "行确定数量为0,是否确认保存？")
						.then(() => {
							flag = true
					})
					}
				}
			//审核不通过
			if(data =='notCheck') {
				for(var i=0;i< receiptDetailList.value.length;i++) {
					receiptDetailList.value[i].status = 0
				}
			}
			if(data =='saveAndCheck') {
				for(var i=0;i< receiptDetailList.value.length;i++) {
					receiptDetailList.value[i].status = 1
				}
			}
			if(flag) {
				var detail = {
					outsourceDetailId: detailInfo.value.id,
					detailList: receiptDetailList.value,
					dayworkId: detailInfo.value.dayworkId
				}
				saveOrUpdateDetail(detail).then((response) => {
					proxy.$modal.msgSuccess('添加成功')
					isSubmitting.value = false;
					visible.value = false
					emit('handleSaveSuccess')
				})
			}
			}
	})
}
//反选操作
function handleDelReturnReceiveDetail(row) {
	proxy.$modal
    .confirm("是否确认删除选中的数据项,如果删除，同时删除该批次下所有工序？")
    .then(function () {
      receiptDetailList.value = []
    })
}

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