<template>
  <div class="app-container">
    <div v-if="buttonPermissions.includes('user:table:query:list')">
      <!-- 搜索栏 -->
      <div class="filter-container">
        <!-- 账号状态 -->
        <el-select
          v-model="listQuery.del"
          style="width: 120px"
          class="filter-item filter-item--status"
          @change="handleSearch"
        >
          <el-option
            :label="$t('pages.userTable.filter.notDeleted')"
            value="0"
          />
          <el-option :label="$t('pages.userTable.filter.deleted')" value="1" />
        </el-select>

        <!-- 系统 -->
        <el-select
          v-model="listQuery.sysOrigins"
          :placeholder="$t('pages.userTable.filter.system')"
          style="width: 200px"
          class="filter-item filter-item--system"
          multiple
          collapse-tags
        >
          <el-option
            v-for="item in permissionsSysOriginPlatforms"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
            <span style="float: left;">
              <sys-origin-icon :icon="item.value" :desc="item.value"
            /></span>
            <span style="float: left;margin-left:10px">{{ item.label }}</span>
          </el-option>
        </el-select>

        <!-- 注册来源 -->
        <el-select
          v-if="showAllCondition"
          v-model="listQuery.authType"
          :placeholder="$t('pages.userTable.filter.registerOrigin')"
          clearable
          style="width: 120px"
          class="filter-item filter-item--register-origin"
          @change="handleSearch"
        >
          <el-option
            v-for="item in registerOrigins"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>

        <!-- 来源平台 -->
        <el-select
          v-if="showAllCondition"
          v-model="listQuery.originPlatform"
          :placeholder="$t('pages.userTable.filter.originPlatform')"
          clearable
          style="width: 120px"
          class="filter-item filter-item--origin-platform"
          @change="handleSearch"
        >
          <el-option
            v-for="item in originPlatforms"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>

        <!-- 性别 -->
        <el-select
          v-if="showAllCondition"
          v-model="listQuery.userSex"
          :placeholder="$t('pages.userTable.filter.gender')"
          clearable
          style="width: 120px"
          class="filter-item filter-item--gender"
          @change="handleUserSexChange"
        >
          <el-option
            v-for="item in genders"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>

        <!-- 国家 -->
        <!-- <el-autocomplete
          v-if="showAllCondition"
          v-model="countryCodeStr"
          popper-class="my-autocomplete"
          :fetch-suggestions="querySearch"
          :placeholder="$t('pages.userTable.filter.country')"
          style="width: 200px"
          class="filter-item filter-item--country"
          clearable
          @clear="handleDelCountryCodeClick"
          @select="handleCountryCodeClick"
        >
          <i
            v-if="!countryCodeStr"
            slot="suffix"
            class="el-icon-edit el-input__icon"
          />
          <template slot-scope="{ item }">
            <div class="name">
              {{ item.phonePrefix + " " + item.countryName }}
            </div>
          </template>
        </el-autocomplete> -->

        <!-- 国家 -->
        <el-select
          v-model="listQuery.countryCode"
          v-loading="loadingCountry"
          :placeholder="$t('pages.userTable.filter.country')"
          style="width: 200px"
          class="filter-item filter-item--user-type"
          clearable
          collapse-tags
          @change="changeCountry"
        >
          <el-option
            v-for="item in countryList"
            :key="item.id"
            :label="item.country.aliasName || item.country.enName"
            :value="item.country.alphaTwo"
          >
            <span style="float: left;">
              <img :src="item.country.nationalFlag" width="30"
            /></span>
            <span style="float: left;margin-left:10px">{{
              item.country.aliasName || item.country.enName
            }}</span>
          </el-option>
        </el-select>

        <!-- 账号类型 -->
        <el-select
          v-if="showAllCondition"
          v-model="listQuery.userType"
          :placeholder="$t('pages.userTable.filter.accountType')"
          clearable
          style="width: 120px"
          class="filter-item"
          @change="handleSearch"
        >
          <el-option
            v-for="item in userTypes"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>

        <!-- 注册时间 -->
        <div class="filter-item filter-item--date">
          <el-date-picker
            v-model="rangeDate"
            value-format="timestamp"
            type="datetimerange"
            :picker-options="pickerOptions"
            :range-separator="$t('pages.userTable.filter.rangeSeparator')"
            :start-placeholder="$t('pages.userTable.filter.registerStartDate')"
            :end-placeholder="$t('pages.userTable.filter.registerEndDate')"
          />
        </div>

        <!-- 长UID -->
        <el-input
          v-model.trim="listQuery.userIds[0]"
          v-number
          :placeholder="$t('pages.userTable.filter.longUid')"
          style="width: 200px;"
          class="filter-item filter-item--long-id"
        />

        <!-- 短账号 -->
        <el-input
          v-model.trim="listQuery.account"
          :placeholder="$t('pages.userTable.filter.shortAccount')"
          style="width: 200px;"
          class="filter-item filter-item--short-id"
        />

        <!-- 设备ID -->
        <el-input
          v-model.trim="listQuery.deviceId"
          :placeholder="$t('pages.userTable.filter.deviceId')"
          style="width: 200px;"
          class="filter-item filter-item--device-id"
        />

        <!-- 搜索按钮 -->
        <el-button
          :loading="searchLoading"
          class="filter-item filter-item--search"
          type="primary"
          icon="el-icon-search"
          @click="handleSearch"
        >
          {{ $t("pages.userTable.filter.search") }}
        </el-button>

        <!-- 是否显示所有条件 -->
        <el-checkbox
          v-model="showAllCondition"
          class="filter-item filter-item--toggle"
          >{{ $t("pages.userTable.filter.showAllConditions") }}</el-checkbox
        >

        <!-- 用户注册情况 -->
        <el-button
          v-if="buttonPermissions.includes('props:config:sales:total')"
          class="filter-item filter-item--overview"
          type="primary"
          icon="el-icon-monitor"
          @click="clickUserRegistrationOverview"
        >
          {{ $t("pages.userTable.filter.registrationOverview") }}
        </el-button>
      </div>

      <!-- 内容列表 -->
      <el-table v-loading="listLoading" :data="list" fit highlight-current-row>
        <!-- 用户基本信息 -->
        <el-table-column
          :label="$t('pages.userTable.table.user')"
          align="center"
          show-overflow-tooltip
          min-width="220"
        >
          <template slot-scope="scope">
            <user-table-exhibit
              :user-profile="scope.row.userProfile"
              :query-details="
                buttonPermissions.includes('user:table:query:details')
              "
            />
          </template>
        </el-table-column>

        <!-- 金币余额 -->
        <el-table-column
          prop="goldBalance"
          :label="$t('pages.userTable.table.goldBalance')"
          align="center"
          min-width="100"
        >
          <template slot-scope="scope">
            <el-link
              v-if="buttonPermissions.includes('user:table:query:gold')"
              @click.native="handleRunningWater(scope.row)"
            >
              <a :title="scope.row.goldBalance">
                {{ scope.row.goldBalance || "0" }}
              </a>
            </el-link>
            <div v-else>
              {{ scope.row.goldBalance }}
            </div>
          </template>
        </el-table-column>

        <!-- 钻石余额 -->
        <el-table-column
          prop="diamondBalance"
          :label="$t('pages.userTable.table.diamondBalance')"
          align="center"
        >
          <template slot-scope="scope">
            <el-link
              v-if="buttonPermissions.includes('user:table:query:gold')"
              @click.native="handleDiamondRunningWater(scope.row)"
            >
              <a :title="scope.row.diamondBalance">
                {{ scope.row.diamondBalance || "0" }}
              </a>
            </el-link>
            <div v-else>
              {{ scope.row.diamondBalance }}
            </div>
          </template>
        </el-table-column>

        <!-- 工资钻石余额 -->
        <el-table-column
          prop="salaryDiamondBalance"
          :label="$t('pages.userTable.table.salaryDiamondBalance')"
          align="center"
        >
          <template slot-scope="scope">
            <el-link
              v-if="buttonPermissions.includes('user:table:query:gold')"
              @click.native="handleDiamondSalaryRunningWater(scope.row)"
            >
              <a :title="scope.row.salaryDiamondBalance">
                {{ scope.row.salaryDiamondBalance || "0" }}
              </a>
            </el-link>
            <div v-else>
              {{ scope.row.salaryDiamondBalance }}
            </div>
          </template>
        </el-table-column>

        <!-- 账号状态 -->
        <el-table-column
          :label="$t('pages.userTable.table.account')"
          align="center"
        >
          <template slot-scope="scope">
            <el-link
              v-if="
                buttonPermissions.includes('user:table:query:account:handler')
              "
              @click.native="accountStatus(scope.row)"
            >
              <a
                :title="scope.row.userProfile.accountStatusName"
                :class="getAccountStatusFontColor(scope.row.userProfile)"
              >
                {{ scope.row.userProfile.accountStatusName }}
              </a>
            </el-link>
            <div
              v-else
              :class="getAccountStatusFontColor(scope.row.userProfile)"
            >
              {{ scope.row.userProfile.accountStatusName }}
            </div>
          </template>
        </el-table-column>

        <!-- 国家 -->
        <!-- <el-table-column label="国家" align="center" width="60">
          <template slot-scope="scope">
            <flag-icon class="flag" :code="scope.row.userProfile.countryCode" :tooltip="scope.row.userProfile.countryName" size="30" />
          </template>
        </el-table-column> -->

        <!-- 注册来源 -->
        <el-table-column
          :label="$t('pages.userTable.table.registerOrigin')"
          align="center"
          width="120"
        >
          <template slot-scope="scope">
            <sys-origin-icon
              :icon="
                scope.row.userProfile.sysOriginChild ||
                  scope.row.userProfile.originSys
              "
              :desc="
                scope.row.userProfile.originSys ||
                  scope.row.userProfile.sysOriginChild
              "
            />
            <platform-svg-icon
              v-if="scope.row.userRegisterInfo"
              :icon="scope.row.userRegisterInfo.originPlatform"
              :desc="
                $t('pages.userTable.row.registerPlatform') +
                  '：' +
                  originText(scope.row)
              "
            />
            <platform-svg-icon
              v-if="scope.row.userRegisterInfo"
              :icon="scope.row.userRegisterInfo.authType"
              :desc="
                $t('pages.userTable.row.registerOrigin') +
                  '：' +
                  scope.row.userRegisterInfo.authType
              "
            />
          </template>
        </el-table-column>

        <!-- 编号 -->
        <el-table-column
          :label="$t('pages.userTable.table.code')"
          align="center"
          show-overflow-tooltip
          min-width="200"
        >
          <template slot-scope="scope">
            <div
              class="cursor-pointer"
              @click="() => copyTextContent(scope.row.userProfile.id)"
            >
              {{ $t("pages.userTable.row.userId") }}：{{
                scope.row.userProfile.id
              }}
            </div>
            <div
              class="cursor-pointer"
              @click="() => copyTextContent(scope.row.userProfile.id)"
            >
              {{ $t("pages.userTable.row.countryId") }}：{{
                scope.row.userProfile.countryId
              }}
            </div>
          </template>
        </el-table-column>

        <!-- 时间 -->
        <el-table-column
          :label="$t('pages.userTable.table.time')"
          align="center"
          show-overflow-tooltip
          min-width="220"
        >
          <template slot-scope="scope">
            <div>
              {{ $t("pages.userTable.row.createTime") }}：{{
                scope.row.userProfile.createTime | dateFormat
              }}
            </div>
            <div>
              {{ $t("pages.userTable.row.recentActive") }}：{{
                scope.row.lastActiveTime | dateFormat
              }}
            </div>
          </template>
        </el-table-column>

        <!-- 操作列表展开按钮 -->
        <el-table-column
          fixed="right"
          :label="$t('pages.userTable.table.actions')"
          align="center"
          width="50"
        >
          <template slot-scope="scope">
            <el-dropdown>
              <span class="el-dropdown-link">
                <i class="el-icon-more" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <!-- 资料详情 -->
                <el-dropdown-item
                  v-if="buttonPermissions.includes('user:table:query:details')"
                  @click.native="queryUserDetails(scope.row)"
                  >{{ $t("pages.userTable.action.detail") }}</el-dropdown-item
                >

                <!-- 编辑用户 -->
                <el-dropdown-item
                  v-if="buttonPermissions.includes('user:table:edit')"
                  @click.native="editUserForm(scope.row)"
                  >{{ $t("pages.userTable.action.editUser") }}</el-dropdown-item
                >

                <!-- 金币收支 -->
                <el-dropdown-item
                  v-if="buttonPermissions.includes('user:table:query:gold')"
                  @click.native="handleRunningWater(scope.row)"
                  >{{ $t("pages.userTable.action.goldFlow") }}</el-dropdown-item
                >

                <!-- 违规记录 -->
                <el-dropdown-item
                  v-if="
                    buttonPermissions.includes('user:table:query:violation')
                  "
                  @click.native="clickViolationTableVisible(scope.row)"
                  >{{
                    $t("pages.userTable.action.violation")
                  }}</el-dropdown-item
                >

                <!-- 账号处理 -->
                <el-dropdown-item
                  v-if="
                    buttonPermissions.includes(
                      'user:table:edit:account:handler'
                    )
                  "
                  @click.native="accountHanle(scope.row)"
                  >{{
                    $t("pages.userTable.action.accountHandle")
                  }}</el-dropdown-item
                >

                <!-- 账号处理记录 -->
                <el-dropdown-item
                  v-if="
                    buttonPermissions.includes(
                      'user:table:query:account:handler'
                    )
                  "
                  @click.native="accountStatus(scope.row)"
                  >{{
                    $t("pages.userTable.action.accountHandleLog")
                  }}</el-dropdown-item
                >

                <!-- 金币奖励 -->
                <el-dropdown-item
                  v-if="
                    buttonPermissions.includes('user:table:edit:reward:gold')
                  "
                  @click.native="editUserGoldCoinRewardForm(scope.row)"
                  >{{
                    $t("pages.userTable.action.goldReward")
                  }}</el-dropdown-item
                >

                <!-- 金币扣除 -->
                <el-dropdown-item
                  v-if="
                    buttonPermissions.includes('user:table:edit:deduction:gold')
                  "
                  @click.native="editUserGoldCoinDeductionForm(scope.row)"
                  >{{
                    $t("pages.userTable.action.goldDeduction")
                  }}</el-dropdown-item
                >

                <!-- 钻石奖励 -->
                <el-dropdown-item
                  v-if="
                    buttonPermissions.includes('user:table:edit:reward:gold')
                  "
                  @click.native="editUserDiamondRewardForm(scope.row)"
                  >{{
                    $t("pages.userTable.action.diamondReward")
                  }}</el-dropdown-item
                >

                <!-- 钻石扣除 -->
                <el-dropdown-item
                  v-if="
                    buttonPermissions.includes('user:table:edit:deduction:gold')
                  "
                  @click.native="editUserDiamondDeductionForm(scope.row)"
                  >{{
                    $t("pages.userTable.action.diamondDeduction")
                  }}</el-dropdown-item
                >

                <!-- 游戏券奖励 -->
                <!-- <el-dropdown-item
                  v-if="
                    buttonPermissions.includes(
                      'user:table:edit:reward:gameCoupon'
                    )
                  "
                  @click.native="editUserGameCouponRewardForm(scope.row)"
                  >游戏券奖励</el-dropdown-item
                > -->

                <!-- 游戏券扣除 -->
                <!-- <el-dropdown-item
                  v-if="
                    buttonPermissions.includes(
                      'user:table:edit:deduction:gameCoupon'
                    )
                  "
                  @click.native="editUserGameCouponDeductionForm(scope.row)"
                  >游戏券扣除</el-dropdown-item
                > -->

                <!-- 添加充值记录 -->
                <el-dropdown-item
                  v-if="
                    buttonPermissions.includes('user:table:add:otherRecharge')
                  "
                  @click.native="addOtherRecharge(scope.row)"
                  >{{
                    $t("pages.userTable.action.addRecharge")
                  }}</el-dropdown-item
                >

                <!-- 线下充值记录 -->
                <el-dropdown-item
                  v-if="
                    buttonPermissions.includes('user:table:query:otherRecharge')
                  "
                  @click.native="addOtherRechargeDialog(scope.row)"
                  >{{
                    $t("pages.userTable.action.offlineRecharge")
                  }}</el-dropdown-item
                >

                <!-- 认证信息 -->
                <el-dropdown-item
                  v-if="buttonPermissions.includes('user:table:auth:info')"
                  @click.native="handleUserAuthForm(scope.row)"
                  >{{ $t("pages.userTable.action.authInfo") }}</el-dropdown-item
                >

                <!-- 银行卡 -->
                <el-dropdown-item
                  v-if="buttonPermissions.includes('user:table:edit:bankCard')"
                  @click.native="handleBankCard(scope.row)"
                  >{{ $t("pages.userTable.action.bankCard") }}</el-dropdown-item
                >

                <!-- 重置密码 -->
                <el-dropdown-item
                  v-if="buttonPermissions.includes('user:table:password:reset')"
                  @click.native="handlePassword(scope.row)"
                  >{{
                    $t("pages.userTable.action.resetPassword")
                  }}</el-dropdown-item
                >

                <!-- IP设备管控 -->
                <el-dropdown-item
                  v-if="buttonPermissions.includes('user:table:password:reset')"
                  @click.native="handleIPDevice(scope.row)"
                  >{{
                    $t("pages.userTable.action.ipDeviceControl")
                  }}</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        :total="total"
        :page.sync="listQuery.pageIndex"
        :limit.sync="listQuery.pageSize"
        layout="total,prev,pager,next,sizes"
        @pagination="renderData"
      />

      <!-- 资料详情组件 -->
      <user-deatils-drawer
        v-if="userDeatilsDrawer"
        :user-id="thatSelectedUserId"
        @close="userDeatilsDrawer = false"
      />

      <!-- 编辑用户组件 -->
      <edit-user-form
        v-if="editUserFormVisible"
        :user-id="thatSelectedUserId"
        @close="editUserFormVisible = false"
        @success="renderDataSuccess"
      />

      <!-- 金币收支组件 -->
      <gold-running-water-dialog
        v-if="candyDialogVisible"
        :user-id="clickUserId"
        @close="candyDialogVisible = false"
      />

      <!-- 违规记录组件 -->
      <user-video-violation-table-dialog
        v-if="violationTableVisible"
        :row="thisRow"
        @close="violationTableVisible = false"
      />

      <!-- 账号处理组件 -->
      <account-hanle
        v-if="accountHandleVisible"
        :user-id="thatSelectedUserId"
        @success="renderDataSuccess"
        @close="accountHandleVisible = false"
      />

      <!-- 账号处理记录组件 -->
      <user-account-status-log-drawer
        v-if="accountStatusLogTable"
        :row="thisRow"
        @close="accountStatusLogTable = false"
      />

      <!-- 金币奖励组件 -->
      <edit-user-gold-coin-reward-form
        v-if="editUserGoldCoinRewardFormVisible"
        :user-id="thatSelectedUserId"
        @close="editUserGoldCoinRewardFormVisible = false"
        @success="renderDataSuccess"
      />

      <!-- 金币扣除组件 -->
      <edit-user-gold-coin-deduction-form
        v-if="editUserGoldCoinDeductionFormVisible"
        :user-id="thatSelectedUserId"
        @close="editUserGoldCoinDeductionFormVisible = false"
        @success="renderDataSuccess"
      />

      <!-- 钻石奖励组件 -->
      <edit-user-diamond-reward-form
        v-if="editUserDiamondRewardFormVisible"
        :user-id="thatSelectedUserId"
        @close="editUserDiamondRewardFormVisible = false"
        @success="renderDataSuccess"
      />

      <!-- 钻石扣除组件 -->
      <edit-user-diamond-deduction-form
        v-if="editUserDiamondDeductionFormVisible"
        :user-id="thatSelectedUserId"
        @close="editUserDiamondDeductionFormVisible = false"
        @success="renderDataSuccess"
      />

      <!-- 游戏券奖励组件 -->
      <edit-user-game-coupon-reward-form
        v-if="editUserGameCouponRewardFormVisible"
        :user-id="thatSelectedUserId"
        @close="editUserGameCouponRewardFormVisible = false"
        @success="renderDataSuccess"
      />

      <!-- 游戏券扣除组件 -->
      <edit-user-game-coupon-deduction-form
        v-if="editUserGameCouponDeductionFormVisible"
        :user-id="thatSelectedUserId"
        @close="editUserGameCouponDeductionFormVisible = false"
        @success="renderDataSuccess"
      />

      <!-- 添加充值记录组件 -->
      <add-other-recharge
        v-if="otherRechargeVisible"
        :user-id="thatSelectedUserId"
        :sys-origin="
          thisRow.userProfile
            ? thisRow.sysOriginChild || thisRow.userProfile.originSys
            : ''
        "
        @close="otherRechargeVisible = false"
        @success="otherRechargeSuccess"
      />

      <!-- 线下充值记录组件 -->
      <add-other-recharge-dialog
        v-if="otherRechargeDialogVisible"
        :user-id="thatSelectedUserId"
        :sys-origin="
          thisRow.userProfile
            ? thisRow.sysOriginChild || thisRow.userProfile.originSys
            : ''
        "
        @close="otherRechargeDialogVisible = false"
      />

      <!-- 认证信息组件 -->
      <user-auth-form
        v-if="userAuthFormVisible"
        :user-id="thatSelectedUserId"
        @close="userAuthFormVisible = false"
      />

      <!-- 银行卡组件 -->
      <bank-card-drawer
        v-if="bankCardVisible"
        :row="thisRow"
        @close="bankCardVisible = false"
      />

      <!-- 钻石余额组件 -->
      <diamond-running-water-dialog
        v-if="diamondDialogVisible"
        :user-id="clickUserId"
        @close="diamondDialogVisible = false"
      />

      <!-- 工资钻石余额组件 -->
      <diamond-salary-running-water-dialog
        v-if="diamondSalaryDialogVisible"
        :user-id="clickUserId"
        @close="diamondSalaryDialogVisible = false"
      />

      <!-- 重置密码确认弹窗 -->
      <el-dialog
        :title="$t('pages.userTable.dialog.resetPasswordTitle')"
        :visible="passwordVisible"
        :modal-append-to-body="true"
        :append-to-body="true"
        width="30%"
        :before-close="
          () => {
            passwordVisible = false;
          }
        "
      >
        <div
          style="width: 100%;display: flex;justify-content: space-around;align-items: center;"
        >
          <el-button type="danger" @click="passwordVisible = false">{{
            $t("pages.userTable.dialog.cancel")
          }}</el-button>
          <el-button type="primary" @click="confirmResetPassword()">{{
            $t("pages.userTable.dialog.confirm")
          }}</el-button>
        </div>
      </el-dialog>

      <!-- 账号处理组件 -->
      <ip-device-handle
        v-if="ipDeviceVisible"
        :user-id="thatSelectedUserId"
        @success="renderDataSuccess"
        @close="ipDeviceVisible = false"
      />
    </div>

    <!-- 用户注册情况弹窗 -->
    <user-registration-overview-charts-dialog
      v-if="UserRegistrationOverviewChartsDialogVisible"
      @close="UserRegistrationOverviewChartsDialogVisible = false"
    />
    <!-- 无权查看用户注册情况弹窗 -->
    <div
      v-else
      v-loading.lock="permissionValidationLoading"
      element-loading-background="#FFFFFF"
      :element-loading-text="$t('pages.userTable.permission.validating')"
      style="text-align: center;"
    >
      {{ $t("pages.userTable.permission.deniedPrefix") }}
      {{ $t("pages.userTable.permission.deniedCode") }}
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { copyText } from "@/utils";
import { genders, userTypes } from "@/constant/user";
import { pickerOptions } from "@/constant/el-const";
import { registerOrigins, originPlatforms } from "@/constant/origin";

import { getUserTable, resetPassword } from "@/api/app-user";
import { getCountryAlls } from "@/api/sys";
import { listPayOpenCountry } from "@/api/sys-pay";

import Pagination from "@/components/Pagination";
import PlatformSvgIcon from "@/components/PlatformSvgIcon";
import GoldRunningWaterDialog from "@/components/data/GoldRunningWaterDialog";
import DiamondRunningWaterDialog from "@/components/data/DiamondRunningWaterDialog";
import DiamondSalaryRunningWaterDialog from "@/components/data/DiamondSalaryRunningWaterDialog";
import AccountHanle from "@/components/data/AccountHanle";
import IpDeviceHandle from "@/components/data/IpDeviceHandle";
import UserVideoViolationTableDialog from "@/components/data/UserVideoViolationTableDialog";
import EditUserForm from "@/components/data/EditUserForm";
import EditUserGoldCoinDeductionForm from "@/components/data/EditUserGoldCoinDeductionForm";
import EditUserGoldCoinRewardForm from "@/components/data/EditUserGoldCoinRewardForm";
import EditUserDiamondDeductionForm from "@/components/data/EditDiamondCoinDeductionForm";
import EditUserDiamondRewardForm from "@/components/data/EditUserDiamondRewardForm";
import EditUserGameCouponRewardForm from "@/components/data/EditUserGameCouponRewardForm";
import EditUserGameCouponDeductionForm from "@/components/data/EditUserGameCouponDeductionForm";
import UserAccountStatusLogDrawer from "@/components/data/UserAccountStatusLogDrawer";
import AddOtherRecharge from "@/components/data/AddOtherRecharge";
import AddOtherRechargeDialog from "@/components/data/AddOtherRechargeDialog";
import UserAuthForm from "@/components/data/UserAuthForm";
import BankCardDrawer from "@/components/data/UserInfo/BankCardDrawer";
import UserRegistrationOverviewChartsDialog from "@/components/data/UserRegistrationOverviewCharts/dialog";

export default {
  name: "AppUserTable",
  components: {
    Pagination,
    GoldRunningWaterDialog,
    DiamondRunningWaterDialog,
    DiamondSalaryRunningWaterDialog,
    PlatformSvgIcon,
    AccountHanle,
    IpDeviceHandle,
    UserVideoViolationTableDialog,
    EditUserForm,
    UserAccountStatusLogDrawer,
    EditUserGoldCoinDeductionForm,
    EditUserGoldCoinRewardForm,
    EditUserDiamondDeductionForm,
    EditUserDiamondRewardForm,
    EditUserGameCouponRewardForm,
    EditUserGameCouponDeductionForm,
    UserRegistrationOverviewChartsDialog,
    AddOtherRecharge,
    AddOtherRechargeDialog,
    UserAuthForm,
    BankCardDrawer
  },
  data() {
    return {
      UserRegistrationOverviewChartsDialogVisible: false,
      otherRechargeDialogVisible: false,
      otherRechargeVisible: false,
      showAllCondition: false,
      permissionValidationLoading: true,
      bankCardVisible: false,
      passwordVisible: false,
      userAuthFormVisible: false,
      pickerOptions,
      thisRow: {},
      countryCodeStr: "",
      level: 0,
      marks: {
        0: "L0",
        1: "L1",
        2: "L2",
        3: {
          style: {
            color: "#1989FA",
            width: "20px"
          },
          label: this.$createElement("strong", "L3")
        }
      },
      levelSubmitLoading: false,
      accountHandleVisible: false,
      accountStatusLogTable: false,
      userDeatilsDrawer: false,
      thatSelectedUserId: "",
      candyDialogVisible: false,
      diamondDialogVisible: false,
      diamondSalaryDialogVisible: false,
      violationTableVisible: false,
      editUserFormVisible: false,
      editUserGoldCoinDeductionFormVisible: false,
      editUserGoldCoinRewardFormVisible: false,
      editUserDiamondRewardFormVisible: false,
      editUserDiamondDeductionFormVisible: false,
      editUserGameCouponRewardFormVisible: false,
      editUserGameCouponDeductionFormVisible: false,
      ipDeviceVisible: false,
      registerOrigins,
      originPlatforms,
      genders,
      userTypes,
      list: [],
      total: 0,
      listQuery: {
        pageIndex: 1,
        pageSize: 20,
        userIds: [],
        countryCode: "",
        authType: "",
        originPlatform: "",
        originPhoneModel: "",
        userSex: "",
        userType: "",
        startTime: "",
        endTime: "",
        startCreateDate: "",
        endCreateDate: "",
        del: "0",
        account: "",
        sysOrigins: [],
        deviceId: ""
      },
      allCountryList: [],
      rangeDate: "",
      listLoading: true,
      hasInitializedSysOrigin: false,
      searchLoading: false,
      clickUserId: "",

      selectedCountry: {}, // 存储完整的国家对象
      countryList: [],
      loadingCountry: false
    };
  },
  computed: {
    ...mapGetters([
      "buttonPermissions",
      "permissionsSysOriginPlatforms",
      "permissionsSysOriginPlatformAlls"
    ])
  },
  watch: {
    rangeDate: {
      immediate: true,
      deep: true,
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.listQuery.startCreateDate = newVal[0];
          this.listQuery.endCreateDate = newVal[1];
          return;
        }
        this.listQuery.startCreateDate = "";
        this.listQuery.endCreateDate = "";
      }
    },
    permissionsSysOriginPlatforms: {
      immediate: true,
      handler(newVal) {
        if (this.hasInitializedSysOrigin || !newVal || newVal.length <= 0) {
          return;
        }
        const querySystem = newVal[0];
        this.hasInitializedSysOrigin = true;
        this.listQuery.sysOrigins = [querySystem.value];
        this.renderData(true);
      }
    }
  },

  created() {
    const that = this;
    // that.loadCountryAlls()
    this.loadOpenCountry();
    setTimeout(() => {
      that.permissionValidationLoading = false;
    }, 3 * 1000);
  },

  methods: {
    renderData(isReset) {
      const that = this;
      if (isReset === true) {
        that.listQuery.pageIndex = 1;
        that.list = [];
      }
      that.listLoading = true;
      that.listQuery.userIds = that.listQuery.userIds.filter(item => item);
      that.listQuery.sysOrigins =
        that.listQuery.sysOrigins && that.listQuery.sysOrigins.length > 0
          ? that.listQuery.sysOrigins
          : that.permissionsSysOriginPlatformAlls.map(item => item.value);
      getUserTable(that.listQuery)
        .then(res => {
          const { body } = res;
          that.total = body.total || 0;
          that.list = body.records || [];
          that.searchLoading = that.listLoading = false;
        })
        .catch(er => {
          that.searchLoading = that.listLoading = false;
        });
    },

    handleSearch() {
      this.searchLoading = true;
      this.renderData(true);
    },

    // querySearch(queryString, cb) {
    //   var restaurants = this.allCountryList;
    //   var results = queryString
    //     ? restaurants.filter(this.createFilter(queryString))
    //     : restaurants;
    //   // 调用 callback 返回建议列表的数据
    //   cb(results);
    // },

    createFilter(queryString) {
      return restaurant => {
        if (
          restaurant.alphaTwo
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        ) {
          return true;
        }
        if (
          restaurant.alphaThree
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        ) {
          return true;
        }
        if (
          restaurant.countryName
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        ) {
          return true;
        }
        if (
          restaurant.aliasName
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        ) {
          return true;
        }
        return (
          String(restaurant.phonePrefix).indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },

    // handleDelCountryCodeClick() {
    //   this.listQuery.countryCode = "";
    //   this.countryCodeStr = "";
    //   this.handleSearch();
    // },

    // handleCountryCodeClick(item) {
    //   this.listQuery.countryCode = item.alphaTwo;
    //   this.countryCodeStr = item.phonePrefix + " " + item.countryName;
    //   this.handleSearch();
    // },

    // loadCountryAlls() {
    //   const that = this;
    //   getCountryAlls()
    //     .then(res => {
    //       that.allCountryList = res.result || {};
    //     })
    //     .catch(er => {});
    // },

    // 获取国家列表
    loadOpenCountry() {
      const that = this;

      that.loadingCountry = true;
      listPayOpenCountry()
        .then(res => {
          that.loadingCountry = false;
          that.countryList = res.body || [];
          that.listQuery.countryCode = "";
          that.selectedCountry = {};
          // that.renderData();
        })
        .catch(er => {
          that.loadingCountry = false;
          console.error(er);
        });
    },

    // 选择国家
    changeCountry(val) {
      const that = this;
      console.log("val", val);

      if (!val) {
        // 如果没有选择国家，清空相关字段
        that.listQuery.countryCode = "";
        that.selectedCountry = {};
      } else {
        // 选择了一个国家
        that.selectedCountry =
          this.countryList.find(item => item.country.alphaTwo === val) || {};

        // 使用传统的方式访问嵌套属性
        that.listQuery.countryCode = that.selectedCountry.country
          ? that.selectedCountry.country.alphaTwo
          : "";
      }

      this.renderData();
    },

    getAccountText(userInfo) {
      if (!userInfo) {
        return "";
      }
      const account = userInfo.account;
      if (userInfo.ownSpecialId && userInfo.ownSpecialId.account) {
        return `${account} / ${userInfo.ownSpecialId.account}${this.$t(
          "pages.userTable.message.specialIdSuffix"
        )}`;
      }
      return account;
    },
    // 资料详情
    queryUserDetails(row) {
      this.thatSelectedUserId = row.id;
      this.userDeatilsDrawer = true;
    },
    handleEidt(row) {},

    // 编辑用户
    editUserForm(item) {
      this.thatSelectedUserId = item.id;
      this.editUserFormVisible = true;
    },

    // 金币扣除
    editUserGoldCoinDeductionForm(item) {
      this.thatSelectedUserId = item.id;
      this.editUserGoldCoinDeductionFormVisible = true;
    },

    // 金币奖励
    editUserGoldCoinRewardForm(item) {
      this.thatSelectedUserId = item.id;
      this.editUserGoldCoinRewardFormVisible = true;
    },

    // IP设备管控
    handleIPDevice(item) {
      this.thatSelectedUserId = item.id;
      this.ipDeviceVisible = true;
    },

    // 钻石扣除
    editUserDiamondDeductionForm(item) {
      this.thatSelectedUserId = item.id;
      this.editUserDiamondDeductionFormVisible = true;
    },

    // 钻石奖励
    editUserDiamondRewardForm(item) {
      this.thatSelectedUserId = item.id;
      this.editUserDiamondRewardFormVisible = true;
    },

    // 游戏券奖励
    editUserGameCouponRewardForm(item) {
      this.thatSelectedUserId = item.id;
      this.editUserGameCouponRewardFormVisible = true;
    },

    // 游戏券扣除
    editUserGameCouponDeductionForm(item) {
      this.thatSelectedUserId = item.id;
      this.editUserGameCouponDeductionFormVisible = true;
    },

    // 银行卡
    handleBankCard(item) {
      this.thisRow = item;
      this.bankCardVisible = true;
    },
    // 打开重置密码弹窗
    handlePassword(item) {
      this.thisRow = item;
      this.passwordVisible = true;
    },

    // 重置密码
    confirmResetPassword() {
      resetPassword({
        userId: this.thisRow.userProfile.id
      })
        .then(res => {
          this.$opsMessage.success();
          this.passwordVisible = false;
        })
        .catch(er => {
          this.$opsMessage.fail();
        });
    },

    // 添加充值记录
    addOtherRecharge(item) {
      this.thisRow = item;
      this.thatSelectedUserId = item.id;
      this.otherRechargeVisible = true;
    },

    // 线下充值记录
    addOtherRechargeDialog(item) {
      this.thisRow = item;
      this.thatSelectedUserId = item.id;
      this.otherRechargeDialogVisible = true;
    },
    otherRechargeSuccess() {
      this.otherRechargeVisible = false;
      this.$opsMessage.success();
    },
    accountHandleSuccess(data) {
      this.$opsMessage.success();
      // this.renderData()
    },

    // 账号处理
    accountHanle(row) {
      this.thatSelectedUserId = row.id;
      this.accountHandleVisible = true;
    },

    // 账号处理记录
    accountStatus(item) {
      this.thisRow = item;
      this.accountStatusLogTable = true;
    },

    // 金币收支
    handleRunningWater(row) {
      this.clickUserId = row.id;
      this.candyDialogVisible = true;
    },

    // 钻石余额
    handleDiamondRunningWater(row) {
      this.clickUserId = row.id;
      this.diamondDialogVisible = true;
    },

    // 工资钻石余额
    handleDiamondSalaryRunningWater(row) {
      this.clickUserId = row.id;
      this.diamondSalaryDialogVisible = true;
    },

    // 认证信息
    handleUserAuthForm(row) {
      this.thatSelectedUserId = row.id;
      this.userAuthFormVisible = true;
    },

    // 违规记录
    clickViolationTableVisible(row) {
      this.thisRow = row;
      this.violationTableVisible = true;
    },
    copyTextContent(text) {
      const that = this;
      copyText(text)
        .then(() => {
          that.$message({
            message: that.$t("pages.userTable.message.copySuccess"),
            type: "success"
          });
        })
        .catch(() => {
          that.$message({
            message: that.$t("pages.userTable.message.copyFail"),
            type: "error"
          });
        });
    },
    originText(row) {
      const texts = [];
      if (!row.userRegisterInfo) {
        return "";
      }
      const userRegisterInfo = row.userRegisterInfo;
      if (userRegisterInfo.originPlatform) {
        texts.push(userRegisterInfo.originPlatform);
      }
      if (userRegisterInfo.originPhoneModel) {
        texts.push(userRegisterInfo.originPhoneModel);
      }
      return texts.join("，");
    },
    renderDataSuccess() {
      this.$message({
        message: "Successful",
        type: "success"
      });
      this.renderData();
    },
    handleMouseEnter(row) {
      this.thisRow = row;
      this.thatSelectedUserId = row.id;
    },
    getLevelName(gender, level) {
      if (gender !== 0) {
        return "-";
      }
      if (level === -1) {
        return "L-1";
      }
      return `L${level}`;
    },
    handleUserSexChange(value) {
      if (value === 0) {
        this.listQuery.maleLevel = "";
        return;
      }
      if (value === 1) {
        this.listQuery.level = "";
        return;
      }
      this.listQuery.maleLevel = "";
      this.listQuery.level = "";
    },
    getAccountStatusFontColor(user) {
      if (!user || !user.actualAccountStatus) {
        return "info";
      }
      if (user.actualAccountStatus === "NORMAL") {
        return "font-success";
      }

      if (user.actualAccountStatus === "FREEZE") {
        return "font-warning";
      }
      return "font-danger";
    },

    // 用户注册情况
    clickUserRegistrationOverview() {
      this.UserRegistrationOverviewChartsDialogVisible = true;
    }
  }
};
</script>
<style scoped lang="scss">
.this-level {
  padding-bottom: 30px;
  display: flex;
  > div {
    width: 150px;
  }
}

.filter-item--system {
  order: 10;
}

.filter-item--country {
  order: 20;
}

.filter-item--long-id {
  order: 30;
}

.filter-item--short-id {
  order: 40;
}

.filter-item--device-id {
  order: 50;
}

.filter-item--status {
  order: 60;
}

.filter-item--user-type {
  order: 70;
}

.filter-item--gender {
  order: 80;
}

.filter-item--register-origin {
  order: 90;
}

.filter-item--origin-platform {
  order: 100;
}

.filter-item--date {
  order: 110;
}

.filter-item--toggle {
  order: 120;
}

.filter-item--search {
  order: 130;
}

.filter-item--overview {
  order: 140;
}
</style>
