<template>
	<div class="table-box">
		<ProTable
			ref="proTable"
			title="参建单位列表"
			:columns="columns"
			:requestApi="getTableList"
			:dataCallback="dataCallback"
			:tool-button="false"
			:pagination="true"
			background
			:isShowSearch="false"
			:initParam="initParam"
			:onReset="true"
		>
			<template #formButton="scope">
				<el-button class="addButtonStyle" @click="handleAddItem(1)">新增</el-button>
			</template>
			<template #operation="{ row }">
				<el-button type="primary" link @click="handleAddItem(2, row)">
					<img src="@/assets/images/tableIcon/look.png" alt="" class="configureIcon" />
					<span>查看</span>
				</el-button>
			</template>
			<template #state="{ row }">
				<span :class="row.state === 1 ? '' : 'redText'">{{ row.state == 1 ? "启用" : "禁用" }}</span>
			</template>
		</ProTable>
		<el-drawer v-model="drawerVisible" :destroy-on-close="true" :before-close="closeDrawer" size="450px" title="配置权限">
			<span class="title sle">所拥有的权限</span>
			<el-scrollbar :style="{ height: title ? `calc(100% - 95px)` : `calc(100% - 56px)` }">
				<!-- check-strictly 父子不关联 这样数据选择父 子不会默认被勾选  子被选择 父也不会 -->
				<el-tree ref="treeRef" default-expand-all :data="datas" show-checkbox node-key="name" :props="defaultProps"> </el-tree>
			</el-scrollbar>
			<template #footer>
				<div class="flx-center">
					<el-button style="margin-right: 60px" @click="cacel">取消</el-button>
					<el-button type="primary" @click="confirm">保存并关闭</el-button>
				</div>
			</template>
		</el-drawer>
		<el-dialog :title="title" show-close v-model="newUnitDialog" style="min-width: 1200px">
			<el-form ref="formRef" :model="formData" label-width="180px" :rules="rules" class="basic-form" size="default">
				<!-- <el-form ref="formDataRef" :model="formData" label-width="150px" class="basic-form"> -->
				<el-row :gutter="120">
					<el-col :span="12">
						<el-form-item label="参建单位类型:" prop="type">
							<el-input v-model="formData.type" placeholder="请输入" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="单位名称:" prop="companyName">
							<el-input v-model="formData.companyName" placeholder="请输入" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="120">
					<el-col :span="12">
						<el-form-item label="统一社会信用代码:" prop="creditCode">
							<el-input v-model="formData.creditCode" placeholder="请输入" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="地址:" prop="address">
							<el-input v-model.number="formData.address" placeholder="请输入" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="120">
					<el-col :span="12">
						<el-form-item label="注册日期:" prop="registrationDate">
							<el-date-picker
								style="width: 100%"
								v-model="formData.registrationDate"
								format="YYYY-MM-DD"
								value-format="YYYY-MM-DD"
								type="datetime"
								placeholder="请选择时间"
							/>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="120">
					<el-col :span="12">
						<el-form-item label="联系人:" prop="leadName">
							<el-input v-model.number="formData.leadName" placeholder="请输入" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="联系电话:" prop="leadTel">
							<el-input v-model.number="formData.leadTel" placeholder="请输入" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="120">
					<el-col :span="12">
						<el-form-item label="劳资专管员姓名:" prop="salaryManager">
							<el-input v-model.number="formData.salaryManager" placeholder="请输入" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="劳资专管员身份证号码:" prop="salaryManagerCard">
							<el-input v-model.number="formData.salaryManagerCard" placeholder="请输入" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="120">
					<el-col :span="12">
						<el-form-item label="劳资专管员电话:" prop="salaryManagerTel">
							<el-input v-model.number="formData.salaryManagerTel" placeholder="请输入" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="法人姓名:" prop="legalPerson">
							<el-input v-model.number="formData.legalPerson" placeholder="请输入" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="120">
					<el-col :span="12">
						<el-form-item label="法人身份证号码:" prop="legalPersonCard">
							<el-input v-model.number="formData.legalPersonCard" placeholder="请输入" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="法人电话:" prop="legalPersonTel">
							<el-input v-model.number="formData.legalPersonTel" placeholder="请输入" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="120">
					<el-col :span="12">
						<el-form-item label="注册资本:" prop="registeredCapital">
							<el-input v-model="formData.registeredCapital" placeholder="请输入">
								<template #append>
									<span>万元</span>
								</template>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="邮箱:" prop="email">
							<el-input v-model="formData.email" placeholder="请输入" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="120">
					<el-col :span="12">
						<el-form-item label="进场时间:" prop="entryTime">
							<el-date-picker
								style="width: 100%"
								v-model="formData.entryTime"
								format="YYYY-MM-DD"
								value-format="YYYY-MM-DD"
								type="datetime"
								placeholder="请选择时间"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="营业执照有效期:" prop="businessLicenseLifespan">
							<div class="date-select">
								<el-date-picker
									style="width: 62%; margin-right: 8px"
									v-model="formData.businessLicenseLifespan"
									format="YYYY-MM-DD"
									value-format="YYYY-MM-DD"
									type="datetime"
									placeholder="请选择时间"
									v-if="changeType == 1"
								/>
								<div v-else>长期</div>
								<el-radio-group v-model="changeType">
									<el-radio-button label="1">日期</el-radio-button>
									<el-radio-button label="2">长期</el-radio-button>
								</el-radio-group>
							</div>
						</el-form-item>
					</el-col>
				</el-row>
				<footer class="footer flx-center" v-if="title == '新增参建单位'">
					<el-button class="cancelButtonStyle" @click="newUnitDialog = false">取消</el-button>
					<el-button type="primary" @click="submitForm(formData)">保存</el-button>
				</footer>
			</el-form>
		</el-dialog>
		<engineeringDrawer v-model="engVisable" ref="engDrawer" :request="getengineering">
			<template #default="{ data }">
				<span style="margin-left: 10px" @click="onUpdate(data)">{{ data.engineeringName }}</span>
			</template>
		</engineeringDrawer>
		<allEngineering @click="engVisable = true" />
	</div>
</template>

<script setup lang="tsx" name="ProjectSupervisionRecord">
import { ref, reactive, nextTick } from "vue";
import { ElMessage, ElMessageBox, ElTree, FormInstance } from "element-plus";
import { useRouter } from "vue-router";
import { ColumnProps } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import { jxj_User } from "@/api/types";
import { getRelevanceList } from "@/api/modules/common";
import TreeFilter from "@/components/TreeFilter/index.vue";
import engineeringDrawer from "@/components/engineeringDrawer/index.vue";
import allEngineering from "@/components/allEngineering/index.vue";
import { deleteRole, editRolePermissions, getSystemRole, getTreemRoleList, getTreeByIdList } from "@/api/modules/goverment";
import { addBuildUnit, getBuildUnitList } from "@/api/modules/project";

import { GlobalStore } from "@/stores";

const treeRef = ref(null);
const engVisable = ref(false);
const changeType = ref(1);
const datas = reactive([]);
const formRef = ref<FormInstance>();

const defaultProps = {
	children: "children",
	label: (data: any, node: { data: { meta: { title: any } } }) => node.data.meta.title
};
const router = useRouter();
const store = GlobalStore();
const drawerVisible = ref(false);
const title = ref("");
const newUnitDialog = ref(false);
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	solveFlag: 1,
	engineeringSn: ""
});
const formData = ref({
	type: "",
	companyName: "",
	creditCode: "",
	address: "",
	registrationDate: "",
	leadName: "",
	leadTel: "",
	salaryManager: "",
	salaryManagerCard: "",
	salaryManagerTel: "",
	legalPerson: "",
	legalPersonCard: "",
	legalPersonTel: "",
	registeredCapital: "",
	email: "",
	entryTime: "",
	businessLicenseLifespan: ""
});
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();

const getId = ref<number | undefined>(undefined);

// 表格配置项
const columns: ColumnProps[] = [
	{ type: "index", label: "序号", width: 80 },
	{
		prop: "companyName",
		label: "单位名称",
		search: { el: "input" }
	},
	// 多级 prop
	{ prop: "type", label: "参建单位类型", search: { el: "input" } },
	{ prop: "address", label: "所属区域" },
	{ prop: "address", label: "地址" },
	{ prop: "leadName", label: "联系人" },
	{ prop: "leadTel", label: "联系电话" },
	{ prop: "operation", label: "操作", fixed: "right", width: 260 }
];

const rules = ref({
	type: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		}
	],
	companyName: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		}
	],
	creditCode: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		}
	],
	address: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		}
	],
	registrationDate: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		}
	],
	leadTel: [
		{
			pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
			message: "请输入合法手机号",
			trigger: "change"
		}
	],
	salaryManagerTel: [
		{
			pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
			message: "请输入合法手机号",
			trigger: "change"
		}
	],
	legalPersonTel: [
		{
			pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
			message: "请输入合法手机号",
			trigger: "change"
		}
	],
	email: [
		{
			type: "email",
			message: "请输入正确的电子邮箱",
			trigger: "change"
		}
	],
	salaryManagerCard: [
		{
			pattern: /^[1-9]\d{5}(19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i,
			message: "请输入正确的身份证号码",
			trigger: "change"
		}
	],
	legalPersonCard: [
		{
			pattern: /^[1-9]\d{5}(19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i,
			message: "请输入正确的身份证号码",
			trigger: "change"
		}
	]
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
	// console.log(data);
	return {
		list: data.records,
		total: Number(data.total),
		pageNo: Number(data.current),
		pageSize: Number(data.size)
	};
};

const closeDrawer = (done: () => void) => {
	datas.length = 0;
	done();
};

const cacel = () => {
	drawerVisible.value = false;
	datas.length = 0;
};

const transfrom = (arr: Array<any>) => {
	const result: any[] | ConcatArray<{ authorityId: any; roleId: number | undefined; type: any }> = [];
	return arr
		.map(item => {
			if (arr.children && Array.isArray(arr.children)) {
				result.concat(transfrom(arr.children));
			}

			return {
				authorityId: item.name,
				roleId: getId.value,
				type: item.type
			};
		})
		.concat(result);
};

const confirm = async () => {
	const checked = treeRef.value.getCheckedNodes();
	await editRolePermissions(transfrom(checked));
	drawerVisible.value = false;
	datas.length = 0;
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
	let newParams = JSON.parse(JSON.stringify(params));
	if (newParams.createTime) {
		newParams.createTime_begin = newParams.createTime[0];
		newParams.createTime_end = newParams.createTime[1];
		delete newParams.createTime;
	}
	return getBuildUnitList(newParams);
};

const handleAddItem = (index: number, row: any) => {
	if (index === 1) {
		title.value = "新增参建单位";
		formData.value = reactive({
			type: "",
			companyName: "",
			creditCode: "",
			address: "",
			registrationDate: "",
			leadName: "",
			leadTel: "",
			salaryManager: "",
			salaryManagerCard: "",
			salaryManagerTel: "",
			legalPerson: "",
			legalPersonCard: "",
			legalPersonTel: "",
			registeredCapital: "",
			email: "",
			entryTime: "",
			businessLicenseLifespan: ""
		});
	} else {
		title.value = "查看参建单位";
		console.log(row);
		formData.value = reactive({ ...row });
		changeType.value = formData.value.businessLicenseLifespan ? 1 : 2;
	}
	newUnitDialog.value = true;
};

// 修改数据按钮
const handleEditItem = async (row: any) => {
	getId.value = row.roleId;

	drawerVisible.value = true;
	const { result = [] } = await getTreemRoleList();
	// console.log("test", result);
	datas.push(...result);

	const res = await getTreeByIdList({ roleId: row.roleId });
	// 打开弹窗时调用上面的接口勾选
	nextTick(() => {
		treeRef.value.setCheckedKeys(res.result.map((item: { authorityId: any }) => item.authorityId));
	});
};
// TODO: 提交表单操作
const submitForm = async (data: any) => {
	const formEl = formRef.value;
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (changeType.value == 2) {
				delete data.businessLicenseLifespan;
			}
			data.engineeringSn = initParam.engineeringSn;
			saveItem(data);
		} else {
			console.log("error submit!", fields);
		}
	});
};
const saveItem = async (form: any) => {
	// if (form.roleId) {
	// 	// console.log(form.dictCode);
	// 	const res = await editRole(form);
	// 	proTable.value.getTableList();
	// 	ElMessage.success("编辑成功");
	// } else {

	// }
	const res = await addBuildUnit(form);
	ElMessage.success("新增成功");
	proTable.value.getTableList();
	newUnitDialog.value = false;
};

// 删除用户信息
const deleteAccount = async (params: jxj_User.ResUserList) => {
	await useHandleData(deleteRole, { roleId: params.roleId }, `删除【${params.roleName}】`);
	proTable.value.getTableList();
};
// 点击抽屉的工程名称更新页面
const onUpdate = async row => {
	initParam.engineeringSn = row.engineeringSn;
	ElMessage.success("页面已更新");
};
const getengineering = (params: any) => {
	// let newParams = JSON.parse(JSON.stringify(params));
	return getRelevanceList();
};
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
