<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">
        <el-table-column prop="userId" label="查看ECPM" width="130" fixed="left">
          <template #default="scope">
            <el-button type="primary" @click="lookEcpm(scope.row.userId)">查看ECPM</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="userId" label="用户ID" width="100" fixed="left" />
        <el-table-column prop="nickName" label="用户昵称" fixed="left" width="90" />
        <el-table-column prop="userStatus" label="用户状态" width="90">
          <template #default="scope">
            {{ getDictionaryName('user_status',Number(scope.row.userStatus)) }}
          </template>
        </el-table-column>
<!--        <el-table-column prop="userType" label="用户类型" width="90" />-->
        <el-table-column prop="appId" label="应用ID" width="150" />
        <el-table-column prop="appName" label="应用名称" width="150" />
        <el-table-column prop="appType" label="应用类型" width="90" />
        <el-table-column prop="communicationOperator" label="通信运营商" width="100" />
        <el-table-column prop="deviceRepeatCount" label="设备重复数量" width="110" />
        <el-table-column prop="ipRepeatCount" label="IP重复数量" width="100" />
        <el-table-column prop="lastLoginIp" label="最新登录IP" width="150" />
        <el-table-column prop="lastLoginTime" label="最新登录时间" width="160">
          <template #default="scope">
            {{ convertUTCToBeijing(scope.row.lastLoginTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="todayVideo" label="今日视频播放数" width="130" />
        <el-table-column prop="totalVideo" label="视频播放总数" width="110" />
        <el-table-column prop="totalIncome" label="用户贡献（当日/总共）" width="180">
          <template #default="scope">
            {{ scope.row.todayIncome === 0 ? '0.00' : scope.row.todayIncome ?? '0.00'}} / 
            {{ scope.row.totalIncome === 0 ? '0.00' : scope.row.totalIncome ?? '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="loginDays" label="登录天数" width="90" />
        <el-table-column prop="pointsBalance" label="积分余额" width="90" />
        <el-table-column prop="pointsTotal" label="积分总额" width="90" />
        <el-table-column prop="redPacketAmount" label="红包总额" width="90" />
        <el-table-column prop="redPacketBalance" label="红包余额" width="90" />
        <el-table-column prop="registryTime" label="注册时间" width="160">
          <template #default="scope">
            {{ convertUTCToBeijing(scope.row.registryTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="versionCode" label="版本号" />
        <el-table-column prop="withdrawCount" label="提现笔数" width="90" />
        <el-table-column prop="withdrawTotal" label="提现总额" width="90" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <div class="button">
              <el-button class="button-item" type="primary" style="margin-bottom: 5px;"
                @click="editUserType(scope.row)">
                风控解除
              </el-button>
              <el-button  v-if="scope.row.userStatus < 3" class="button-item" type="danger" style="margin-bottom: 5px;" @click="edit(scope.row)">
                封禁用户
              </el-button>
              <el-popconfirm title="确认锁定该用户?" @confirm="lockUser(scope.row)">
                <template #reference>
                  <el-button v-if="scope.row.userStatus < 2" class="button-item" style="margin-bottom: 5px;" type="warning">锁定用户</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </Table>
    </div>

    <!-- 操作弹窗 -->
    <Layer :layer="layer" @confirm="submit(ruleForm)" @close="layer.show = false">
      <el-form :model="formEdit" :rules="rules" ref="ruleForm" label-width="120px" style="margin-right:30px;">
        <el-form-item label="封禁期限：" required prop="bannedLimit">
          <el-input v-model="formEdit.bannedLimit" type="number" placeholder="请输入封禁期限" clearable />
        </el-form-item>
        <el-form-item label="封禁原因：" required prop="bannedReason">
          <el-input v-model="formEdit.bannedReason" placeholder="请输入封禁原因" clearable />
        </el-form-item>
      </el-form>
    </Layer>

    <Layer :layer="layer1" @confirm="submit1(ruleForm1)" @close="layer.show = false">
      <el-form :model="formEdit1" :rules="rules1" ref="ruleForm1" label-width="120px" style="margin-right:30px;">
        <el-form-item label="用户状态：" required prop="userStatus">
          <el-select v-model="formEdit1.userStatus" placeholder="请选择状态" filterable>
            <el-option v-for="option in getOptions('user_status')" :key="option.label" :label="option.label"
              :value="option.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="原因：" prop="reason">
          <el-input v-model="formEdit1.reason" placeholder="请输入原因" clearable />
        </el-form-item>
      </el-form>
    </Layer>

    <Layer :layer="ecpmLayer" @confirm="ecpmLayer.show = false" @close="ecpmLayer.show = false">
        <Table :showPage="false" ref="ecpmTable" :data="ecpmData" :height="ecpmLayer.height">
          <el-table-column prop="userId" label="用户ID" width="100" />
          <el-table-column prop="adSourceId" label="广告源ID" width="100" />
          <el-table-column prop="beginTime" label="开始时间" />
          <el-table-column prop="finishTime" label="完成时间" />
          <el-table-column prop="ecpm" label="ECPM" width="100" />
          <el-table-column prop="adSourceType" label="广告源类型" width="160">
            <template #default="scope">
              {{ getDictionaryName('ad_source_type',scope.row.adSourceType) }}
            </template>
          </el-table-column>
          <el-table-column prop="adSourceIndex" label="竞价匹配优先级" width="130" />
          <el-table-column prop="networkFormId" label="广告平台ID" width="100" />
          <el-table-column prop="networkName" label="广告平台名称" width="120" />
          <el-table-column prop="networkPlacementId" label="广告平台广告位ID" width="160" />
          <el-table-column prop="nickName" label="用户昵称" width="100" />
          <el-table-column prop="placementId" label="广告位ID" width="100" />
          <el-table-column prop="recordId" label="广告记录ID" width="100" />
          <el-table-column prop="revenue" label="收益" width="100" />
        </Table>
    </Layer>
  </div>
</template>

<script setup>
  import { onBeforeMount, ref, reactive } from "vue";
  import From from "@/components/from/index.vue";
  import Table from "@/components/table/index.vue";
  import Layer from '@/components/layer/index.vue'
  import Card from './components/card/index.vue'
  import { ElMessage } from 'element-plus'
  import { getUserList, getStaticList, riskBannedUser, riskLockUser, appUserEcpm } from '@/api/userModule.js'
  import { riskChangeUserStatus } from '@/api/riskModule.js'
  import { convertUTCToBeijing } from '@/utils/index.js'
  import { useGetDictList } from '@/hooks/useGetDictList.js'
  import { useStore } from 'vuex'

  const store = useStore()
  const { dictData, loadDictData, getOptions, getDictionaryName } = useGetDictList();
  const form = ref(null);
  const tableData = ref([]);

  // 分页参数, 供table使用
  const page = reactive({
    pageNum: 1,
    pageSize: 20,
    total: 0,
  });

  const formSearch = ref({
    channelOrigin: undefined,// 渠道来源
    channelType: undefined,// 渠道类型
    lastLoginTime: undefined,// 最新登录时间
    limit: 20,// 当前页数量(查询量)
    nickName: undefined,// 用户昵称
    userId: undefined,// 用户ID
    page: 1,// 当前页码
    registryTime: undefined,// 注册时间
    userType: undefined,// 用户类型
  });

  const dynamicFormItems = ref([])

  onBeforeMount(() => {
    settingData()
    getList();
  });

  // 获取缓存数据设置筛选数据
  const settingData = () => {
    loadDictData().then(() => {
      dynamicFormItems.value = [
        {
          label: '用户昵称',
          prop: 'nickName',
          type: 'input',
          needEnterEvent: true
        },
        {
          label: '用户ID',
          prop: 'userId',
          type: 'input',
          needEnterEvent: true
        },
        /* {
          label: '渠道类型',
          prop: 'channelType',
          type: 'select',
          options: getOptions('channel_type')
        }, */
        {
          label: '渠道来源',
          prop: 'channelOrigin',
          type: 'select',
          options: getOptions('channel_origin'),
        },
        {
          label: '用户类型',
          prop: 'userType',
          type: 'select',
          options: getOptions('user_status'),
        },
        { label: '登录时间', prop: 'lastLoginTime', type: 'date' },
        { label: '注册时间', prop: 'registryTime', type: 'date' },
      ]
    })
  }

  // 分页数据
  const getList = async () => {
    let res = await getUserList({ ...formSearch.value });
    tableData.value = res.data;
    page.total = res.pageMeta.total;
  };

  const changeTableData = () => {
    formSearch.value.page = page.pageNum;
    formSearch.value.limit = page.pageSize;

    console.log('page',page)
    // 分页切换
    getList();
  };

  // 搜索
  const handleFormSubmitted = (formData) => {
    // console.log("接收到子组件传递的数据", formData);
    formSearch.value.page = 1;
    formSearch.value.limit = 20;
    formSearch.value.nickName = formData.nickName;
    formSearch.value.userId = formData.userId;
    formSearch.value.channelOrigin = formData.channelOrigin;
    formSearch.value.channelType = formData.channelType;
    formSearch.value.userType = formData.userType;
    formSearch.value.lastLoginTime = formData.lastLoginTime || null
    formSearch.value.registryTime = formData.registryTime || null

    getList();
  };

  // 表单重置
  const handleFormReset = () => {
    formSearch.value = {
      channelOrigin: undefined,// 渠道来源
      channelType: undefined,// 渠道类型
      lastLoginTime: undefined,// 最新登录时间
      limit: 20,// 当前页数量(查询量)
      nickName: undefined,// 用户昵称
      userId: undefined,// 用户ID
      page: 1,// 当前页码
      registryTime: undefined,// 注册时间
      userType: undefined,// 用户类型
    };
    getList();
  };

  // 选择监听器
  const handleSelectionChange = (val) => {
    context.emit("selection-change", val)
  }

  // 弹窗
  const layer = ref({
    show: false,
    title: "封禁用户",
    showButton: true,
    width: '300px'
  });

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

  const edit = (row) => {
    ruleForm.value?.resetFields()
    layer.value.show = true
    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
  }

  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) {
        // 提交内容
        riskBannedUser({ ...formEdit.value }).then((res) => {
          ElMessage.success('封禁用户成功')
          layer.value.show = false
          getList();
        })
      } else {
        console.log("error submit!", fields);
      }
    })  
  }

  // 弹窗2
  const layer1 = ref({
    show: false,
    title: "更改用户状态",
    showButton: true,
    width: '300px'
  });

  const formEdit1 = ref({
    bannedType: null,//封禁类型 1-渠道 2-平台
    operator: '',//操作人
    operatorName: '',//操作人名称
    reason: '',//原因
    userId: '', //用户ID
    userStatus: null, //用户状态
  })

  const editUserType = (row) => {
    ruleForm1.value?.resetFields()
    layer1.value.show = true

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

  const ruleForm1 = ref(null);

  const rules1 = reactive({
    userStatus: [
      {
        required: true,
        message: "请选择用户状态",
        trigger: "change",
      },
    ],
    reason: [
      {
        required: true,
        message: "请输入更改原因",
        trigger: ["blur"],
      },
    ],
  });

  const submit1 = async (formEl) => {
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        // 提交内容
        riskChangeUserStatus(formEdit1.value).then((res) => {
          ElMessage.success('更改用户状态成功')
          layer1.value.show = false
          getList();
        })
      } else {
        console.log("error submit!", fields);
      }
    })
  }


  // 锁定用户
  const lockUser = async (row) => {
    riskLockUser({ userId: row.userId }).then((res) => {
      ElMessage.success('锁定用户成功')
      getList();
    })
  }

  // 查看ECPM
  const ecpmLayer = ref({
    show: false,
    title: "查看ECPM",
    showButton: true,
    width: '90vw',
    height: '60vh'
  });

  const ecpmTable = ref(null)
  const ecpmData = ref([])

  const lookEcpm = async(userId)=> {
    ecpmData.value = []
    let res = await appUserEcpm({userId})
    ecpmData.value = res.data
    ecpmLayer.value.show = true
  }

</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;
      }
    }
  }
</style>