<template>
  <div class="layout-container">
    <!-- 菜单栏 -->
    <From :form-items="dynamicFormItems" @formSubmitted="handleFormSubmitted" @formReset="handleFormReset" />
	<div  style="display: flex;justify-content: flex-end;padding-right: 50px;">
	  <el-button type="primary"  @click="handleAdd">新增</el-button>
	</div>
    <!-- 表格 -->
    <div class="layout-container">
      <Table @getTableData="changeTableData" v-model:page="page" ref="table" :data="tableData" :showSelection="true"
        @selection-change="handleSelectionChange" @select-all="handleSelectAll" @select="handleSelect">
		<el-table-column prop="channelCode" label="渠道码" />
		<el-table-column prop="userId" label="用户ID" />
		<el-table-column prop="headImage" label="用户头像" >
			<template #default="scope">
				<el-image :src="scope.row.headImage" :preview-src-list="[scope.row.headImage]" fit="cover" preview-teleported="true"   preview-z-index="9999"></el-image>
			</template>
		</el-table-column>
		<el-table-column prop="nickName" label="用户昵称" />
		<el-table-column prop="phone" label="手机号" />
		<el-table-column prop="realName" label="真实姓名" />
		<el-table-column prop="idCard" label="身份证号" />
		<!-- <el-table-column prop="userStatus" label="用户状态" ></el-table-column> -->
		<el-table-column prop="userType" label="用户类型" >
			<template #default="scope">
				{{ scope.row.userType == 1?'app':scope.row.userType == 2?'平台':'代理端' }}
			</template>
		</el-table-column>
		<el-table-column prop="rewardBalance" label="悬赏余额" />
		<el-table-column prop="taskBalance" label="任务余额" />
		<el-table-column prop="totalIncome" label="总收益" />
		<el-table-column prop="loginTime" label="最后登录时间" >
			<template #default="scope">
				{{ formatDateFull(scope.row.loginTime) }}
			</template>
		</el-table-column>
		<el-table-column label="操作" prop="" width="160">
		  <template #default="scope">
			  <el-button type="text" size="default" @click="resetPwd(scope.row)">重置密码</el-button>
			  <el-button type="text" size="default" @click="incomeConfig(scope.row)">收益配置</el-button>
		  </template>
		</el-table-column>
      </Table>
    </div>

    <!-- 操作弹窗 -->
    <Layer :layer="layer" @confirm="submit(ruleForm)" @close="layer.show = false">
		<el-form :model="updateForm" :rules="rules" ref="ruleForm" label-width="120px" style="margin-right:30px;">
		  <el-form-item label="用户账号：" prop="phone">
		    <el-input v-model="updateForm.phone" maxlength="11" placeholder="请输入用户账号" clearable />
		  </el-form-item>
		  <el-form-item label="用户昵称：" prop="nickName">
		    <el-input v-model="updateForm.nickName" placeholder="请输入用户昵称" clearable />
		  </el-form-item>
		  <el-form-item label="用户密码：" prop="password">
		    <el-input v-model="updateForm.password" placeholder="请输入用户密码" clearable />
		  </el-form-item>
		  <el-form-item label="确认密码：" prop="confirmPwd">
		    <el-input v-model="updateForm.confirmPwd" placeholder="请输入确认密码" clearable />
		  </el-form-item>
		</el-form>
    </Layer>
	<!-- 收益配置 -->
	<Layer :layer="layerIncome" @confirm="submitIncome(ruleFormIncome)" @close="closeIncomeLayer">
		<el-form :model="updateFormIncome" :rules="rulesIncome" ref="ruleFormIncome" class="income-config-form" label-width="150px">
		  <div class="income-config-container">
		    <template v-for="(item, index) in updateFormIncome.configParamList" :key="item.type">
		      <div class="income-config-item">
		        <div class="config-item-header">
		          <span class="config-type-name">{{ orderTypes[item.type] || '' }}</span>
		        </div>
		        <div class="config-item-body">
		          <!-- 比例值输入 -->
		          <el-form-item 
		            :label="'收益比例'"
		            :prop="'configParamList.' + index + '.value'"
		            class="config-form-item"
		          >
		            <div class="input-with-unit">
		              <el-input 
		                v-model.number="item.value" 
		                placeholder="请输入比例值" 
		                clearable 
		                type="number"
		                :min="0"
		                :max="100"
		                class="percentage-input"
		              />
		              <span class="unit-text">%</span>
		            </div>
		          </el-form-item>
		          <!-- 备注输入 -->
		          <el-form-item 
		            label="备注"
		            class="config-form-item"
		          >
		            <el-input 
		              v-model="item.remark" 
		              placeholder="请输入备注（选填）" 
		              clearable 
		              maxlength="200"
		              show-word-limit
		              type="textarea"
		              :rows="2"
		              class="remark-input"
		            />
		          </el-form-item>
		        </div>
		      </div>
		    </template>
		  </div>
		</el-form>
	</Layer>
  </div>
</template>

<script setup>
import { onBeforeMount,computed, ref, reactive, nextTick } from "vue";
import From from "@/components/from/index.vue";
import Table from "@/components/table/index.vue";
import Layer from '@/components/layer/index.vue'
import { FullScreen } from '@element-plus/icons'
import { ElMessage, ElLoading,ElMessageBox } from 'element-plus'
import { createNextLevelChannelUser,nextLevelChannelUser,passwordReset,allOrderType,getOrderConfig,saveOrderConfig } from '@/api/userModule.js'
import { convertUTCToBeijing, getTodayRangeLocal,formatDateFull } from '@/utils/index.js'
import { useStore } from 'vuex'
const store = useStore()
const parentId = computed(() => store.state.user.info.parentId);
const tableData = ref([]);
const table = ref(null)
const tableDetail = ref(null)
const tableDetailData = ref([]);
// 分页参数, 供table使用
const page = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
const pageDetail = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});


const formSearch = ref({
  nickName: undefined,// 用户昵称
  phone: undefined,// 用户手机号
  pageNum: 1,// 当前页码
  pageSize: 10,// 当前页数量(查询量)
  loginTime: undefined, //登录时间
});

const dynamicFormItems = ref([])

onBeforeMount(() => {
  settingData()
  getList();
});
const updateForm = ref({
	nickName:'',
	confirmPwd:'',
	password:'',
	phone:'',
})
const layerIncome = ref({
  show: false,
  title: "收益配置",
  showButton: true,
  width: '800px',
  isMulty: false
});
const updateFormIncome = ref({
	configParamList:[]
})
const orderTypes = ref({
	1: "充值",
	2: "提现",
	3: "购买刷新包/置顶包",
	4:"下架",
	5: "购买会员",
	6: "任务发布",
	7: "任务加价",
	8: "任务加量",
	9: "悬赏余额退款",
})
// 关闭收益配置弹窗
const closeIncomeLayer = () => {
	layerIncome.value.show = false
	// 重置表单验证
	if (ruleFormIncome.value) {
		ruleFormIncome.value.clearValidate()
	}
}

// 收益配置 
const incomeConfig = (row)=>{
	curUserId.value = row.userId
	// 先清空表单数据，避免显示旧的验证错误
	updateFormIncome.value.configParamList = []
	// 获取账户订单收益配置
	getOrderConfig({
		userId:row.userId,
	}).then(res=>{
		console.log('res',res)
		// 检查是否有configParamList数据
		if(res.data && res.data.length > 0){
			// 如果有配置数据，直接使用
			updateFormIncome.value.configParamList = res.data.map(item => ({
				...item,
				type: String(item.type),
				value: item.valueBig * 100 || '',
				remark: item.remark || ''
			}))
			// 更新订单类型映射（如果需要）
			if(res.data.orderTypes){
				orderTypes.value = res.data.orderTypes
			}
			// 数据加载完成后，先显示弹窗，然后在表单渲染后生成验证规则
			layerIncome.value.show = true
			// 使用 nextTick 确保表单已经渲染
			nextTick(() => {
				generateIncomeRules()
			})
		} else {
			// 如果没有配置数据，获取所有订单类型并生成默认配置
			allOrderType().then(orderRes=>{
				console.log('allOrderType res',orderRes.data)
				// 更新订单类型
				orderTypes.value = orderRes.data
				// 将订单类型对象转化为configParamList数组
				updateFormIncome.value.configParamList = Object.keys(orderRes.data).map(key => ({
					type: String(key),
					code: 'order',
					value: '',
					remark: ''
				}))
				// 数据加载完成后，先显示弹窗，然后在表单渲染后生成验证规则
				layerIncome.value.show = true
				// 使用 nextTick 确保表单已经渲染
				nextTick(() => {
					generateIncomeRules()
				})
			}).catch(err => {
				console.error('获取订单类型失败:', err)
				ElMessage.error('获取订单类型失败')
				layerIncome.value.show = false
			})
		}
	}).catch(err => {
		console.error('获取收益配置失败:', err)
		ElMessage.error('获取收益配置失败')
		layerIncome.value.show = false
	})
	
}
const submitIncome = async (formEl) => {
	if (!formEl) return
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			let data = {
				userId: curUserId.value,
				code: 'order',
				configParamList: updateFormIncome.value.configParamList.map(item => ({
					type: Number(item.type), // 转换为数字
					code: 'order',
					value: Number(item.value)/100 || 0,
					remark: item.remark || ''
				}))
			}
			try {
				const res = await saveOrderConfig(data)
				console.log('saveOrderConfig res', res)
				if (res.code === 200) {
					layerIncome.value.show = false
					ElMessage.success('收益配置保存成功')
					getList()
				} else {
					ElMessage.error(res.message || '保存失败')
				}
			} catch (error) {
				console.error('保存收益配置失败:', error)
				ElMessage.error('保存失败，请稍后重试')
			}
		} else {
			console.log("error submit!", fields);
			ElMessage.warning('请完善表单信息')
		}
	})
}
const resetPwd = (row)=>{
	ElMessageBox.confirm(
	    '是否将密码重置为 yt123456',
	    '提示',
	    {
	        confirmButtonText: '确认',
	        cancelButtonText: '取消',
	        type: 'warning',
	    }
	)
	    .then(async () => {
			await passwordReset({ targetUserId:row.userId })
	        ElMessage({
	            type: 'success',
	            message: '密码重置成功',
	        })
	        await getList();
	    })
	    .catch(() => {
	        
	    })
}
const handleAdd = ()=>{
	updateForm.value = {
		nickName:'',
		confirmPwd:'',
		password:'',
		phone:'',
	}
	layer.value.show = true
}
const curUserId = ref('') // 用户id
const lookDetail = (row)=>{
	curUserId.value = row.userId
	layer.value.show = true
}
// 获取缓存数据设置筛选数据
const settingData = async () => {
    dynamicFormItems.value = [
      {
        label: '用户昵称',
        prop: 'nickName',
        type: 'input',
        needEnterEvent: true
      },
      {
        label: '用户手机号',
        prop: 'phone',
        type: 'input',
        needEnterEvent: true
      },
	  { label: '登录时间', prop: 'loginTime', type: 'daterange' },
    ]
}


const firstApp = ref('')

// 分页数据
const getList = async () => {
  // openFullScreen('数据请求中，请勿重复点击！！！')
  nextLevelChannelUser({
  	  ...formSearch.value
  }).then(res=>{
  	  tableData.value = res.data.records;
  	  page.total = res.data.total;
  })
};
const changeTableData = (type) => {
	formSearch.value.pageNum =  page.pageNum;
	formSearch.value.pageSize = page.pageSize;
	getList();
};

// 搜索
const handleFormSubmitted = (formData) => {
  // console.log("接收到子组件传递的数据", formData);
  formSearch.value.pageNum = page.pageNum;
  formSearch.value.pageSize = page.pageSize;
  formSearch.value.nickName = formData.nickName;
  formSearch.value.phone = formData.phone;
  if(formData.loginTime){
	  formSearch.value.loginTimeStart = (convertUTCToBeijing(formData.loginTime[0], false) + ' 00:00:00') || undefined
	  formSearch.value.loginTimeEnd = (convertUTCToBeijing(formData.loginTime[1], false) + ' 23:59:59') || undefined
  }

  getList(0);
};

// 表单重置
const handleFormReset = () => {
  formSearch.value = {
    nickName: undefined,// 用户昵称
    pageNum: 1,// 当前页码
    pageSize: 10,// 当前页数量(查询量)
    // lastLoginTimeBegin: getTodayRangeLocal(), //最新登录时间开始
    // lastLoginTimeEnd:undefined //最新登录时间结束
  };

  page.pageNum = 1
  page.pageSize = 10
  page.total = 0
  getList();
  // settingData()
};

const selectData = ref([])
const currentAppName = ref(null) // 存储允许全选的 appName
// 选择监听器
const handleSelectionChange = (val) => {
  selectData.value = val
}

// 全选
const handleSelectAll = (selection) => {
  if (selection.length === 0) {
    // 全选取消
    currentAppName.value = null
    return
  }

  // 取第一个选中的 appName 作为基准
  const firstAppName = selection[0].appName
  // 先全部取消
  table.value.table.clearSelection()

  // 再只选中同一 appName 的行
  tableData.value.forEach(row => {
    if (row.appName === firstAppName) {
      table.value.table.toggleRowSelection(row, true)
    }
  })

  currentAppName.value = firstAppName

}

// 取消全选
const clearSelection = () => {
  currentAppName.value = null
  table.value.table.clearSelection()
}

// 单选
const handleSelect = (selection, row) => {
  // 如果是单选时第一次选中，就记录当前 appName
  if (selection.length === 1) {
    currentAppName.value = selection[0].appName
  }

  // 如果选了不同 appName 的数据，则取消
  if (selection.length > 0 && row.appName !== currentAppName.value) {
    table.value.table.toggleRowSelection(row, false)
    ElMessage.warning('只能选择同一个应用的用户哦')
  }
}

const loading = ref(null)

// 加载信息
const openFullScreen = (loadText) => {
  loading.value = ElLoading.service({
    lock: true,
    text: loadText,
    background: 'rgba(0, 0, 0, 0.7)',
  })
}

const closeFullScreen = () => {
  loading.value.close()
}

// 弹窗
const layer = ref({
  show: false,
  title: "新增渠道用户",
  showButton: true,
  // width: '500px',
  isMulty: false
});

const ruleForm = ref(null);
const ruleFormIncome = ref(null);

// 收益配置表单验证规则
const rulesIncome = reactive({})

// 动态生成收益配置验证规则
const generateIncomeRules = () => {
	if (!updateFormIncome.value.configParamList || updateFormIncome.value.configParamList.length === 0) {
		console.warn('configParamList为空，无法生成验证规则')
		// 清空所有规则
		Object.keys(rulesIncome).forEach(key => {
			delete rulesIncome[key]
		})
		return
	}
	
	// 生成新规则对象
	const newRules = {}
	updateFormIncome.value.configParamList.forEach((item, index) => {
		const ruleKey = `configParamList.${index}.value`
		const itemType = item.type
		// value 字段验证规则（必填）
		newRules[ruleKey] = [
			{ 
				validator: (rule, value, callback) => {
					if (value === null || value === undefined || value === '') {
						callback(new Error(`${orderTypes.value[itemType] || '该类型'}的收益比例不能为空`))
					} else {
						const numValue = Number(value)
						if (isNaN(numValue)) {
							callback(new Error('请输入有效的数字'))
						} else if (numValue < 0 || numValue > 100) {
							callback(new Error('比例值必须在0-100之间'))
						} else {
							callback()
						}
					}
				},
				trigger: ['blur', 'change']
			}
		]
	})
	
	// 清空原有规则
	Object.keys(rulesIncome).forEach(key => {
		delete rulesIncome[key]
	})
	
	// 添加新规则
	Object.keys(newRules).forEach(key => {
		rulesIncome[key] = newRules[key]
	})
	setTimeout(()=>{
		if (ruleFormIncome.value) {
			ruleFormIncome.value.clearValidate()
		}
	})
	console.log('生成的验证规则:', rulesIncome)
	console.log('configParamList长度:', updateFormIncome.value.configParamList.length)
}

const checkPhone = (rule, value, callback) => {
	 // 判断传入的值是否为合法手机号（中国大陆标准）
	 const phoneRegex = /^1[3-9]\d{9}$/;
	 if (value && !phoneRegex.test(value)) {
	   // 校验失败：提示合法手机号格式
	   callback(new Error("请输入11位合法的手机号"));
	 } 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({
  phone: [
    { required: true, message: "请输入用户账号", trigger: "blur" },
	{ validator: checkPhone, trigger: "blur" },
  ],
  nickName: [
    {
      required: true,
      message: "请输入用户昵称",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入用户密码", trigger: "blur" },
  ],
  confirmPwd: [
    { required: true, message: "请输入确认密码", trigger: "blur" },
  ],
});
const submit = async (formEl) => {
	let data = {...updateForm.value}
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      createNextLevelChannelUser(data).then(res=>{
		  console.log('res',res)
		  layer.value.show = false
		  ElMessage.success('新增成功')
		  getList()
	  })
    } else {
      console.log("error submit!", fields);
    }
  })
}

</script>

<style scoped lang="scss">
.layout-container {

  .card {
    .title {
      margin-bottom: 10px;
      font-weight: 600;
    }

    display: flex;
    flex-direction: column;
    align-items: start;
    width: calc(100% - 60px);
    margin: 30px 30px 0;
  }

  .button {
    display: flex;
    //flex-direction: column;

    .button-item {
      margin: 4px;
    }
  }
}

.btn {
  display: flex;
  margin: 10px 0 -10px 30px;
}

.full-icon {
  position: absolute;
  right: 40px;
  top: 15px;
  cursor: pointer;
  padding: 8px;
  border-radius: 5px;
}

// 收益配置表单样式
.income-config-container {
  // max-height: 600px;
  // overflow-y: auto;
  padding-right: 10px;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;

    &:hover {
      background: #a8a8a8;
    }
  }
}

.income-config-item {
  background: #fafafa;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  transition: all 0.3s ease;

  &:hover {
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
  }

  &:last-child {
    margin-bottom: 0;
  }
}

.config-item-header {
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e8e8e8;

  .config-type-name {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    position: relative;
    padding-left: 12px;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 16px;
      background: #409eff;
      border-radius: 2px;
    }
  }
}

.config-item-body {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.config-form-item {
  margin-bottom: 0 !important;

  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #606266;
  }
}

.input-with-unit {
  display: flex;
  align-items: center;
  gap: 8px;

  .percentage-input {
    width: 200px;
  }

  .unit-text {
    color: #909399;
    font-size: 14px;
    font-weight: 500;
    min-width: 20px;
  }
}

.remark-input {
  width: 100%;

  :deep(.el-textarea__inner) {
    resize: vertical;
  }
}

// 收益配置表单响应式样式
.income-config-form {
  margin-right: 0;
  padding: 0;

  // 手机端响应式
  @media screen and (max-width: 768px) {
    :deep(.el-form-item) {
      display: flex;
      flex-direction: column;
    }

    :deep(.el-form-item__label) {
      width: 100% !important;
      text-align: left !important;
      margin-bottom: 0px !important;
      padding: 0 !important;
      line-height: 1.5;
	  justify-content: flex-start;
    }

    :deep(.el-form-item__content) {
      margin-left: 0 !important;
      width: 100%;
    }
  }

  @media screen and (max-width: 480px) {
    padding: 0 5px;
  }
}

// 收益配置容器响应式
@media screen and (max-width: 768px) {
  .income-config-container {
    max-height: calc(100vh - 250px);
    padding-right: 5px;
  }

  .income-config-item {
    padding: 12px;
    margin-bottom: 12px;
  }

  .config-item-header {
    margin-bottom: 12px;
    padding-bottom: 8px;

    .config-type-name {
      font-size: 14px;
      padding-left: 10px;

      &::before {
        width: 3px;
        height: 14px;
      }
    }
  }

  .config-item-body {
    gap: 12px;
  }

  .input-with-unit {
    flex-direction: row;
    align-items: center;
    gap: 8px;
    width: 100%;

    .percentage-input {
      flex: 1;
      width: auto !important;
    }

    .unit-text {
      position: static;
      flex-shrink: 0;
      margin-left: 0;
    }
  }

  .config-form-item {
    :deep(.el-form-item__label) {
      width: 100% !important;
      margin-bottom: 8px;
      padding: 0;
      text-align: left;
    }

    :deep(.el-form-item__content) {
      margin-left: 0 !important;
      width: 100%;
    }
  }

  .remark-input {
    width: 100%;
  }
}

// Layer 弹窗响应式样式 - 通过深度选择器覆盖
:deep(.el-dialog) {
  @media screen and (max-width: 768px) {
    width: 95% !important;
    margin: 2vh auto !important;
    max-height: 96vh;
    display: flex;
    flex-direction: column;
  }

  @media screen and (max-width: 480px) {
    width: 98% !important;
    margin: 1vh auto !important;
  }
}

:deep(.el-dialog__header) {
  @media screen and (max-width: 768px) {
    padding: 15px 15px 10px;
    flex-shrink: 0;
  }

  @media screen and (max-width: 480px) {
    padding: 12px 12px 8px;

    .el-dialog__title {
      font-size: 16px;
    }
  }
}

:deep(.el-dialog__body) {
  @media screen and (max-width: 768px) {
    flex: 1;
    overflow: hidden;
    padding: 15px;
    max-height: calc(96vh - 120px);
  }

  @media screen and (max-width: 480px) {
    padding: 12px;
  }
}

:deep(.el-dialog__footer) {
  @media screen and (max-width: 768px) {
    padding: 10px 15px;
    flex-shrink: 0;
    display: flex;
    gap: 10px;

    .el-button {
      flex: 1;
      margin: 0;
    }
  }

  @media screen and (max-width: 480px) {
    padding: 8px 12px;
    flex-direction: column;
    gap: 8px;

    .el-button {
      width: 100%;
    }
  }
}
</style>