﻿<template>
	<div class="mesQiDefect-container">
		<el-dialog v-model="state.isShowDialog" v-if="state.isShowDialog" :width="800" draggable="" :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<!--<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit /> </el-icon>-->
					<span>{{ props.title }}</span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
						<el-input v-model="state.ruleForm.id" />
					</el-form-item>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="缺陷编码" prop="defectCode">
							<el-input v-model="state.ruleForm.defectCode" placeholder="请输入缺陷编码" maxlength="100" show-word-limit clearable />

						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="缺陷名称" prop="defectName">
							<el-input v-model="state.ruleForm.defectName" placeholder="请输入缺陷名称" maxlength="100" show-word-limit clearable />

						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="缺陷等级" prop="lv">
							<el-select clearable v-model="state.ruleForm.lv" placeholder="请选择缺陷等级">
								<el-option v-for="(item,index) in dl('defectLevel')"  :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="12" :xl="12" class="mb20">
						<el-form-item label="排序" prop="sorts">
							<el-input-number v-model="state.ruleForm.sorts" placeholder="请输入排序" clearable />

						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="备注" prop="remark">
							<el-input v-model="state.ruleForm.remark" placeholder="请输入备注" maxlength="500" show-word-limit clearable />

						</el-form-item>

					</el-col>
				</el-row>
			</el-form>
      <el-tabs  :model-value="'checkItem'">
        <el-tab-pane label="关联检验项目"  name="checkItem"></el-tab-pane>
      </el-tabs>
      <el-button icon="el-icon-plus" type="primary" @click="subAdd" class="subaddBtn">新增</el-button>
      <el-table :data="checkItemTableData" style="width: 100%" tooltip-effect="light" row-key="id" border="" >
        <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="" />
        <el-table-column label="操作" width="140" align="center" fixed="right">
          <template #default="scope">
            <el-button icon="ele-Delete" size="small" type="primary" @click="subDelete(scope.row, scope.$index)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
    <choose-qi-item title="选择检验项" ref="chooseCheckItemRef" :is-any="true" @finish="onChooseFinish"></choose-qi-item>
	</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 { addMesQiDefect, updateMesQiDefect, detailMesQiDefect } from "/@/api/mes/mesQiDefect";
	import { pageMesQiDefect, deleteMesQiDefect } from '/@/api/mes/mesQiDefect';

	import { getDictDataItem as di, getDictDataList as dl } from '/@/utils/dict-utils';
  	import { formatDate } from '/@/utils/formatTime';
    import ChooseQiItem from "/@/businessComponents/chooseQiItem.vue";
    import ChooseUser from "/@/businessComponents/chooseUser.vue";

	//父级传递来的参数
	var props = defineProps({
		title: {
		type: String,
		default: "",
	},
	});
	//父级传递来的函数，用于回调
	const emit = defineEmits(["reloadTable"]);
	const ruleFormRef = ref();
    const state = reactive({
    isShowDialog: false,
    ruleForm: {} as any,
});

	//自行添加其他规则
	const rules = ref<FormRules>({
		defectCode: [{required: true, message: '请输入缺陷编码！', trigger: 'blur',},],
		defectName: [{required: true, message: '请输入缺陷名称！', trigger: 'blur',},],
	});

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

	});

  const checkItemTableData = ref([]);
  const chooseCheckItemRef = ref();
  const subAdd = ()=>{
    chooseCheckItemRef.value.openDialog({});
  }
  const subDelete = (row: any, index: number) => {
    checkItemTableData.value.splice(index, 1);
  };

  const onChooseFinish = (data: any) => {
    console.log(data);
    let list: any[] = (data?.rows || []).map((item: any) => ({
      ...item,
      itemName: item.itemName,
      itemCode: item.itemCode,
    }));
    checkItemTableData.value.push(...list);
  }

	// 打开弹窗
	const openDialog = async (row: any) => {
		// state.ruleForm = JSON.parse(JSON.stringify(row));
		// 改用detail获取最新数据来编辑
    let data =JSON.parse(JSON.stringify(row));
    let rowData = data;
    checkItemTableData.value = [];
		if (rowData.id){
      state.ruleForm = (await detailMesQiDefect(rowData.id)).data.result;
      checkItemTableData.value = (data.qiItemCodes || '')
          .split(',')
          .filter((item) => item)
          .map((item, index) => {
            return {
              itemCode: item || '',
              itemName: (data.qiItemNames || '').split(',').filter((item) => item)?.[index] || '',
            };
          });
    } else{
      state.ruleForm = rowData;
    }
		state.isShowDialog = true;
	};

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

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

	// 提交
	const submit = async () => {
		ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
			if (isValid) {
				let values = state.ruleForm;
        // 人员绑定
        values.qiItemCodes = checkItemTableData.value.map((item: any) => item.itemCode).join(',');
        values.qiItemName = checkItemTableData.value.map((item: any) => item.itemName).join(',');
				if (state.ruleForm.id == undefined || state.ruleForm.id == null || state.ruleForm.id == "" || state.ruleForm.id == 0) {
					await addMesQiDefect(values);
				} else {
					await updateMesQiDefect(values);
				}
				closeDialog();
			} else {
				ElMessage({
					message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
					type: "error",
				});
			}
		});
	};






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




