<template>
	<div class="quality-template-container layout-pd">
		<el-card shadow="never">
			<el-form :model="state.queryParams" ref="ruleFormRef" :inline="true" @submit.native.prevent>
				<el-form-item label="模版名称" prop="Name">
					<el-input v-model="state.queryParams.Name" placeholder="请输入模版名称" clearable @keyup.enter="queryList" style="width: 250px" />
				</el-form-item>
				<el-form-item label="质检分类" prop="Grouping">
					<el-select v-model="state.queryParams.Grouping" placeholder="请选择质检分类">
						<el-option v-for="item in templateGrouping" :value="item.key" :key="item.key" :label="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="queryList" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
					<el-button @click="resetQuery(ruleFormRef)" v-waves class="default-button"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
				</el-form-item>
			</el-form>
		</el-card>
		<el-card shadow="never">
			<div class="mb20">
				<el-button type="primary" @click="onTemplateAdd" v-waves v-auth="'quality:template:add'">
					<SvgIcon name="ele-Plus" class="mr5" />新增
				</el-button>
				<el-button type="primary" @click="onTemplateDelete" v-waves v-auth="'quality:template:delete'" :disabled="!multipleSelection.length">
					<SvgIcon name="ele-Delete" class="mr5" />删除
				</el-button>
			</div>
			<!-- 表格 -->
			<el-table :data="state.tableData" v-loading="state.loading" row-key="id" ref="multipleTableRef" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" />
				<el-table-column prop="name" label="模版名称" show-overflow-tooltip width="130"></el-table-column>
				<el-table-column prop="groupingText" label="质检分类" show-overflow-tooltip></el-table-column>
        <el-table-column label="是否启用" show-overflow-tooltip>
          <template #default="{ row }">
            <el-switch
                v-model="row.isEnable"
                :active-value="1"
                :inactive-value="0"
                inline-prompt
                active-text="启用"
                inactive-text="禁用"
                @change="changeIsEnable(row)"
                v-if="auth('quality:template:edit')"
            />
            <span v-else>{{ row.isEnable === 1 ? '启用' : '禁用' }}</span>
          </template>
        </el-table-column>
				<el-table-column prop="creatorName" label="创建人" show-overflow-tooltip></el-table-column>
				<el-table-column prop="creationTime" label="创建时间" show-overflow-tooltip width="170">
					<template #default="{ row }">
						<span>{{ formatDate(row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="lastModificationName" label="更新人" show-overflow-tooltip></el-table-column>
				<el-table-column prop="lastModificationTime" label="更新时间" show-overflow-tooltip width="170">
					<template #default="{ row }">
						<span>{{ formatDate(row.lastModificationTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="120" fixed="right" align="center">
					<template #default="{ row }">
						<el-button link type="primary" @click="onTemplateEdit(row)" v-auth="'quality:template:edit'" title="编辑模板"> 编辑 </el-button>
					</template>
				</el-table-column>
				<template #empty>
					<Empty />
				</template>
			</el-table>
			<!-- 分页 -->
			<pagination
				:total="state.total"
				v-model:page="state.queryParams.PageIndex"
				v-model:limit="state.queryParams.PageSize"
				@pagination="queryList"
			/>
		</el-card>
		<!--  模板新增  -->
		<quality-template-add ref="templateAdd" @updateList="queryList"  :templateGrouping="templateGrouping"/>
		<!--  模板编辑  -->
		<quality-template-edit ref="templateEditRef" @updateList="queryList" :templateGrouping="templateGrouping" />
	</div>
</template>

<script lang="ts" setup name="qualityTemplate">
import { reactive, ref, onMounted, defineAsyncComponent } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
import { auth } from '/@/utils/authFunction';
import {templateBaseData,templateList,templateDelete,templateUpdate} from "/@/api/quality/template"

// 引入组件
const QualityTemplateAdd = defineAsyncComponent(() => import('/@/views/quality/template/components/Template-add.vue')); // 模板新增
const QualityTemplateEdit = defineAsyncComponent(() => import('/@/views/quality/template/components/Template-edit.vue')); // 模板编辑

// 定义变量内容
const state = reactive<any>({
	loading: false, // 加载状态
	queryParams: {
		// 查询参数
		PageIndex: 1,
		PageSize: 10,
    Grouping: null,
		Name: '',
	},
	total: 0, // 总条数
	tableData: [], // 表格数据
});
const ruleFormRef = ref<RefType>(null); // 表单ref
const templateGrouping = ref<EmptyArrayType>([]); // 质检分组
const getBaseData = async () => {
	try {
		const res = await templateBaseData();
    templateGrouping.value = res.result?.templateGrouping ?? [];
	} catch (error) {
		console.log(error);
	}
};
// 获取参数列表
const queryList = () => {
	state.loading = true;
	if (!auth('quality:template:query')) ElMessage.error('抱歉，您没有权限获取质检模板列表！');
	else {
    templateList(state.queryParams)
			.then((res) => {
				state.loading = false;
				state.tableData = res.result.items ?? [];
				state.total = res.result.total ?? 0;
			})
			.finally(() => {
				state.loading = false;
			});
	}
};
// 重置表单
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
};
// 新增意见
const templateAdd = ref<RefType>(); // 意见新增
const onTemplateAdd = () => {
	templateAdd.value.openDialog();
};
// 修改意见
const templateEditRef = ref<RefType>(); // 修改意见
const onTemplateEdit = (row: any) => {
	templateEditRef.value.openDialog(row);
};
// 表格多选
const multipleTableRef = ref<RefType>();
const multipleSelection = ref<any>([]);
const handleSelectionChange = (val: any[]) => {
	multipleSelection.value = val;
};
//  修改是否启用
const changeIsEnable = (row: any) => {
  ElMessageBox.confirm(`您确定要${row.isEnable ? '启用' : '禁用'}：【${row.name}】模板，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
    cancelButtonClass: 'default-button',
    autofocus: false,
  })
      .then(() => {
        const request = {
          ...row,
          isEnable: row.isEnable,
        };
        templateUpdate(request)
            .then(() => {
              ElMessage.success('操作成功');
              queryList();
            })
            .catch(() => {
              queryList();
            });
      })
      .catch(() => {
        queryList();
      });
};
// 删除参数
const onTemplateDelete = () => {
	const names = multipleSelection.value.map((item: any) => item.name).join('、');
	const ids = multipleSelection.value.map((item: any) => item.id);
	ElMessageBox.confirm(`您确定要删除：【${names}】模板，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
      templateDelete({ ids }).then(() => {
				ElMessage.success('操作成功');
				queryList();
			});
		})
		.catch(() => {});
};
// 页面加载时
onMounted(() => {
	getBaseData();
	queryList();
});
</script>

<style lang="scss" scoped>
.quality-template-container {
}
</style>
