<template>
	<div class="quality-project-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-form :model="state.queryParams" ref="ruleFormRef" inline @submit.native.prevent :disabled="state.loading">
				<el-form-item label="质检项名称" prop="Name">
					<el-input v-model="state.queryParams.Name" placeholder="请填写质检项目名称" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<el-form-item label="质检项分组" prop="GroupingName">
					<el-select v-model="state.queryParams.GroupingName" placeholder="请选择质检项目分组" @change="handleQuery">
						<el-option v-for="item in qualityItemGrouping" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
					</el-select>
				</el-form-item>
				<el-form-item label="分值" prop="value">
					<input-number-range v-model="state.queryParams.value" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
					<el-button @click="drawer = true" class="default-button"> <SvgIcon name="ele-Search" class="mr5" />更多查询</el-button>
				</el-form-item>
			</el-form>
			<vxe-toolbar
				ref="toolbarRef"
				:loading="state.loading"
				custom
				:refresh="{
					queryMethod: handleQuery,
				}"
			>
				<template #buttons>
					<el-button type="primary" @click="onProjectAdd" v-auth="'quality:project:add'">
						<SvgIcon name="ele-Plus" class="mr5" />新增质检项
					</el-button>
					<el-button type="danger" @click="onProjectDelete" v-auth="'quality:project:delete'" :disabled="isChecked">
						<SvgIcon name="ele-Delete" class="mr5" />删除
					</el-button>
				</template>
			</vxe-toolbar>
			<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
				<vxe-table
					border
					:loading="state.loading"
					:data="state.tableData"
					:column-config="{ resizable: true }"
					:row-config="{ isCurrent: true, isHover: true, height: 30, useKey: true }"
					ref="tableRef"
					height="auto"
					auto-resize
					show-overflow
					:scrollY="{ enabled: true, gt: 100 }"
					id="qualityProject"
					:custom-config="{ storage: true }"
					showHeaderOverflow
					@checkbox-all="selectAllChangeEvent"
					@checkbox-change="selectChangeEvent"
				>
					<vxe-column type="checkbox" width="50" align="center"></vxe-column>
					<vxe-column field="name" title="质检项名称" min-width="150"></vxe-column>
					<vxe-column field="describe" title="质检项描述" width="200"></vxe-column>
					<vxe-column field="groupingName" title="质检项分组" width="150"></vxe-column>
					<vxe-column field="type" title="是否智能质检" width="120" v-if="['YiBin'].includes(themeConfig.appScope)">
						<template #default="{ row }">
							{{ row.isIntelligent === 1 ? '是' : '否' }}
						</template>
					</vxe-column>
					<vxe-column field="grade" title="分值（分）" width="100"></vxe-column>
					<vxe-column field="isEnable" title="是否启用" width="100">
						<template #default="{ row }">
							<template v-if="auth('quality:project:edit')">
								<el-switch
									v-model="row.isEnable"
									active-text="启用"
									inactive-text="禁用"
									:active-value="1"
									:inactive-value="0"
									@change="changeIsEnable(row)"
									inline-prompt
									size="small"
								/>
							</template>
							<span v-else>{{ row.isEnable ? '已启用' : '已禁用' }}</span>
						</template>
					</vxe-column>
					<vxe-column field="creatorName" title="创建人" width="120"></vxe-column>
					<vxe-column field="creationTime" title="创建时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="lastModificationName" title="更新人" width="120"></vxe-column>
					<vxe-column field="lastModificationTime" title="更新时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.lastModificationTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column title="操作" fixed="right" width="90" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="onProjectEdit(row)" v-auth="'quality:project:edit'" title="编辑质检项目"> 编辑 </el-button>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
			<pagination
				@pagination="queryList"
				:total="state.total"
				v-model:current-page="state.queryParams.PageIndex"
				v-model:page-size="state.queryParams.PageSize"
				:disabled="state.loading"
			/>
		</div>
		<!--  质检项目新增  -->
		<project-add ref="projectAddRef" @updateList="queryList" :qualityItemGrouping="qualityItemGrouping" />
		<!--  质检项目编辑  -->
		<project-edit ref="projectEditRef" @updateList="queryList" :qualityItemGrouping="qualityItemGrouping" />
		<!--	更多查询	-->
		<el-drawer v-model="drawer" title="更多查询" size="500px">
			<el-form :model="state.queryParams" ref="drawerRuleFormRef" @submit.native.prevent label-width="100px" :disabled="state.loading">
				<el-form-item label="质检描述" prop="Describe">
					<el-input v-model.trim="state.queryParams.Describe" placeholder="质检描述" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="创建时间" prop="crTime">
					<el-date-picker
						v-model="state.queryParams.crTime"
						type="datetimerange"
						unlink-panels
						range-separator="至"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
						:shortcuts="shortcuts"
						@change="handleQuery"
						value-format="YYYY-MM-DD[T]HH:mm:ss"
						:default-time="defaultTimeStartEnd"
					/>
				</el-form-item>
				<el-form-item label="是否启用" prop="IsEnable">
					<el-select v-model="state.queryParams.IsEnable" placeholder="请选择是否启用" @change="handleQuery" clearable>
						<el-option label="启用" :value="1" />
						<el-option label="禁用" :value="0" />
					</el-select>
				</el-form-item>
				<el-form-item label="创建人" prop="CreatorName">
					<el-input v-model.trim="state.queryParams.CreatorName" placeholder="创建人" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="更新人" prop="LastModificationName">
					<el-input v-model.trim="state.queryParams.LastModificationName" placeholder="更新人" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="更新时间" prop="gxTime">
					<el-date-picker
						v-model="state.queryParams.gxTime"
						type="datetimerange"
						unlink-panels
						range-separator="至"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
						:shortcuts="shortcuts"
						@change="handleQuery"
						value-format="YYYY-MM-DD[T]HH:mm:ss"
						:default-time="defaultTimeStartEnd"
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
				<el-button @click="resetQuery(drawerRuleFormRef)" class="default-button"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
			</template>
		</el-drawer>
	</div>
</template>

<script lang="tsx" setup name="qualityProject">
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { auth } from '@/utils/authFunction';
import { projectBaseData, projectDelete, projectList, projectUpdate } from '@/api/quality/project';
import { useThemeConfig } from '@/stores/themeConfig';
import { storeToRefs } from 'pinia';
import Other from '@/utils/other';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';

// 引入组件
const ProjectAdd = defineAsyncComponent(() => import('@/views/quality/project/components/Project-add.vue')); // 质检项目新增
const ProjectEdit = defineAsyncComponent(() => import('@/views/quality/project/components/Project-edit.vue')); // 质检项目编辑
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页
const InputNumberRange = defineAsyncComponent(() => import('@/components/NumberRange/index.vue')); // 数字区间

// 定义变量内容
const state = reactive<any>({
	loading: false, // 加载状态
	queryParams: {
		// 查询参数
		PageIndex: 1,
		PageSize: 20,
		GroupingName: null,
		Type: null,
		Name: null,
		value: [0, 100], // 质检分值
		Describe: null, // 质检描述
		IsEnable:null, // 是否启用
		CreatorName:null, // 创建人
		crTime: [], // 创建时间
		CreationTimeStart: null, // 创建时间开始
		CreationTimeEnd: null, // 创建时间结束
		gxTime: [], // 更新时间
		LastModificationTimeStart: null, // 更新时间开始
		LastModificationTimeEnd: null, // 更新时间结束
	},
	total: 0, // 总条数
	tableData: [], // 表格数据
});
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const qualityItemGrouping = ref<EmptyArrayType>([]); // 质检项目分组
const getBaseData = async () => {
	try {
		const res = await projectBaseData();
		qualityItemGrouping.value = res.result?.qualityItemGrouping ?? [];
	} catch (error) {
		console.log(error);
	}
};
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
// 获取参数列表
const requestParams = ref<EmptyObjectType>({});
const queryList = () => {
	state.loading = true;
	requestParams.value = Other.deepClone(state.queryParams);
	requestParams.value.MinGrade = state.queryParams.value === null ? null : state.queryParams.value[0]; // 分值
	requestParams.value.MaxGrade = state.queryParams.value === null ? null : state.queryParams.value[1];
	Reflect.deleteProperty(requestParams.value, 'value'); // 删除无用的参数
	requestParams.value.CreationTimeStart = state.queryParams.crTime === null ? null : state.queryParams.crTime[0]; // 创建时间
	requestParams.value.CreationTimeEnd = state.queryParams.crTime === null ? null : state.queryParams.crTime[1];
	Reflect.deleteProperty(requestParams.value, 'crTime'); // 删除无用的参数
	requestParams.value.LastModificationTimeStart = state.queryParams.gxTime === null ? null : state.queryParams.gxTime[0]; // 更新时间
	requestParams.value.LastModificationTimeEnd = state.queryParams.gxTime === null ? null : state.queryParams.gxTime[1];
	Reflect.deleteProperty(requestParams.value, 'gxTime'); // 删除无用的参数
	projectList(requestParams.value)
		.then((res) => {
			state.loading = false;
			state.tableData = res.result.items ?? [];
			state.total = res.result.total ?? 0;
			tableRef.value.clearCheckboxRow();
			checkTable.value = [];
		})
		.finally(() => {
			state.loading = false;
			tableRef.value.clearCheckboxRow();
			checkTable.value = [];
		});
};
// 重置表单
const drawerRuleFormRef = ref();
const ruleFormRef = ref<RefType>(); // 表单ref
const drawer = ref(false);
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	ruleFormRef.value?.resetFields();
	queryList();
};
// 新增质检项目
const projectAddRef = ref<RefType>();
const onProjectAdd = () => {
	projectAddRef.value.openDialog();
};
// 编辑质检项目
const projectEditRef = ref<RefType>();
const onProjectEdit = (row: any) => {
	projectEditRef.value.openDialog(row);
};
// 删除质检项目
const onProjectDelete = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	ElMessageBox.confirm(`您确定要删除选中的质检项目，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			projectDelete({ ids }).then(() => {
				ElMessage.success('操作成功');
				queryList();
			});
		})
		.catch(() => {});
};
//  修改是否启用
const changeIsEnable = (row: any) => {
	row.isEnable = row.isEnable === 1 ? 0 : 1; //保持switch点击前的状态
	ElMessageBox.confirm(`您确定要${row.isEnable === 1 ? '禁用' : '启用'}：【${row.name}】质检项，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			const isEnable = row.isEnable === 1 ? 0 : 1;
			const request = {
				...row,
				isEnable: isEnable,
			};
			projectUpdate(request)
				.then(() => {
					ElMessage.success('删除成功');
					queryList();
				})
				.catch(() => {
					queryList();
				});
		})
		.catch(() => {
			queryList();
		});
};
const tableRef = ref<RefType>();
const checkTable = ref<EmptyArrayType>([]);
const selectAllChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '所有勾选事件' : '所有取消事件', records);
	}
};

const selectChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '勾选事件' : '取消事件', records);
	}
};
const isChecked = computed(() => {
	return !checkTable.value.length;
});
const toolbarRef = ref<RefType>();
// 页面加载时
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
	getBaseData();
});
</script>
