<template>
  <div
    id="user_CustomerList"
    v-loading="pictLoading"
    class="view"
    element-loading-background="rgba(43, 48, 67, 0.65)"
    element-loading-spinner="el-icon-loading"
  >
    <div class="crm_search">
      <el-form ref="formRef" label-position="" :model="search" label-width="">
        <el-row>
          <el-col :span="24" :md="24" :lg="24">
            <el-form-item style="margin-right: 10px">
              <el-select
                v-model="search.roleId"
                clearable
                :placeholder="$t('Label.RoleName')"
                @change="toSearch"
              >
                <el-option
                  v-for="(item, index) in roleName"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="search.tag"
                class="crm_search_down crm-border-radius-no"
                :placeholder="$t('Placeholder.Choose')"
              >
                <el-option :label="$t('Label.Email')" :value="1"></el-option>
                <!--                <el-option :label="$t('Label.Code')" :value="2"></el-option>-->
              </el-select>
            </el-form-item>
            <el-form-item style="margin-right: 10px">
              <el-input
                v-if="search.tag == 1"
                v-model.trim="search.email"
                class="crm-border-left-no crm-border-radius-no"
                :placeholder="$t('Placeholder.Input')"
                @keyup.enter="toSearch"
              ></el-input>
              <!--              <el-input-->
              <!--                v-if="search.tag == 2"-->
              <!--                v-model.trim="search.ibNo"-->
              <!--                class="crm-border-left-no crm-border-radius-no"-->
              <!--                :placeholder="$t('Placeholder.Input')"-->
              <!--                @keyup.enter="toSearch"-->
              <!--              ></el-input>-->
            </el-form-item>
            <el-form-item>
              <el-date-picker
                v-model="search.date"
                class="crm_date_pick crm-border-radius-no"
                type="daterange"
                unlink-panels
                value-format="YYYY-MM-DD"
                range-separator="-"
                :start-placeholder="$t('Placeholder.Start')"
                :end-placeholder="$t('Placeholder.End')"
                @input="getSearchDate"
              >
              </el-date-picker>
              <el-button
                class="crm-border-left-no crm-border-radius-no"
                :icon="Search"
                @click="toSearch"
              ></el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="display['R-UserList-Add'].show">
          <div class="search_action_btn">
            <span class="crm-cursor" @click="addUser">
              <el-icon><Plus /></el-icon>
              <span>{{ $t('Btn.Add') }}</span>
            </span>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="mock_tableData" stripe style="width: 100%">
      <el-table-column prop="" align="left" :label="$t('Label.Name')">
        <template #default="scope">
          {{ scope.row.name || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="" align="left" :label="$t('Label.UserNames')">
        <template #default="scope">
          {{ scope.row.username || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="email" align="left" :label="$t('Label.Email')"> </el-table-column>
      <el-table-column prop="" align="left" :label="$t('Label.RoleName')">
        <template #default="scope">
          {{ scope.row.roleName || '--' }}
        </template>
      </el-table-column>
      <!--      <el-table-column prop="" align="left" :label="$t('Label.Code')">-->
      <!--        <template #default="scope">-->
      <!--          <span>{{ scope.row.ibNo || '&#45;&#45;' }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!-- <el-table-column prop="" align="left" :label="$t('Label.ibNoTemp')">
        <template #default="scope">
          {{ scope.row.ibNoTemp || "--" }}
        </template>
      </el-table-column> -->
      <el-table-column prop="" align="left" :label="$t('Label.Region')">
        <template #default="scope">
          {{
            Session.Get('lang') == 'cn'
              ? scope.row.groupName || '--'
              : scope.row.groupEnName || '--'
          }}
        </template>
      </el-table-column>
      <el-table-column prop="" align="left" :label="$t('Label.Nationality')">
        <template #default="scope">
          {{
            Session.Get('lang') == 'cn'
              ? scope.row.countryName || '--'
              : scope.row.countryEnName || '--'
          }}
        </template>
      </el-table-column>
      <el-table-column prop="" align="left" :label="$t('Area.item1')">
        <template #default="scope">
          {{ scope.row.areaName || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="" align="left" :label="$t('Label.LoginIp')">
        <template #default="scope">
          {{ scope.row.lastIp || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="" align="left" :label="$t('Label.IpLimit')">
        <template #default="scope">
          <span v-if="scope.row.ipLimit == 1" class="">{{ $t('Btn.Yes') }}</span>
          <span v-if="!scope.row.ipLimit" class="">{{ $t('Btn.No') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="" align="left" :label="$t('Label.limitIp')">
        <template #default="scope">
          {{ scope.row.limitIp || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="" align="left" :label="$t('Label.CreationDate')">
        <template #default="scope">
          {{ scope.row.addTime || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="" align="center" width="120" :label="$t('Label.State')">
        <template #default="scope">
          <span v-if="scope.row.valid == 1" class="state crm_state_blue">{{
            $t('State.Normal')
          }}</span>
          <span v-if="scope.row.valid == 0" class="state crm_state_red">{{
            $t('State.Freeze')
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="" align="center" :label="$t('Label.Action')">
        <template #default="scope">
          <el-dropdown trigger="click" @command="handleCommand">
            <span class="el-dropdown-link crm-cursor">
              <i style="font-weight: bold; font-size: 20px" class="iconfont iconcaidan"></i>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-if="display['R-UserList-Update'].show"
                  :command="{ type: 'editor', row: scope.row }"
                >
                  <el-icon><Operation /></el-icon>
                  <span>{{ $t('Btn.Editor') }}</span>
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="display['R-UserList-Delete'].show"
                  :command="{ type: 'delete', id: scope.row.id }"
                >
                  <el-icon><Delete /></el-icon>
                  <span>{{ $t('Btn.Delete') }}</span>
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="display['R-UserList-GroupSettings'].show"
                  :command="{ type: 'group', row: scope.row }"
                >
                  <el-icon><Discount /></el-icon>
                  <span>{{ $t('R-UserList-GroupSettings') }}</span>
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="display['R-UserList-Unseal'].show"
                  :command="{ type: 'Unseal', row: scope.row }"
                >
                  <el-icon><CircleCheck /></el-icon>
                  <span>{{ $t('R-UserList-Unseal') }}</span>
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="display['R-UserList-reSecretKey'].show"
                  :command="{ type: 'reSecretKey', row: scope.row }"
                >
                  <el-icon><Refresh /></el-icon>
                  <span>{{ $t('R-UserList-reSecretKey') }}</span>
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="display['R-UserList-rePassword'].show"
                  :command="{ type: 'rePassword', row: scope.row }"
                >
                  <el-icon><Refresh /></el-icon>
                  <span>{{ $t('R-UserList-rePassword') }}</span>
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="display['R-UserList-closeSecretKey'].show"
                  :command="{ type: 'closeSecretKey', row: scope.row }"
                >
                  <el-icon><Delete /></el-icon>
                  <span>{{ $t('R-UserList-closeSecretKey') }}</span>
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="display['R-UserList-secretKey'].show"
                  :command="{ type: 'secretKey', row: scope.row }"
                >
                  <el-icon><Key /></el-icon><span>{{ $t('R-UserList-secretKey') }}</span>
                </el-dropdown-item>
                <!--                <el-dropdown-item-->
                <!--                  v-if="display['R-Marketing-Extension-Btn'].show"-->
                <!--                  :command="{ type: 'extension', row: scope.row }"-->
                <!--                >-->
                <!--                  <el-icon><Key /></el-icon><span>{{ $t('R-Marketing-Extension-Btn') }}</span>-->
                <!--                </el-dropdown-item>-->
                <!--                <el-dropdown-item-->
                <!--                  v-if="-->
                <!--                    display['R-UserList-AccountSetup'].show || display['R-UserList-Disabled'].show-->
                <!--                  "-->
                <!--                  :command="{ type: 'accountSetup', row: scope.row }"-->
                <!--                >-->
                <!--                  <el-icon><Setting /></el-icon><span>{{ $t('R-UserList-AccountSetup') }}</span>-->
                <!--                </el-dropdown-item>-->
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="pagerInfo.rowTotal" class="crm_pagination">
      <div class="crm_page_total">
        <span>{{ $t('Page.total.item1') }}</span>
        <span>{{ pagerInfo.rowTotal }}</span>
        <span>{{ $t('Page.total.item2') }}</span>
      </div>
      <el-pagination
        class="page"
        background
        layout="sizes, prev, pager, next"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagerInfo.row"
        :total="pagerInfo.rowTotal"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>

    <!-- 开户链接 弹出 -->
    <el-dialog
      v-model="dialogCheck"
      :title="$t('Dashboard.Profile.ConsumerShareLinks')"
      center
      custom-class="dialog_header_w"
    >
      <div class="dia-content">
        <el-form
          ref="dialogCheckFormRef"
          :model="dialogCheck_form"
          label-width="150px"
          class="dialogCheck_form"
        >
          <el-form-item prop="" :label="$t('Label.Name') + '：'">
            {{ dialogCheck_form.name }}
          </el-form-item>
          <el-form-item prop="" :label="$t('Label.UserNames') + '：'">
            {{ dialogCheck_form.username }}
          </el-form-item>
          <el-form-item prop="" :label="$t('Label.Email') + '：'">
            {{ dialogCheck_form.email }}
          </el-form-item>
          <el-form-item
            v-if="dialogCheck_form.departmentId == 1"
            :label="$t('Dashboard.Profile.AgentShareLink')"
          >
            <span
              style="
                display: block;
                width: 100%;
                word-break: break-all;
                line-height: 1.5;
                margin-top: 8px;
              "
              >{{ Host00 + '/#/signup/' + dialogCheck_form.id + '/F0/B0' }} （
              <span>{{ $t('Label.OutsideCommission') }}</span> 0/
              <span>{{ $t('Dashboard.Profile.Allow') }}</span> ）</span
            >
            <span
              style="
                display: block;
                width: 100%;
                word-break: break-all;
                line-height: 1.5;
                margin-top: 8px;
              "
              >{{ Host00 + '/#/signup/' + dialogCheck_form.id + '/F1/B0' }} （
              <span>{{ $t('Label.OutsideCommission') }}</span> 10/
              <span>{{ $t('Dashboard.Profile.Allow') }}</span> ）</span
            >
            <span
              style="
                display: block;
                width: 100%;
                word-break: break-all;
                line-height: 1.5;
                margin-top: 8px;
              "
              >{{ Host00 + '/#/signup/' + dialogCheck_form.id + '/F2/B0' }} （
              <span>{{ $t('Label.OutsideCommission') }}</span> 20/
              <span>{{ $t('Dashboard.Profile.Allow') }}</span> ）</span
            >
            <span
              style="
                display: block;
                width: 100%;
                word-break: break-all;
                line-height: 1.5;
                margin-top: 8px;
              "
              >{{ Host00 + '/#/signup/' + dialogCheck_form.id + '/F0/B1' }} （
              <span>{{ $t('Label.OutsideCommission') }}</span> 0/
              <span>{{ $t('Dashboard.Profile.NotAllow') }}</span> ）</span
            >
            <span
              style="
                display: block;
                width: 100%;
                word-break: break-all;
                line-height: 1.5;
                margin-top: 8px;
              "
              >{{ Host00 + '/#/signup/' + dialogCheck_form.id + '/F1/B1' }} （
              <span>{{ $t('Label.OutsideCommission') }}</span> 10/
              <span>{{ $t('Dashboard.Profile.NotAllow') }}</span> ）</span
            >
            <span
              style="
                display: block;
                width: 100%;
                word-break: break-all;
                line-height: 1.5;
                margin-top: 8px;
              "
              >{{ Host00 + '/#/signup/' + dialogCheck_form.id + '/F2/B1' }} （
              <span>{{ $t('Label.OutsideCommission') }}</span> 20/
              <span>{{ $t('Dashboard.Profile.NotAllow') }}</span> ）</span
            >
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button type="primary" @click="dialogCheck = false">{{ $t('Btn.Confirm') }}</el-button>
          <el-button @click="dialogCheck = false">{{ $t('Btn.Cancel') }}</el-button>
        </div>
      </div>
    </el-dialog>

    <!--组别设置 弹出 -->
    <el-dialog v-model="dialogCheck1" :title="dialogCheckTit" center custom-class="dialog_header_w">
      <div class="dia-content">
        <el-form
          ref="dialogCheckForm1Ref"
          :model="dialogCheck_form1"
          :rules="rules"
          label-width="190px"
          class="dialogCheck_form"
        >
          <el-form-item prop="" :label="$t('Label.UserNames') + '：'">
            {{ dialogCheck_form1.username }}
          </el-form-item>
          <div>
            <el-form-item
              prop="selectLoginTypes"
              :label="$t('news_add_field.Label.SelectAccountType') + '：'"
            >
              <el-select
                v-model="dialogCheck_form1.selectLoginTypes"
                class="crm_search_down"
                multiple
                :placeholder="$t('Placeholder.Choose')"
                @change="selectChange"
              >
                <el-option :label="$t('AccountType.ClassicAccount')" value="1"></el-option>
                <el-option :label="$t('AccountType.SeniorAccount')" value="2"></el-option>
                <el-option :label="$t('AccountType.SpeedAccount')" value="5"></el-option>
                <el-option :label="$t('AccountType.NewSpeedAccount')" value="6"></el-option>
                <el-option :label="$t('AccountType.StandardAccount')" value="7"></el-option>
                <el-option :label="$t('AccountType.CentAccount')" value="8"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              prop="excludeLoginTypes"
              :label="$t('news_add_field.Label.ExclusionAccountType') + '：'"
            >
              <el-select
                v-model="dialogCheck_form1.excludeLoginTypes"
                class="crm_search_down"
                multiple
                :placeholder="$t('Placeholder.Choose')"
                @change="selectChange"
              >
                <el-option :label="$t('AccountType.ClassicAccount')" value="1"></el-option>
                <el-option :label="$t('AccountType.SeniorAccount')" value="2"></el-option>
                <el-option :label="$t('AccountType.SpeedAccount')" value="5"></el-option>
                <el-option :label="$t('AccountType.NewSpeedAccount')" value="6"></el-option>
                <el-option :label="$t('AccountType.StandardAccount')" value="7"></el-option>
                <el-option :label="$t('AccountType.CentAccount')" value="8"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              prop="selectGroupType"
              :label="$t('news_add_field.Label.SelectGroupType') + '：'"
            >
              <el-select
                v-model="dialogCheck_form1.selectGroupType"
                class="crm_search_down"
                clearable
                :placeholder="$t('Placeholder.Choose')"
                @change="selectChange"
              >
                <el-option
                  v-for="item in groupType_options"
                  :key="item.name"
                  :label="Session.Get('lang') == 'cn' ? item.name : item.enName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              prop="defaultGroupType"
              :label="$t('news_add_field.Label.DefaultGroupType') + '：'"
            >
              <el-select
                v-model="dialogCheck_form1.defaultGroupType"
                class="crm_search_down"
                clearable
                :placeholder="$t('Placeholder.Choose')"
                @change="selectChange"
              >
                <el-option
                  v-for="item in groupType_options"
                  :key="item.name"
                  :label="Session.Get('lang') == 'cn' ? item.name : item.enName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form>
        <div class="dialog-footer">
          <el-button type="primary" @click="toVerified()">{{ $t('Btn.Confirm') }}</el-button>
          <el-button @click="cancel">{{ $t('Btn.Cancel') }}</el-button>
        </div>
      </div>
    </el-dialog>

    <!--解封 弹出 -->
    <el-dialog
      v-model="dialogCheckUnseal"
      :title="dialogCheckTit"
      center
      width="400"
      custom-class="dialog_header_w"
    >
      <div class="dia-content">
        <el-form
          ref="dialogCheckFormUnsealRef"
          :model="dialogCheck_formUnseal"
          :rules="rules"
          label-width="160px"
          class="dialogCheck_form"
        >
          <el-form-item prop="" :label="$t('Label.UserNames') + '：'">
            {{ dialogCheck_formUnseal.loginName }}
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="toVerifiedUnseal()">{{ $t('Btn.Confirm') }}</el-button>
          <el-button @click="cancel">{{ $t('Btn.Cancel') }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!--秘钥 弹出 -->
    <el-dialog
      v-model="dialogCheckKey"
      :title="dialogCheckKeyTit"
      center
      width="600"
      custom-class="dialog_header_w"
    >
      <div class="dia-content">
        <el-form
          ref="dialogCheckKeyFormRef"
          :model="dialogCheckKey_form"
          :rules="rules"
          label-width="150px"
          class="dialogCheck_form"
        >
          <template v-if="dialogCheckKey_type != 4">
            <el-form-item prop="" :label="$t('Label.Name') + '：'">
              {{ dialogCheckKey_form.name }}
            </el-form-item>
            <el-form-item prop="" :label="$t('Label.UserNames') + '：'">
              {{ dialogCheckKey_form.username }}
            </el-form-item>
            <div v-if="dialogCheckKey_type == 3" class="googBox">
              <img :src="dialogCheckKey_key.qrUrl" alt="" width="150px" />
              <div class="googleSecretKey">
                <span
                  ><span>{{ $t('getCode.item5') }}</span
                  >:</span
                >
                <input
                  id="ConsumerShareLink1"
                  v-model="dialogCheckKey_key.secretKey"
                  class="link"
                  readonly="readonly"
                />
                <span class="btn-copy" @click="CopyShareLink('ConsumerShareLink1')">{{
                  $t('Dashboard.Profile.Copy')
                }}</span>
              </div>
            </div>
          </template>
          <template v-if="dialogCheckKey_type == 4">
            <el-form-item prop="updateType" :label="$t('Label.Type') + '：'">
              <el-select
                v-model="dialogCheckKey_form.updateType"
                class="crm_search_down"
                clearable
                :placeholder="$t('Placeholder.Choose')"
                @change="selectChange"
              >
                <el-option :label="$t('vaildate.password.updateType1')" :value="1"></el-option>
                <el-option :label="$t('vaildate.password.updateType2')" :value="2"></el-option>
                <el-option :label="$t('vaildate.password.updateType3')" :value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="password" :label="$t('Label.Pwd') + '：'">
              <el-input
                v-model.trim="dialogCheckKey_form.password"
                class="crm_search_down"
                :placeholder="$t('Placeholder.Input')"
              ></el-input>
            </el-form-item>
          </template>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="dialogCheckKey_type == 1" type="primary" @click="toreSecretKey()">{{
            $t('Btn.Confirm')
          }}</el-button>
          <el-button v-if="dialogCheckKey_type == 2" type="primary" @click="tocloseSecretKey()">{{
            $t('Btn.Confirm')
          }}</el-button>
          <el-button v-if="dialogCheckKey_type == 4" type="primary" @click="rePassword()">{{
            $t('Btn.Confirm')
          }}</el-button>
          <el-button
            v-if="dialogCheckKey_type == 3"
            type="primary"
            @click="dialogCheckKey = false"
            >{{ $t('Btn.Confirm') }}</el-button
          >
          <el-button @click="dialogCheckKey = false">{{ $t('Btn.Cancel') }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!--开户设置 弹出 -->
    <el-dialog
      v-model="dialogCheckAccountSetup"
      :title="$t('R-UserList-AccountSetup')"
      center
      custom-class="dialog_header_w"
    >
      <div class="dia-content">
        <el-form
          ref="dialogCheckAccountSetupFormRef"
          :model="dialogCheckAccountSetup_form"
          :rules="rules"
          label-width="190px"
          class="dialogCheck_form"
        >
          <el-form-item prop="" :label="$t('Label.UserNames') + '：'">
            {{ dialogCheckAccountSetup_form.username }}
          </el-form-item>
          <el-form-item
            prop="excludeShowLoginTypes"
            :label="$t('news_add_field.Label.ExclusionAccountType') + '：'"
          >
            <el-select
              v-model="dialogCheckAccountSetup_form.excludeShowLoginTypes"
              class="crm_search_down"
              multiple
              :placeholder="$t('Placeholder.Choose')"
              :disabled="hideAccountSetup ? false : hideDisabled"
              @change="selectChange"
            >
              <el-option :label="$t('AccountType.ClassicAccount')" value="1"></el-option>
              <el-option :label="$t('AccountType.SeniorAccount')" value="2"></el-option>
              <el-option :label="$t('AccountType.SpeedAccount')" value="5"></el-option>
              <el-option :label="$t('AccountType.NewSpeedAccount')" value="6"></el-option>
              <el-option :label="$t('AccountType.StandardAccount')" value="7"></el-option>
              <el-option :label="$t('AccountType.CentAccount')" value="8"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="display['R-UserList-AccountSetup'].show"
            type="primary"
            @click="toVerifiedAccountSetup()"
            >{{ $t('Btn.Confirm') }}</el-button
          >
          <el-button @click="cancelAccountSetup">{{ $t('Btn.Cancel') }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 账户新增/修改弹出 -->
    <UserAdd
      :dialog-info-trading-add="dialogInfoTradingAdd"
      :editor="editor"
      :form-list="formList"
      @confirm-to-reload="confirmToReload"
      @close-add="closeAdd"
    ></UserAdd>
    <div v-if="dialogInfoTradingAdd" class="crm_verified_info_mask" @click="closeDiaAdd"></div>
  </div>
</template>

<script setup>
  import { ref, computed, onMounted, watch, inject } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import Service from '@/service/user'
  import ServiceEnter from '@/service/enter'
  import Config from '@/config/index'
  import UserAdd from './components/UserAdd.vue'
  // import AttributionNumber from '@/views/global/AttributionNumber'
  // import ConsumerShareLink from '@/views/global/ConsumerShareLink.vue'
  import {
    Delete,
    Discount,
    Key,
    Operation,
    Plus,
    Refresh,
    Search,
    Setting,
  } from '@element-plus/icons-vue'
  import { useI18n } from 'vue-i18n'

  const { Code, Host00 } = Config
  const Session = inject('session')
  const { t } = useI18n()

  // Refs
  const formRef = ref(null)
  const dialogCheckFormRef = ref(null)
  const dialogCheckForm1Ref = ref(null)
  const dialogCheckFormUnsealRef = ref(null)
  const dialogCheckKeyFormRef = ref(null)
  const dialogCheckAccountSetupFormRef = ref(null)
  const consumerShareLinkRef = ref(null)

  // State
  const pictLoading = ref(false)
  const mock_tableData = ref([])
  const search = ref({
    tag: 1,
    email: '',
    roleId: '',
    ibNo: '',
    date: [],
    startDate: '',
    endDate: '',
  })
  const dialogInfoNumber = ref(false)
  const formInfoNum = ref({})
  const dialogInfo = ref(false)
  const addType = ref('')
  const formList = ref({})
  const type = ref(1)
  const dialogInfoTradingAdd = ref(false)
  const btn = ref('')
  const editor = ref('')
  const dialogInfoTrading = ref(false)
  const infoType = ref('')
  const formInfo = ref({})
  const roleName = ref([])

  const dialogCheck = ref(false)
  const dialogCheck_form = ref({})

  const dialogCheck1 = ref(false)
  const dialogCheck_form1 = ref({})
  const dialogCheckTit = ref('')

  const dialogCheckUnseal = ref(false)
  const dialogCheck_formUnseal = ref({})

  const groupType_options = ref({})

  const dialogCheckKey = ref(false)
  const dialogCheckKeyTit = ref('')
  const dialogCheckKey_form = ref({
    password: '',
    updateType: 1,
  })
  const dialogCheckKey_type = ref(null)
  const dialogCheckKey_key = ref({})

  const dialogCheckAccountSetup = ref(false)
  const dialogCheckAccountSetup_form = ref({})

  const pagerInfo = ref({ row: 10, current: 1, pageTotal: 0, rowTotal: 0 })
  const flag = ref(false)

  // 验证规则
  const rules = {
    password: [
      {
        validator: (rule, value, callback) => {
          if (Config.Pattern.Password1.test(value) || !value) {
            callback()
          } else {
            callback(new Error(t('vaildate.password.same1')))
          }
        },
        trigger: 'blur',
      },
    ],
    updateType: [
      {
        required: true,
        message: t('vaildate.select.empty'),
        trigger: 'change',
      },
    ],
  }

  // Computed
  const hideDisabled = computed(() => {
    return display.value['R-UserList-Disabled'].show
  })

  const hideAccountSetup = computed(() => {
    return display.value['R-UserList-AccountSetup'].show
  })

  const display = computed(() => {
    return JSON.parse(Session.Get('display', true))
  })

  // Methods
  const parseStringToArray = (value) => {
    if (!value) return []
    if (typeof value === 'string') {
      return value.split(',').filter((item) => item)
    }
    if (Array.isArray(value)) {
      return value
    }
    return []
  }

  const closeDia = () => {
    dialogInfoNumber.value = false
  }

  const close = (val) => {
    dialogInfoNumber.value = val
  }

  const selectChange = () => {
    // force update if needed
  }

  const CopyShareLink = (link) => {
    let linkEle = document.getElementById(link)
    linkEle.value = linkEle.value.split('--')[0]
    linkEle.select()
    document.execCommand('Copy')
    ElMessage.success(t('Dashboard.Profile.CopySuccess'))
  }

  const handleCommand = (command) => {
    if (command.type == 'editor') {
      UserSingle(command.row.id)
      editor.value = 1
    } else if (command.type == 'delete') {
      deleteUser(command.id)
    } else if (command.type == 'group') {
      if (dialogCheckForm1Ref.value) {
        dialogCheckForm1Ref.value.resetFields()
      }
      dialogCheck_form1.value = {}
      dialogCheckTit.value = t('R-UserList-GroupSettings')
      dialogCheck_form1.value.id = command.row.id
      dialogCheck_form1.value.username = command.row.username
      dialogCheck_form1.value.selectLoginTypes = parseStringToArray(command.row.selectLoginTypes)
      dialogCheck_form1.value.excludeLoginTypes = parseStringToArray(command.row.excludeLoginTypes)
      dialogCheck_form1.value.selectGroupType = command.row.selectGroupType
      dialogCheck_form1.value.defaultGroupType = command.row.defaultGroupType
      customGroupType()
    } else if (command.type == 'Unseal') {
      if (dialogCheckFormUnsealRef.value) {
        dialogCheckFormUnsealRef.value.resetFields()
      }

      dialogCheck_formUnseal.value = {}
      dialogCheckTit.value = t('R-UserList-Unseal')
      dialogCheck_formUnseal.value.loginName = command.row.username
      dialogCheckUnseal.value = true
    } else if (
      command.type == 'reSecretKey' ||
      command.type == 'rePassword' ||
      command.type == 'closeSecretKey' ||
      command.type == 'secretKey'
    ) {
      if (dialogCheckKeyFormRef.value) {
        dialogCheckKeyFormRef.value.resetFields()
      }

      dialogCheckKey_form.value = command.row
      if (command.type == 'reSecretKey') {
        dialogCheckKeyTit.value = t('R-UserList-reSecretKey')
        dialogCheckKey_type.value = 1
      } else if (command.type == 'rePassword') {
        dialogCheckKeyTit.value = t('R-UserList-rePassword')
        dialogCheckKey_type.value = 4
      } else if (command.type == 'closeSecretKey') {
        dialogCheckKeyTit.value = t('R-UserList-closeSecretKey')
        dialogCheckKey_type.value = 2
      } else if (command.type == 'secretKey') {
        dialogCheckKeyTit.value = t('R-UserList-secretKey')
        dialogCheckKey_type.value = 3
        togetsecretKey()
      }
      dialogCheckKey.value = true
    } else if (command.type == 'extension') {
      // getLink(command.row)
    } else if (command.type == 'accountSetup') {
      if (dialogCheckAccountSetupFormRef.value) {
        dialogCheckAccountSetupFormRef.value.resetFields()
      }
      dialogCheckAccountSetup_form.value = {}
      dialogCheckAccountSetup_form.value.id = command.row.id
      dialogCheckAccountSetup_form.value.username = command.row.username
      dialogCheckAccountSetup_form.value.excludeShowLoginTypes = parseStringToArray(
        command.row.excludeShowLoginTypes
      )
      dialogCheckAccountSetup.value = true
    }
  }

  const customGroupType = async () => {
    let res = await Service.customGroupTypeList({})
    if (res.code == Code.StatusOK) {
      groupType_options.value = res.data
      dialogCheck1.value = true
    } else {
      ElMessage.error(res.msg)
    }
  }

  const toVerified = async () => {
    dialogCheckForm1Ref.value.validate(async (valid) => {
      if (valid) {
        if (flag.value) {
          return
        } else {
          flag.value = true
        }

        let res = await Service.ibGroup({
          id: dialogCheck_form1.value.id,
          selectLoginTypes: dialogCheck_form1.value.selectLoginTypes || null,
          excludeLoginTypes: dialogCheck_form1.value.excludeLoginTypes || null,
          selectGroupType: dialogCheck_form1.value.selectGroupType || null,
          defaultGroupType: dialogCheck_form1.value.defaultGroupType || null,
        })
        if (res.code == Code.StatusOK) {
          ElMessage.success(t('Msg.ModifySuccess'))
          cancel()
          searchFunc()
          flag.value = false
        } else {
          flag.value = false
          ElMessage.error(res.msg)
        }
      } else {
        return false
      }
    })
  }

  const toVerifiedAccountSetup = async () => {
    dialogCheckAccountSetupFormRef.value.validate(async (valid) => {
      if (valid) {
        if (flag.value) {
          return
        } else {
          flag.value = true
        }

        let res = await Service.userAccountSetup({
          id: dialogCheckAccountSetup_form.value.id,
          excludeShowLoginTypes: dialogCheckAccountSetup_form.value.excludeShowLoginTypes || null,
        })
        if (res.code == Code.StatusOK) {
          ElMessage.success(t('Msg.ModifySuccess'))
          cancelAccountSetup()
          searchFunc()
          flag.value = false
        } else {
          flag.value = false
          ElMessage.error(res.msg)
        }
      } else {
        return false
      }
    })
  }

  const cancelAccountSetup = () => {
    dialogCheckAccountSetup.value = false
    dialogCheckAccountSetupFormRef.value && dialogCheckAccountSetupFormRef.value.resetFields()
  }

  const cancel = () => {
    dialogCheck1.value = false
    dialogCheckForm1Ref.value && dialogCheckForm1Ref.value.resetFields()
    dialogCheckUnseal.value = false
    dialogCheckFormUnsealRef.value && dialogCheckFormUnsealRef.value.resetFields()
    dialogCheckAccountSetup.value = false
    dialogCheckAccountSetupFormRef.value && dialogCheckAccountSetupFormRef.value.resetFields()
  }

  const toVerifiedUnseal = async () => {
    dialogCheckFormUnsealRef.value.validate(async (valid) => {
      if (valid) {
        if (flag.value) {
          return
        } else {
          flag.value = true
        }

        let res = await Service.userUnseal({
          loginName: dialogCheck_formUnseal.value.loginName,
        })
        if (res.code == Code.StatusOK) {
          ElMessage.success(t('Msg.ModifySuccess'))
          cancel()
          searchFunc()
          flag.value = false
        } else {
          flag.value = false
          ElMessage.error(res.msg)
        }
      } else {
        return false
      }
    })
  }

  const toreSecretKey = async () => {
    if (flag.value) {
      return
    } else {
      flag.value = true
    }
    let res = await Service.secretKeyRe({
      id: dialogCheckKey_form.value.id,
    })
    if (res.code == Code.StatusOK) {
      ElMessage.success(t('Msg.ModifySuccess'))
      dialogCheckKey.value = false
      searchFunc()
      flag.value = false
    } else {
      flag.value = false
      ElMessage.error(res.msg)
    }
  }

  const tocloseSecretKey = async () => {
    if (flag.value) {
      return
    } else {
      flag.value = true
    }
    let res = await Service.secretKeyClose({
      id: dialogCheckKey_form.value.id,
    })
    if (res.code == Code.StatusOK) {
      ElMessage.success(t('Msg.ModifySuccess'))
      dialogCheckKey.value = false
      searchFunc()
      flag.value = false
    } else {
      flag.value = false
      ElMessage.error(res.msg)
    }
  }

  const rePassword = async () => {
    dialogCheckKeyFormRef.value.validate(async (valid) => {
      if (valid) {
        if (flag.value) {
          return
        } else {
          flag.value = true
        }
        let res = await Service.rePassword({
          id: dialogCheckKey_form.value.id,
          password: dialogCheckKey_form.value.password,
          updateType: dialogCheckKey_form.value.updateType,
        })
        if (res.code == Code.StatusOK) {
          dialogCheckKey.value = false
          flag.value = false
          ElMessageBox.confirm(`${t('Label.Pwd')}：${res.data}`, t('Msg.SystemPrompt'), {
            confirmButtonText: t('Btn.Confirm'),
            cancelButtonText: t('Btn.Cancel'),
          })
            .then(() => {
              searchFunc()
            })
            .catch(() => {})
        } else {
          ElMessage.error(res.msg)
          flag.value = false
        }
      } else {
        flag.value = false
      }
    })
  }

  const togetsecretKey = async () => {
    dialogCheckKey_key.value = {}
    if (flag.value) {
      return
    } else {
      flag.value = true
    }
    let res = await Service.secretKeyGet({
      id: dialogCheckKey_form.value.id,
    })
    if (res.code == Code.StatusOK) {
      dialogCheckKey_key.value = res.data
      flag.value = false
    } else {
      ElMessage.error(res.msg)
      flag.value = false
    }
  }

  const closeDiaAdd = () => {
    dialogInfoTradingAdd.value = false
    editor.value = ''
  }

  const closeAdd = (val) => {
    dialogInfoTradingAdd.value = val
  }

  const addUser = () => {
    editor.value = ''
    dialogInfoTradingAdd.value = true
  }

  const confirmToReload = () => {
    closeDiaAdd()
    searchFunc()
  }

  const closeDiaTrading = () => {
    dialogInfoTrading.value = false
  }

  const closeTrading = (val) => {
    dialogInfoTrading.value = val
  }

  const openInfo = (val) => {
    dialogInfo.value = val
  }

  const accountOpen = (form) => {
    formInfo.value = form
    dialogInfoTrading.value = true
  }

  const deleteUser = async (id) => {
    ElMessageBox.confirm(t('Msg.Delete'), t('Msg.SystemPrompt'), {
      confirmButtonText: t('Btn.Confirm'),
      cancelButtonText: t('Btn.Cancel'),
    })
      .then(async () => {
        let ids = []
        ids.push(id)
        let res = await Service.userListDelete({ ids: ids })
        if (res.code == Code.StatusOK) {
          ElMessage.success(t('Msg.DeleteSuccess'))
          searchFunc()
        } else {
          ElMessage.error(res.msg)
        }
      })
      .catch(() => {})
  }

  const UserSingle = async (id) => {
    let res = await Service.userSingle({
      id: id,
    })
    if (res.code == Code.StatusOK) {
      formList.value = res.data
      addType.value = 'user_CustomerList'
      dialogInfoTradingAdd.value = true
    } else {
      ElMessage.error(res.msg)
    }
  }

  const getRoleList = async () => {
    let res = await Service.roleNameList({})
    if (res.code == Code.StatusOK) {
      roleName.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
  }

  const searchFunc = async () => {
    pictLoading.value = true
    if (!display.value['R-UserList-Search'].show) {
      ElMessage.warning(t('Msg.NotDisplay'))
      pictLoading.value = false
      return
    }
    if (search.value.date == null) {
      search.value.startDate = ''
      search.value.endDate = ''
    } else if (search.value.date.length == 0) {
      search.value.startDate = ''
      search.value.endDate = ''
    } else {
      search.value.startDate = search.value.date[0]
      search.value.endDate = search.value.date[1]
    }
    let res = await Service.userList({
      ...search.value,
      page: {
        current: pagerInfo.value.current,
        row: pagerInfo.value.row,
      },
    })
    if (res.code == Code.StatusOK) {
      mock_tableData.value = res.data
      if (res.page != null) {
        pagerInfo.value.rowTotal = res.page.rowTotal
        pagerInfo.value.pageTotal = res.page.pageTotal
      } else {
        pagerInfo.value.rowTotal = 0
      }
      ElMessage.success(t('Msg.SearchSuccess'))
      pictLoading.value = false
    } else {
      ElMessage.error(res.msg)
      pictLoading.value = false
    }
  }

  const getSearchDate = (e) => {
    search.value.date = e
  }

  const toSearch = () => {
    pagerInfo.value.current = 1
    searchFunc()
  }

  const handleSizeChange = (val) => {
    pagerInfo.value.row = val
    searchFunc()
  }

  const handleCurrentChange = (val) => {
    pagerInfo.value.current = val
    searchFunc()
  }

  const CopyShareLinks = async (link) => {
    try {
      await navigator.clipboard.writeText(link)
      ElMessage.success(t('Dashboard.Profile.CopySuccess'))
    } catch (err) {
      copyText(link)
    }
  }

  const copyText = (text) => {
    const textarea = document.createElement('textarea')
    textarea.value = text
    document.body.appendChild(textarea)
    textarea.select()
    try {
      document.execCommand('copy')
      ElMessage.success(t('Dashboard.Profile.CopySuccess'))
    } catch (err) {
      // console.log(err)
    }
    document.body.removeChild(textarea)
  }

  // Lifecycle
  onMounted(() => {
    getRoleList()
    searchFunc()
  })

  // Watchers
  watch(
    () => search.value.tag,
    () => {
      search.value.email = ''
      search.value.ibNo = ''
    }
  )
</script>
<style scoped lang="scss">
  @import 'index.scss';
</style>
<style lang="scss">
  #user_CustomerList {
    .dialog_header_w {
      .crm_search_down {
        width: 400px;
      }
    }
  }
</style>
