<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" :showSelection="true"
        @selection-change="handleSelectionChange" @select-all="handleSelectAll" @select="handleSelect"
        :revenue="totalRevenue">
		<el-table-column prop="userId" label="查看明细" width="130">
		  <template #default="scope">
		    <el-button type="primary" @click="lookDetail(scope.row)">查看明细</el-button>
		  </template>
		</el-table-column>
		<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>
      </Table>
    </div>

    <!-- 操作弹窗 -->
    <Layer :layer="layer" @confirm="submit(ruleForm)" @close="layer.show = false">
		<Table @getTableData="changeTableDetailData" v-model:page="pageDetail" ref="tableDetail" :data="tableDetailData" >
				<el-table-column prop="orderInfo" label="订单名称" />
				<el-table-column prop="createTime" label="订单时间" />
				<el-table-column prop="amount" label="订单金额" />
				<el-table-column prop="serviceFee" label="平台收取的服务费/手续费" />
		</Table>
    </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 } from 'element-plus'
import { invitationCodeUser,getUserList,orderPageList } 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);
console.log('parentId',parentId.value)
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 curUserId = ref('') // 用户id
const lookDetail = (row)=>{
	curUserId.value = row.userId
	layer.value.show = true
	getDetailList()
}
// 获取缓存数据设置筛选数据
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 totalRevenue = ref(0)

// 分页数据
const getList = async (timeout = 0) => {
  // openFullScreen('数据请求中，请勿重复点击！！！')
  return new Promise((resolve) => {
    setTimeout(async () => {
      try {
		let apiRequest =  parentId.value ? invitationCodeUser : getUserList
        const listRes = await apiRequest({...formSearch.value })
		console.log('listRes',listRes)
        tableData.value = listRes.data.records;
        page.total = listRes.data.total;
        resolve(true);
      } catch (e) {
        console.log('数据请求超时或报错', e)
        resolve(false);
      } finally {
		  
      }
    }, timeout)
  });
};
const getDetailList = ()=>{
	orderPageList({
		...pageDetail,
		userId:curUserId.value
	}).then(res=>{
		tableDetailData.value = res.data.records;
		pageDetail.total = res.data.total;
	})
}
const changeTableData = (type) => {
	formSearch.value.pageNum =  page.pageNum;
	formSearch.value.pageSize = page.pageSize;
	getList();
};

const changeTableDetailData = ()=>{
	formSearch.value.pageNum = page.pageNum;
	formSearch.value.pageSize = page.pageSize;
	getDetailList();
}

// 搜索
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: false,
  // width: '500px',
  isMulty: false
});

const formEdit = ref({
  bannedLimit: undefined, //封禁期限
  bannedReason: undefined,//封禁原因
  bannedTargetId: undefined,//封禁目标ID
  bannedType: undefined,//封禁类型 1-渠道 2-平台
  operator: undefined,//操作人
  operatorName: undefined,//操作人名称
  userId: undefined, //用户ID
  appId: undefined,//应用ID
  userIds: undefined, //用户ID
})

const edit = (row, isMulty = 0) => {
  ruleForm.value?.resetFields()
  layer.value.isMulty = isMulty

  if (isMulty === 1) {
    layer.value.title = '批量封禁用户'
    formEdit.value = {}

  } else if(isMulty === 2) {
    layer.value.title = '批量封禁母包'
    formEdit.value = {}

  } else {
    layer.value.title = '封禁用户'

    formEdit.value.bannedTargetId = row.appId
    formEdit.value.bannedType = row.channelType
    formEdit.value.operator = store.state.user.info.loginName
    formEdit.value.operatorName = store.state.user.info.nickName
    formEdit.value.userId = row.userId
    formEdit.value.appId = row.appId
  }

  layer.value.show = true
}

const ruleForm = ref(null);

const rules = reactive({
  formEditbannedLimit: [
    { required: true, message: "请输入封禁期限", trigger: "blur" },
  ],
  bannedReason: [
    {
      required: true,
      message: "请输入封禁原因",
      trigger: "blur",
    },
  ],
});

const submit = async (formEl) => {
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      
    } 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;
}
</style>