<template>
	<div class="layout-container">
		<From :form-items="dynamicFormItems" @formSubmitted="handleFormSubmitted" @formReset="handleFormReset" />
		<div class="layout-container">
			<Table @getTableData="changeTableData" v-model:page="page" ref="table" :data="tableData"
				@selection-change="handleSelectionChange" style="margin-top: 10px">
				<el-table-column prop="" label="查看ecpm" width="110">
					<template #default="scope">
						<el-button type="primary" size="small" @click="viewEcpm(scope.row)">查看ecpm</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="id" width="80" label="用户id" ></el-table-column>
				<el-table-column prop="nickName" label="用户昵称" />
				<el-table-column prop="openId" label="openId" />
				<el-table-column prop="userState" width="90" label="用户状态">
					<template #default="scope">
						{{ scope.row.userState == 0?'正常':'封禁' }}
					</template>
				</el-table-column>
				<el-table-column prop="gameName" label="游戏名称" width="120" />
				<el-table-column prop="todayAdPlay" label="今日激励广告播放数" width="160" />
				<el-table-column prop="totalAdPlay" label="广告播放总数" width="110" />
				<el-table-column prop="contribution" label="用户贡献(当日/总共)" width="160"  />
				<el-table-column label="操作" width="90" >
				<template #default="scope">
				  <el-button type="text" size="default" style="color: red;" v-if="scope.row.userState == 0" @click="block(scope.row)">封禁</el-button>
				  <el-button type="text" size="default" style="color: green;" v-else @click="unblock(scope.row)">解封</el-button>
				</template>
			  </el-table-column>
			</Table>
		</div>
		<Layer :layer="layer" @confirm="confirm(ruleFormRef)">
			<el-form ref="ruleFormRef" :rules="rules" :model="updateForm" label-width="100px" class="demo-ruleForm">
				<el-form-item label="用户状态：" v-if="layer.title=='更改用户状态'" prop="statusCode" label-width="120">
					正常
				</el-form-item>
				<el-form-item label=" 封禁期限：" v-else prop="banDuration" label-width="120">
					<el-input v-model="updateForm.banDuration" type="number" placeholder="请输入封禁期限" >
						<template #append>小时</template>
					</el-input>
				</el-form-item>
				<el-form-item :label="layer.title=='更改用户状态' ?'解封原因：': '封禁原因：'" prop="banReason" label-width="120">
					<el-input :placeholder="layer.title=='更改用户状态' ?'请输入解封原因：': '请输入封禁原因：'" maxlength="15" v-model="updateForm.banReason">
					</el-input>
				</el-form-item>
			</el-form>
		</Layer>
		<Layer :layer="layerView" @close="adType = null">
			<el-form ref="ruleFormRef" :rules="rules" :model="updateForm" label-width="100px" class="demo-ruleForm">
				<el-row>
					<el-form-item label="广告类型：" prop="adType" label-width="120">
						<el-select v-model="adType" placeholder="请选择" style="width: 240px">
						    <el-option
						      v-for="item in options"
						      :key="item.value"
						      :label="item.label"
						      :value="item.value"
						    />
						  </el-select>
					</el-form-item>
					<el-form-item label="" label-width="20">
						<el-button type="primary" @click="ecpmSearch">查询</el-button>
						<el-button @click="ecpmReset">重置</el-button>
					</el-form-item>
				</el-row>
			</el-form>
			<Table ref="tableECPM" v-model:page="ecpmPage"  :data="ecpmList" style="margin-top: 10px;max-height: 500px;overflow-y: auto;">
				<el-table-column prop="id" label="用户id" ></el-table-column>
				<el-table-column prop="advertisingType" label="广告类型" >
					<template #default="scope">
						{{ scope.row.advertisingType == '1'?'激励广告':scope.row.advertisingType == '2'?'插屏广告':'bannner广告' }}
					</template>
				</el-table-column>
				<el-table-column prop="ecpm" label="ECPM" />
				<el-table-column prop="earnings" label="收益" width="120" />
				<el-table-column prop="accomplishTime" label="完成时间" width="150" />
			</Table>
		</Layer>
	</div>
</template>

<script setup>
import { onBeforeMount, ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import Table from "@/components/table/index.vue";
import From from "@/components/from/index.vue";
import Layer from "@/components/layer/index.vue";
import { sysUserUpdate, sysUserRegister, sysUserPage, becomeHead,
		queryUserList,disableUser,enableUser,updateUserStatus,queryUserEcpm } from '@/api/sysUser'
import { queryGameList } from '@/api/common.js'

import { beforeAvatarUpload } from '@/utils/index.js'
import { Plus } from "@element-plus/icons-vue";
import OssUploader from "@/utils/ossUploader.js";
const partnerList = ['普通用户','初级合伙人','高级合伙人','团长']
const ossUploader = new OssUploader();
// const gameList=
onBeforeMount(async() => {
	searchFormList();
	let res = await queryGameList()
	if(res.length){
		res = res.map(item=>{
			return{
				label:item.gameName,
				value:item.gameCode
			}
		})
	}
	dynamicFormItems.value[0].options  = res
	console.log('res',res)
});


const adType = ref('')
const options = [
  {
    value: '1',
    label: '激励',
  },
  {
    value: '2',
    label: '插屏',
  },
  {
    value: '3',
    label: 'banner',
  },
]
const ecpmList = ref([])
const ecpmUserId = ref('')
const searchEcpmList = async() =>{
	// 获取对应的数据
	const res = await queryUserEcpm({
		advertisingType:adType.value,
		userId:ecpmUserId.value,
	})
	ecpmList.value = res
	ecpmPage.total = res.length;
}
// ecpm 查询/重置
const ecpmSearch = ()=>{
	searchEcpmList()
}
// ecpm 查询/重置
const ecpmReset = ()=>{
	adType.value = null 
	searchEcpmList()
}
const tableData = ref([]);
// 分页参数, 供table使用
const page = reactive({
	pageNum: 1,
	pageSize: 20,
	total: 0,
});
const ecpmPage = reactive({
	pageNum: 1,
	pageSize: 100,
	total: 0,
});
const ruleFormRef = ref(null);
const layer = ref({
	show: false,
	title: "新增",
	showButton: true,
});
const layerView = ref({
	show: false,
	title: "查看ECPM",
	showButton: false,
});
const dynamicFormItems = ref([
	{ label: "游戏名称",  
	  prop: "gameCode",
	  type: "select",
	  options: [
	    { label: "游戏1", value: 0 },
	    { label: "游戏2", value: 1 },
	  ],},
	{ label: "用户id", prop: "userId", type: "input" },
	{ label: "openId", prop: "openId", type: "input" },//"daterange"
	{
	  label: "用户状态",
	  prop: "userState",
	  type: "select",
	  options: [
	    { label: "正常", value: 0 },
	    { label: "封禁", value: 1 },
	  ],
	},
	// 其他动态的表单项配置
]);
const handleFormSubmitted = (formData) => {
	console.log("接收到子组件传递的数据", formData);
	if (formData.createdTime) {
		formSearch.value.beginTime = new Date(formData.createdTime[0])
			.toLocaleDateString()
			.slice()
			.replace(/\//g, "-");
		formSearch.value.endTime = new Date(formData.createdTime[1])
			.toLocaleDateString()
			.slice()
			.replace(/\//g, "-");
	} else {
		formSearch.value.beginTime = null;
		formSearch.value.endTime = null;
	}

	// 其他处理逻辑
	Object.assign(formSearch.value, formData)
	formSearch.value.createdTime = undefined

	searchFormList();
};
const updateForm = ref({
	userId: '',//用户id
	banDuration: '',//封禁时长(小时)
	banReason: '',//	封禁原因
});
const checkLoginName = (rule, value, callback) => {
	// 判断传入的值是否可以通过校验
	const regex = /^[a-zA-Z0-9]{3,10}$/;
	if (value && !regex.test(value)) {
		callback(new Error("用户名限3-10位以内数字、字母"));
	} else {
		callback();
	}
};
const checkNickName = (rule, value, callback) => {
	// 判断传入的值是否可以通过校验
	// const regex = /^[A-Za-z0-9\u4e00-\u9fa5]{1,10}$/;
	// if (value && !regex.test(value)) {
	// 	callback(new Error("昵称限3-15位以内中文、数字或字母"));
	// } else {
		callback();
	// }
};
const checkEncodedPassword = (rule, value, callback) => {
	// 判断传入的值是否可以通过校验
	// const regex = /^[A-Za-z\d]{6,16}$/;
	// if (value && !regex.test(value)) {
	// 	callback(new Error("密码限6-16位数字、字母组成"));
	// } else {
		callback();
	// }
};
const rules = reactive({
	userLoginName: [
		{
			required: true,
			message: "请输入用户名",
			trigger: "blur",
		},
		{ validator: checkLoginName, trigger: "blur" },
	],
	banDuration: [
		{
			required: true,
			message: "请输入封禁期限",
			trigger: "blur",
		},
		// { validator: checkNickName, trigger: "blur" },
	],
	banReason: [
		{
			required: true ,
			message: "请输入原因",
			trigger: "blur",
		},
		// { validator: checkEncodedPassword, trigger: "blur" },
	],
	// statusCode: [
	//   {
	//     required: true,
	//     message: "请选择状态",
	//     trigger: "change",
	//   },
	// ],
});
const confirm = async (formEl) => {
	let data = updateForm.value
	console.log('data',data)
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			// data.id ? await sysUserUpdate(data) : await sysUserRegister(data)
			if(layer.value.title=='更改用户状态'){ // 解封
				// enableUser 、 updateUserStatus
				enableUser({
					userId:data.userId,
					id:data.userId,
					deblockingReason:data.banReason,
					userState:0, // 解封
				}).then(res=>{
					layer.value.show = false;
					ElMessage.success("解封成功");
				})
			}else{ // 封禁
				disableUser({
					userId:data.userId,
					banDuration:data.banDuration,
					banReason:data.banReason
				}).then(res=>{
					layer.value.show = false;
					ElMessage.success("封禁成功");
				})
			}
			setTimeout(()=>{
				searchFormList();
			},300)
		} else {
			console.log("error submit!", fields);
		}
	});
};
// 查询
const searchFormList = async () => {
	// const res = await sysUserPage(formSearch.value);
	const res = await queryUserList(formSearch.value);
	tableData.value = res.records;
	page.total = res.total;
};
const changeTableData = () => {
	formSearch.value.pageNum = page.pageNum;
	formSearch.value.pageSize = page.pageSize;
	searchFormList();
};
const handleFormReset = () => {
	formSearch.value = {
		hours: "", //用户真实名称查询
		userLoginName: "", //用户用户名查询
		id: "", //用户ID
		pageNum: 1,
		pageSize: 20,
	};
	// 其他处理逻辑
	searchFormList();
};
const formSearch = ref({
	hours: "", //用户真实名称查询
	userLoginName: "", //用户用户名查询
	userPhone: "", //用户手机号
	pageNum: 1,
	pageSize: 20,
});
const handleSelectionChange = (val) => {
	chooseData.value = val;
};
// 查看ecpm
const viewEcpm = async(row)=>{
	layerView.value.show = true
	ecpmUserId.value = row.id
	searchEcpmList()
}
// 封禁
const block = async(row)=>{
	layer.value.title = "封禁用户";
	layer.value.show = true
	setTimeout(() => { ruleFormRef.value.clearValidate();updateForm.value.userId = row.id })
	// ElMessage.success('操作成功')
}
// 解除封禁
const unblock = async(row)=>{
	layer.value.title = "更改用户状态";
	layer.value.show = true
	setTimeout(() => { ruleFormRef.value.clearValidate();updateForm.value.userId = row.id })
	// ElMessage.success('操作成功')
}
// 编辑
const edit = async (row) => {
	// console.log(row);
	// storage.value = row;
	layer.value.title = "编辑";
	layer.value.show = true;

	updateForm.value.userLoginName = row.userLoginName
	// updateForm.value.reason = row.reason
	updateForm.value.hours = row.hours
	updateForm.value.userImg = row.userImg
	updateForm.value.id = row.id
	setTimeout(() => { ruleFormRef.value.clearValidate() })
};
// 删除
const del = async (row) => {
	await sysUserUpdate({ id: row.id, delInd: '1' });
	ElMessage.success("删除成功");
	searchFormList();
};
const selfUpload = (param) => {
	const file = param.file;
	const currentPath = "admin/";
	//  const formData = new FormData();
	//  formData.append("file", file); // 这里可以根据需要设置其他表单字段
	//  // formData.append("filePath", currentPath);
	//  uploadFile(formData).then((res) => {
	//     if(res.statusCode === 200){
	//       ElMessage.success('上传成功');
	//     }
	//     // console.log(res,8);
	//     updateForm.value.userImg = res;
	//  });
	//  return formData;
	ossUploader
		.uploadFile(file, currentPath)
		.then((res) => {
			ElMessage.success("上传成功");
			updateForm.value.userImg = res;
		})
		.catch((error) => {
			ElMessage.error("上传失败");
		});
};
</script>

<style lang="scss" scoped>
.btn {
	display: flex;
	margin: 10px;
}

.avatar {
	width: 50px;
	height: 50px;
}

.avatar-uploader .avatar {
	width: 178px;
	height: 178px;
	display: block;
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	height: 178px;
	width: 178px;
	text-align: center;
}
</style>