<template>
	<div class="mesBusLog-container">
		<el-dialog v-model="state.isShowDialog" v-if="state.isShowDialog" width="90%" draggable="" :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<span>{{ props.title }}</span>
				</div>
			</template>
			<div style="width: 100%" v-if="step == 2">
				<el-form :model="ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
					<el-row :gutter="35">
						<el-col :xs="24" :sm="12" :md="12" :lg="5" :xl="5" class="mb20">
							<el-form-item label="工序" prop="processCode">
								<el-input :model-value="inspSearchState.processCode" placeholder="请输入工序" disabled clearable />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="5" :xl="5" class="mb20">
							<el-form-item label="产品" prop="productCode">
								<el-input :model-value="inspSearchState.productCode" placeholder="请输入产品" clearable disabled />
							</el-form-item>
						</el-col>
						<!-- <el-col :xs="24" :sm="12" :md="12" :lg="5" :xl="5" class="mb20">
              <el-form-item label="检验类型" prop="inspType">
                <el-select clearable v-model="ruleForm.inspType" placeholder="请选择检验类型">
                  <el-option v-for="(item,index) in dl('checkTypes')"  :key="index" :value="item.code" :label="`${item.name} [${item.value}]`"></el-option>

                </el-select>
              </el-form-item>
            </el-col> -->
						<!--            <el-col :xs="24" :sm="12" :md="12" :lg="5" :xl="5" class="mb20">-->
						<!--              <el-form-item label="控制方法" prop="opAccount">-->
						<!--&lt;!&ndash;                <el-input v-model="ruleForm.opAccount" placeholder="请输入控制手段" clearable />&ndash;&gt;-->
						<!--                <el-select clearable v-model="ruleForm.inspType" placeholder="请选择控制手段">-->
						<!--                  <el-option v-for="(item,index) in dl('controlMethod')"  :key="index" :value="item.code" :label="`${item.name} [${item.value}]`"></el-option>-->

						<!--                </el-select>-->
						<!--              </el-form-item>-->
						<!--            </el-col>-->
						<el-col :xs="24" :sm="12" :md="12" :lg="5" :xl="5" class="mb20">
							<el-form-item>
								<el-button type="primary" @click="getCheckItem">搜索</el-button>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<div>
					<div style="color: var(--el-color-primary); margin-bottom: 10px">检验项目</div>
					<el-table :data="checkItemData" style="width: 100%" v-loading="loading" tooltip-effect="light" row-key="id" border="">
						<el-table-column type="selection" width="55" />
						<el-table-column type="index" label="序号" width="55" align="center" />
						<el-table-column prop="itemCode" label="检验项编码" show-overflow-tooltip="" />
						<el-table-column prop="itemName" label="检验项名称" show-overflow-tooltip="">
							<template #default="scope">
								{{ scope.row.qiItemInfo?.itemName || '' }}
							</template>
						</el-table-column>
						<el-table-column prop="calendarCode" label="单位" show-overflow-tooltip="" />
						<el-table-column prop="itemProps" label="维护项属性" show-overflow-tooltip="">
							<template #default="scope">
								{{ scope.row.itemProps == '2' ? '定性' : '定量' }}
							</template>
						</el-table-column>
						<el-table-column prop="standVal" label="标准值" show-overflow-tooltip="" />
						<el-table-column prop="maxVal" label="上限" show-overflow-tooltip="" />
						<el-table-column prop="minVal" label="下限" show-overflow-tooltip="" />
						<el-table-column prop="sorts" label="显示顺序" show-overflow-tooltip="" />
						<el-table-column prop="isMust" label="是否必填项" show-overflow-tooltip="">
							<template #default="scope">
								{{ scope.row.isMust == '1' ? '是' : '否' }}
							</template>
						</el-table-column>
						<el-table-column prop="resultVal" label="检验结果" show-overflow-tooltip="">
							<template #default="scope">
								<el-input v-model="scope.row.resultVal"></el-input>
							</template>
						</el-table-column>
						<el-table-column prop="inspResult" label="结论" show-overflow-tooltip="">
							<template #default="scope">
								<!-- <el-input v-model="scope.row.inspResult"></el-input> -->
								<el-select v-model="scope.row.inspResult">
									<el-option :value="true" label="合格"></el-option>
									<el-option :value="false" label="不合格"></el-option>
								</el-select>
							</template>
						</el-table-column>
					</el-table>
					<!-- <el-pagination v-model:currentPage="tableParams.page" v-model:page-size="tableParams.pageSize" :total="tableParams.total" :page-sizes="[10, 20, 50, 100, 200, 500]" small="" background="" @size-change="handleSizeChange" @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper" /> -->
				</div>
				<!--        <div style="width:100%;display:flex;flex-direction: column;align-items: center;">-->
				<!--          <div style="margin-top:10px;display:flex;justify-content:space-between;width:5%;">-->
				<!--            <el-button type="primary" @click="submit">提 交</el-button>-->
				<!--            <el-button type="primary" @click="reset">重 置</el-button>-->
				<!--          </div>-->
				<!--        </div>-->
			</div>
			<div v-if="step == 1">
				<el-table :data="tableData" :ref="(e) => (workRecordTabRef = e)" style="width: 100%" v-loading="loading" tooltip-effect="light" row-key="id" border="" @selection-change="onSelectionChange">
					<el-table-column type="selection" width="55" />
					<el-table-column type="index" label="序号" width="55" align="center" />
					<el-table-column prop="produceWorkOrderNo" label="工单号" show-overflow-tooltip="" />
					<el-table-column prop="productCode" label="产品编码" show-overflow-tooltip="" />
					<el-table-column prop="productName" label="产品名称" show-overflow-tooltip="" />
					<el-table-column prop="startWorkDate" label="开工时间" show-overflow-tooltip="" />
					<el-table-column prop="endWorkDate" label="完工时间" show-overflow-tooltip="" />
					<el-table-column prop="num" label="批次数" show-overflow-tooltip="" />
					<el-table-column prop="processCode" label="工序编码" show-overflow-tooltip="" />
					<el-table-column prop="processName" label="工序名称" show-overflow-tooltip="" />
					<el-table-column prop="packCode" label="载具编码" show-overflow-tooltip="" />
					<el-table-column prop="packName" label="载具名称" show-overflow-tooltip="" />
					<el-table-column prop="equipmentCode" label="设备编码" show-overflow-tooltip="" />
					<el-table-column prop="equipmentName" label="设备名称" show-overflow-tooltip="" />
					<el-table-column prop="workShopCode" label="车间编码" show-overflow-tooltip="" />
					<el-table-column prop="workShopName" label="车间名称" show-overflow-tooltip="" />
					<el-table-column prop="factoryCode" label="工厂编码" show-overflow-tooltip="" />
					<el-table-column prop="factoryName" label="工厂名称" show-overflow-tooltip="" />
				</el-table>
			</div>
			<template #footer>
				<el-button @click="closeDialog">关 闭</el-button>
				<el-button v-if="step == 1" type="primary" @click="chooseFinish">选择完毕</el-button>
				<el-button v-if="step == 2" type="primary" @click="submit">提 交</el-button>
			</template>
		</el-dialog>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>
<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormRules } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
import { getDictDataList as dl } from '/@/utils/dict-utils';
import { getFinishList, getInspItem, saveSalfInsp } from '/@/api/mes/mesControlBoard';
//父级传递来的参数
var props = defineProps({
	title: {
		type: String,
		default: '',
	},
	produceWorkOrderNo: {
		type: String,
		default: '',
	},
	processCode: {
		type: String,
		default: '',
	},
	factoryCode: {
		type: String,
		default: '',
	},
	productCode: {
		type: String,
		default: '',
	},
	equipmentCode: {
		type: String,
		default: '',
	},
});

const checkItemData = ref([]);
const getCheckItem = async () => {
	let res = await getInspItem({
		processCode: inspSearchState.value.processCode,
		productCode: inspSearchState.value.productCode,
		inspType: 5,
	});
	checkItemData.value = (res.data?.result || []).map((item) => ({
		...item,
		itemName: item.qiItemInfo?.qiItemName,
		itemCode: item.qiItemInfo?.itemCode,
		itemProps: item.qiItemInfo?.itemProps,
		inspType: item.qiItemInfo?.inspType,
	}));
};

// 选择行变更
const step = ref(1);
const tableRef = ref();
const selectionList = ref([]);
const onSelectionChange = (e) => {
	console.log(e);
	if (e) {
		inspSearchState.value.processCode = e[0].processCode;
		inspSearchState.value.productCode = e[0].productCode;
    inspSearchState.value.workRecordId = e[0].id;
	}
	step.value = 2;

	getCheckItem();
	// selectionList.value = tableRef.value.getSelectionRows();
};
const getWorkRecord = async () => {
	let res = await getFinishList({
		page: 1,
		pageSize: 9999,
		factoryCode: props.factoryCode,
		equipmentCode: props.equipmentCode,
		processCode: props.processCode,
	});
	tableData.value = res.data?.result?.items || [];
};

const workRecordTabRef = ref();
const inspSearchState = ref({
	processCode: '',
	productCode: '',
  workRecordId:0,
});
const chooseFinish = () => {
	// var rows = workRecordTabRef.value.getSelectionRows();
	// inspSearchState.value.processCode =
	step.value = 2;

	getCheckItem();
};

//自行添加其他规则
const rules = ref<FormRules>({
	// processCode: [{ required: true, message: '请补充工序信息！', trigger: 'blur' }],
	// productCode: [{ required: true, message: '请补充产品信息！', trigger: 'blur' }],
	inspType: [{ required: true, message: '请选择检验类型！', trigger: 'blur' }],
});

//父级传递来的函数，用于回调
const emit = defineEmits(['reloadTable']);
const ruleFormRef = ref();
const tableData = ref<any>([]);
const loading = ref(false);
const tableParams = ref({
	page: 1,
	pageSize: 10,
	total: 0,
});
const handleSizeChange = (val: number) => {
	tableParams.value.pageSize = val;
	handleQuery();
};
// 改变页码序号
const handleCurrentChange = (val: number) => {
	tableParams.value.page = val;
	handleQuery();
};
const handleQuery = () => {};

const ruleForm = ref<any>({});
const state = reactive({
	isShowDialog: false,
});

const ruleForm1 = ref<any>({});

// 页面加载时
onMounted(() => {});

// 打开弹窗
const openDialog = async (row: any) => {
	// 改用detail获取最新数据来编辑
	step.value = 1;
	let rowData = JSON.parse(JSON.stringify(row));
	state.isShowDialog = true;
	// 获取报工记录
	tableData.value = [];
	getWorkRecord();
	// getCheckItem();
};

// 关闭弹窗
const closeDialog = () => {
	emit('reloadTable');
	step.value = 2;
	state.isShowDialog = false;
};

// 取消
const cancel = () => {
	state.isShowDialog = false;
};

// 签到
const submit = async () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			if (checkItemData.value.length == 0) return ElMessage.warning('缺失检验项信息');
			if (checkItemData.value.some((item) => !item.inspResult && item.isMust == 1)) return ElMessage.warning('请补充检验结果');
			await saveSalfInsp({
				items: checkItemData.value.map((item: any) => ({
					id: item.id,
					inspResult: item.inspResult,
					resultVal: item.resultVal,
				})),
				workRecordId:inspSearchState.value.workRecordId,
				inspType: 5,
			});
			ElMessage.success('提交成功');
			closeDialog();
		}
	});
};

//将属性或者函数暴露给父组件
defineExpose({ openDialog });
</script>
