<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="appId" label="应用ID" width="150" />
        <el-table-column prop="appName" label="应用名称" width="150" />
        <el-table-column prop="nickName" label="用户昵称" width="120" />
        <el-table-column prop="userId" label="用户ID" width="120" />
        <el-table-column prop="userStatus" label="用户状态" width="90">
          <template #default="scope">
            {{ getDictionaryName('user_status',scope.row.userStatus) }}
          </template>
        </el-table-column>
        <el-table-column prop="bannedLimit" label="风控期限" width="90">
          <template #default="scope">
            {{ scope.row.bannedLimit }}天
          </template>
        </el-table-column>
        <el-table-column prop="bannedReason" label="封禁原因" width="260" />
        <el-table-column prop="bannedTime" label="封禁时间" width="160">
          <template #default="scope">
            {{ convertUTCToBeijing(scope.row.bannedTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="bannedType" label="封禁类型" width="90">
          <template #default="scope">
            {{ scope.row.bannedType === 1 ? '渠道' : '平台' }}
          </template>
        </el-table-column>
        <el-table-column prop="channelId" label="渠道商ID" width="110" />
        <el-table-column prop="phoneModel" label="手机型号" width="110" />
        <el-table-column prop="platformId" label="平台ID" width="150" />
        <el-table-column prop="communicationOperator" label="IP运营商" width="120" />
        <el-table-column prop="ipAddr" label="IP归属地" width="200" />
        <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="operatorName" label="操作人" width="90" />

        <el-table-column prop="registryTime" label="注册时间" width="160">
          <template #default="scope">
            {{ convertUTCToBeijing(scope.row.registryTime) }}
          </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="reason">
          <el-input v-model="formEdit.reason" placeholder="请输入封禁原因" clearable />
        </el-form-item>
      </el-form>
    </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 } from '@/api/userModule.js'
  import { riskBannedList, 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({
    userId: null,//用户ID
    appId: null,// 应用ID
    bannedReason: null, //封禁原因
    bannedTimeBegin: null, //封禁开始时间
    bannedTimeEnd: null, //封禁结束时间
    channelId: null,// 渠道商ID
    channelOrigin: null, //渠道来源
    channelType: null,//渠道类型

    limit: 20,// 当前页数量(查询量)
    page: 1,// 当前页码
  });


  const dynamicFormItems = ref([])

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

  // 获取缓存数据设置筛选数据
  const settingData = () => {
    loadDictData().then(() => {
      dynamicFormItems.value = [
        {
          label: '用户ID',
          prop: 'userId',
          type: 'input',
          needEnterEvent: true
        },
        {
          label: '应用ID',
          prop: 'appId',
          type: 'input',
          needEnterEvent: true
        },
        {
          label: '封禁原因',
          prop: 'bannedReason',
          type: 'input',
          needEnterEvent: true
        },
        {
          label: '渠道来源',
          prop: 'channelOrigin',
          type: 'select',
          options: getOptions('channel_origin'),
        },
        { label: '封禁时间', prop: 'bannedTime', type: 'daterange' },
      ]
    })
  }

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

  const changeTableData = (type) => {
    formSearch.value.page = type ? 1 : page.pageNum;
    formSearch.value.limit = page.pageSize;
    // 分页切换
    getList();
};

  // 搜索
  const handleFormSubmitted = (formData) => {
    // console.log("接收到子组件传递的数据", formData.appId);
    formSearch.value.page = page.pageNum;
    formSearch.value.limit = page.pageSize;

    formSearch.value.appId = formData.appId;
    formSearch.value.userId = formData.userId;
    formSearch.value.bannedReason = formData.bannedReason;

    formSearch.value.channelId = formData.channelId;
    formSearch.value.channelOrigin = formData.channelOrigin;
    formSearch.value.channelType = formData.channelType;

    // 封禁时间
    if (formData.bannedTime) {
      formSearch.value.bannedTimeBegin = convertUTCToBeijing(formData.bannedTime[0], false);
      formSearch.value.bannedTimeEnd = convertUTCToBeijing(formData.bannedTime[1], false);
    }else {
      formSearch.value.bannedTimeBegin = null
      formSearch.value.bannedTimeEnd = null
    }


    getList();
  };

  // 表单重置
  const handleFormReset = () => {
    formSearch.value = {
      userId: null,//用户ID
      appId: null,// 应用ID
      bannedReason: null, //封禁原因
      bannedTimeBegin: null, //封禁开始时间
      bannedTimeEnd: null, //封禁结束时间
      channelId: null,// 渠道商ID
      channelOrigin: null, //渠道来源
      channelType: null,//渠道类型

      limit: 20,// 当前页数量(查询量)
      page: 1,// 当前页码
    };
    page.pageNum = 1
    page.pageSize = 20
    page.total = 0

    getList();
  };

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

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

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

  const editUserType = (row) => {
    ruleForm.value?.resetFields()
    layer.value.show = true
    layer.value.title = `解封用户${row.nickName}`
    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.userStatus = 1 //正常
  }

  const ruleForm = ref(null);

  const rules = reactive({
    reason: [
      {
        required: true,
        message: "请输入解封原因",
        trigger: ["blur"],
      },
    ],
  });

  const submit = async (formEl) => {
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        // 提交内容
        riskChangeUserStatus({ ...formEdit.value }).then((res) => {
          ElMessage.success('用户解封成功')
          getList();
        })
      } else {
        console.log("error submit!", fields);
      }
    })
    layer.value.show = false
  }

</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>