<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
					@keyup.enter="handleQuery" />
			</el-form-item> -->
			<el-form-item label="批次号：" prop="lotCode">
				<el-input v-model.trim="queryParams.lotCode" placeholder="请输入批次号" style="width: 130px" clearable
					@keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item label="收回单号：" prop="returnFormCode">
				<el-input v-model.trim="queryParams.returnFormCode" placeholder="请输入收回单号" style="width: 144px" clearable
					@keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item label="产品描述：" prop="productDescription">
				<el-input v-model.trim="queryParams.productDescription" placeholder="请输入产品描述" style="width: 144px" clearable
					@keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item label="外协商：" prop="supplierName">
				<el-input v-model.trim="queryParams.supplierName" placeholder="请输入外协商" style="width: 130px" clearable
					@keyup.enter="handleQuery" />
			</el-form-item>

			<el-form-item label="箱号：" prop="newCarrierName">
				<el-input v-model.trim="queryParams.newCarrierName" placeholder="请输入周转箱号" style="width: 144px" clearable
					@keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item label="外协检状态：">
				<el-select v-model="queryParams.inspectionStatus" clearable placeholder="请选择状态" style="width: 130px">
					<el-option v-for="dict in outsourced_inspection_status" :key="dict.value" :label="dict.label"
						:value="dict.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="状态：" prop="supplierName">
				<el-select v-model="queryParams.statusValue" placeholder="请选择周转状态" style="width: 120px;">
					<el-option v-for="item in statusLabels" :key="item.value" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="标识：">
				<el-select style="width: 200px" multiple v-model="queryParams.flags" clearable placeholder="请选择标识"
					@change="handleFlagChange">
					<el-option v-for="item in is_identification" :key="item.value" :label="item.label"
						:value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="收回日期：" prop="startTime">
				<el-date-picker v-model="queryParams.startTime" 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>
				<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
				<el-button type="success" icon="Search" @click="handleBatchTurnover">批量周转</el-button>
			</el-form-item>
		</el-form>
		<!-- 渲染数据区 -->
		<div class="el-table-container">
			<div class="el-table-inner-container">
				<el-table v-loading="loading" :data="dataList" size="small" border height="100%"
					@selection-change="handleOutsourceOrderSelectionChange">
					<el-table-column type="selection" align="center" />
					<!-- <el-table-column label="收回单号" align="center" prop="formCode" width="120" /> -->
					<el-table-column label="外协商" align="center" prop="supplierName" width="120" />
					<el-table-column label="收回单号" align="center" prop="returnFormCode" width="120" />
					<el-table-column label="批次号" align="center" prop="lotCode" width="110" />
					<el-table-column label="产品描述" align="center" prop="productDescription" />
					<el-table-column label="收回数" align="center" prop="auditNum" width="60" />
					<el-table-column label="收回日期" align="center" prop="formDate" width="100">
						<template #default="scope">
							{{ parseTime(scope.row.formDate, '{y}-{m}-{d}') }}
						</template>
					</el-table-column>
					<el-table-column label="备注" align="center" prop="remark" />
					<el-table-column label="周转箱号" align="center" prop="productionCarrier">
						<template #default="scope">
							<div>{{ scope.row.productionDeptId === '0' ? scope.row.newCarrierName : scope.row.productionCarrier }}
							</div>
						</template>
					</el-table-column>
					<el-table-column label="周转工段" align="center" prop="productionDeptName" width="90" />
					<el-table-column label="外协检" width="100px" align="center" prop="inspectionStatus">
						<template #default="scope">
							<dict-tag :options="outsourced_inspection_status" :value="scope.row.inspectionStatus" />
						</template>
					</el-table-column>
					<el-table-column label="状态" align="center" prop="status" width="80">
						<template #default="scope">
							<div>{{ scope.row.productionDeptId === '0' ? '待周转' : '已周转' }}</div>
						</template>
					</el-table-column>
					<el-table-column label="批次标识" align="center" prop="lotID">
						<template #default="scope">
							<el-tag v-if="scope.row.isAmend == 1" class="spacing" type="danger">{{ "工艺修改" }}</el-tag>
							<el-tag v-if="scope.row.isWasteRecycling == 1" class="spacing" type="danger">{{ "废品回用" }}</el-tag>
							<el-tag v-if="scope.row.isWasteRecycling == 0 && scope.row.isAmend == 0" class="spacing">{{
								"正常批次" }}</el-tag>
							<el-tag v-if="scope.row.isSuperaddition == 1" class="warning">{{
								"追增" }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="64">
						<template #default="scope">
							<el-button v-if="scope.row.flag" link type="warning" icon="Edit"
								@click="handleShowTurnoverDialog(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" />
		<!-- 周转信息弹窗 -->
		<dialog-return-turnover ref="dialogReturnTurnoverRef" @handleSaveSuccess=getList() />
		<dialog-return-turnover-batch ref="dialogReturnTurnoverBatchRef" @handleSaveSuccess="getList" />
	</div>
</template>

<script setup name="ReturnTurnover">
import { getFinishedReturnList, getProcessInspectionList, checkCarriers, getProcessInspectionLists } from '@/api/business/returnTurnover'
import { getP2NeedCheckProcess } from '@/api/business/p2'
import dialogReturnTurnover from './DialogReturnTurnover.vue';
import DialogReturnTurnoverBatch from './DialogReturnTurnoverBatch.vue';
import { isTakeStock } from "@/api/business/takeStockPeriod.js"
const { proxy } = getCurrentInstance()
const dataList = ref([])
const loading = ref(false)
const ids = ref([])
const total = ref(0)
const selections = ref([])
const statusLabels = ref([{
	value: '0',
	label: '全部'
}, {
	value: '1',
	label: '待周转'
}, {
	value: '2',
	label: '已周转'
}])
/** 查询对象 */
const queryParams = ref({
	pageNum: 1,
	pageSize: 10,
	formCode: null,
	formDate: null,
	statusValue: '1'
})
/** 字典数组区 */
const { outsourced_inspection_status } = proxy.useDict("outsourced_inspection_status");

const is_identification = ref([
	// 	{
	// 	value: '1',
	// 	label: '废品回用'
	// }, 
	{
		value: '2',
		label: '工艺修改'
	}, {
		value: '4',
		label: '追增'
	}, {
		value: '3',
		label: '正常批次'
	}])

/***********************  方法区  ****************************/

/** 查询收回周转 */
function getList() {
	loading.value = true
	getFinishedReturnList(queryParams.value).then((response) => {
		dataList.value = response.rows
		total.value = response.total
		loading.value = false
	})
}

/** 搜索按钮操作 */
function handleQuery() {
	queryParams.value.pageNum = 1
	getList()
}

/** 重置按钮操作 */
function resetQuery() {
	proxy.resetForm('queryRef')
	queryParams.value.statusValue = '1'
	handleQuery()
}

/** 修改周转按钮操作 */
function handleShowTurnoverDialog(row) {
	console.log(row)
	//proxy.$refs.dialogReturnTurnoverRef.open(row)
	//判断该批次的工序是否需要审核
	// /* 
	getP2NeedCheckProcess("Y").then(res => {
		if (res.code == 200) {
			//需要序检的工序
			var process = []
			let needCheckProcessCodeList = res.rows.map(item => item.prcode.trim())
			let returnReceiptProcessCodeList = row.finishedProcesses.map(v => ({ processCode: v.processCode, processStepNumber: v.processStepNumber, returnReceiptDetailId: v.returnReceiptDetailId }))
			for (let i = 0; i < needCheckProcessCodeList.length; i++) {
				for (let j = 0; j < returnReceiptProcessCodeList.length; j++) {
					if (needCheckProcessCodeList[i] == returnReceiptProcessCodeList[j].processCode) {
						process.push(returnReceiptProcessCodeList[j])
					}
				}
			}
			console.log(needCheckProcessCodeList)
			console.log(returnReceiptProcessCodeList)
			console.log(process)
			process.sort((a, b) => (a.processStepNumber > b.processStepNumber ? 1 : -1))
			console.log('process', process)
			if (process.length > 0) {
				getProcessInspectionList(process[process.length - 1]).then(res => {
					if (res.code == 200) {
						if (res.data) {
							//判断盘点
							isTakeStock().then(response => {
								if (response.data) {
									proxy.$modal.msgError('正在盘点，不能周转')
								} else {
									proxy.$refs.dialogReturnTurnoverRef.open(row)
								}
							})
						}
						else {
							proxy.$modal.msgError('当前批次检查未处于合格状态，暂时无法周转')
						}
					}
				})
			} else {
				proxy.$refs.dialogReturnTurnoverRef.open(row)
			}
		}
	})
	// */

	// proxy.$refs.dialogReturnTurnoverRef.open(row)
}

/** 导出按钮操作 */
function handleExport() {
	proxy.download(
		'business/returnReceipt/export',
		{
			...queryParams.value
		},
		`order_${new Date().getTime()}.xlsx`
	)
}

function handleFlagChange() {
}

function handleOutsourceOrderSelectionChange(selection) {
	selections.value = selection
}

async function handleBatchTurnover() {
	// 批量周转
	// 判断是否选择批次周转项
	if (selections.value.some(v => v.productionDeptId != '0')) {
		proxy.$modal.msgError('请选择未周转外协单进行周转')
		return
	}
	if (selections.value.length === 0) {
		proxy.$modal.msgError('请选择一条外协单进行周转')
		return
	}
	// 先判断批量周转是否是同一个产品
	if (selections.value.findIndex(v => v.productId != selections.value[0].productId) >= 0) {
		proxy.$modal.msgError('请选择同一产品进行批量周转')
		return
	}
	// 判断批量周转中是否存在单批单改
	if (selections.value.length > 1 && selections.value.findIndex(v => v.isAmend == 1 || v.isWasteRecycling == 1) >= 0) {
		proxy.$modal.msgError('请选择标准工艺批次进行批量周转')
		return
	}
	const carriers = selections.value.map(v => v.newCarrierName).join()
	const res = await checkCarriers({ carriers: carriers })
	if (!res.data) {
		proxy.$modal.msgError('请不要选择外协箱外协单进行批量周转')
		return
	}
	// /* 
	getP2NeedCheckProcess("Y").then(res => {
		if (res.code == 200) {
			//需要序检的工序
			var process = []
			let needCheckProcessCodeList = res.rows.map(item => item.prcode.trim())
			let returnReceiptProcessCodeList = []
			selections.value.forEach(e => {
				let itemReturnCodes = e.finishedProcesses.map(v => ({ processCode: v.processCode, processStepNumber: v.processStepNumber, returnReceiptDetailId: v.returnReceiptDetailId }))
				let item = itemReturnCodes.reverse().find(e => needCheckProcessCodeList.some(t => t === e.processCode))
				if (item != null) {
					returnReceiptProcessCodeList.push(item)
				}
			})
			process.push(...returnReceiptProcessCodeList)
			// let returnReceiptProcessCodeList = row.finishedProcesses.map(v => ({ processCode: v.processCode, processStepNumber: v.processStepNumber, returnReceiptDetailId: v.returnReceiptDetailId }))
			// for (let i = 0; i < needCheckProcessCodeList.length; i++) {
			// 	for (let j = 0; j < returnReceiptProcessCodeList.length; j++) {
			// 		if (needCheckProcessCodeList[i] == returnReceiptProcessCodeList[j].processCode) {
			// 			process.push(returnReceiptProcessCodeList[j])
			// 		}
			// 	}
			// }
			console.log('needCheckProcessCodeList', needCheckProcessCodeList)
			console.log('returnReceiptProcessCodeList', returnReceiptProcessCodeList)
			console.log('process', process)
			process.sort((a, b) => (a.processStepNumber > b.processStepNumber ? 1 : -1))
			console.log('process', process)
			if (process.length > 0) {
				getProcessInspectionLists(process).then(res => {
					if (res.code == 200) {
						if (res.data) {
							//判断盘点
							isTakeStock().then(response => {
								if (response.data) {
									proxy.$modal.msgError('正在盘点，不能周转')
								} else {
									proxy.$refs.dialogReturnTurnoverBatchRef.openBatch(selections.value)
								}
							})
						}
						else {
							proxy.$modal.msgError('当前批次检查未处于合格状态，暂时无法周转')
						}
					}
				})
			} else {
				//判断盘点
				isTakeStock().then(response => {
					if (response.data) {
						proxy.$modal.msgError('正在盘点，不能周转')
					} else {
						proxy.$refs.dialogReturnTurnoverBatchRef.openBatch(selections.value)
					}
				})
			}
		}
	})
	// */

	// proxy.$refs.dialogReturnTurnoverBatchRef.openBatch(selections.value)
}

getList();
</script>
