<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="ditchName" label="渠道来源" width="150" />
        <el-table-column prop="nickName" label="用户昵称" width="90" />
        <el-table-column prop="userId" label="用户ID" width="160" />
        <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="platformId" label="平台ID" width="150" />
        <el-table-column prop="deblockingReason" label="解禁原因" width="200" />
        <el-table-column prop="deblockingTime" label="解禁时间" width="160">
          <template #default="scope">
            {{ convertUTCToBeijing(scope.row.deblockingTime) }}
          </template>
        </el-table-column>
        <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>


        <!-- <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="edit(scope.row)">
                更改用户状态
              </el-button>
            </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="userStatus">
          <el-select v-model="formEdit.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="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 { riskDeblockingList, riskChangeUserStatus } from '@/api/riskModule.js'
  import { convertUTCToBeijing, camelToSnake } 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({
    appId: null,// 应用ID
    channelOrigin: null,// 渠道来源
    deblockingReason: null,// 解封原因
    deblockingTimeBegin: null,// 解封时间开始
    deblockingTimeEnd: null,// 解封时间结束
    loginTimeBegin: null,// 登录时间开始
    loginTimeEnd: null,// 登录时间截止
    operator: null,// 用户昵称

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


  const dynamicFormItems = ref([])

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

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

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

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

  // 搜索
  const handleFormSubmitted = (formData) => {
    formSearch.value.page = 1;
    formSearch.value.limit = 20;
    formSearch.value.appId = formData.appId;
    formSearch.value.channelId = formData.channelId;
    formSearch.value.channelType = formData.channelType;
    formSearch.value.channelOrigin = formData.channelOrigin;
    formSearch.value.deblockingReason = formData.deblockingReason
    formSearch.value.operator = formData.operator

    // 解封时间
    if (formData.deblockingTime) {
      formSearch.value.deblockingTimeBegin = formData.deblockingTime[0];
      formSearch.value.deblockingTimeEnd = formData.deblockingTime[1];
    }else{
      formSearch.value.deblockingTimeBegin = null
      formSearch.value.deblockingTimeEnd = null
    }

    // 登录时间
    if (formData.loginTime) {
      formSearch.value.loginTimeBegin = formData.loginTime[0];
      formSearch.value.loginTimeEnd = formData.loginTime[1];
    }else {
      formSearch.value.loginTimeBegin = null
      formSearch.value.loginTimeEnd = null
    }

    getList();
  };

  // 表单重置
  const handleFormReset = () => {
    formSearch.value = {
      appId: null,// 应用ID
      channelOrigin: null,// 渠道来源
      deblockingReason: null,// 解封原因
      deblockingTimeBegin: null,// 解封时间开始
      deblockingTimeEnd: null,// 解封时间结束
      loginTimeBegin: null,// 登录时间开始
      loginTimeEnd: null,// 登录时间截止
      operator: null,// 用户昵称

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

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

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

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

  const edit = (row) => {
    ruleForm.value?.resetFields()
    layer.value.show = true

    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({
    userStatus: [
      {
        required: true,
        message: "请选择用户状态",
        trigger: "change",
      },
    ],
    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>