<template>
  <div class="recharge-record card">
    <div class="search">
      <CustomForm
        :formConfig="queryformConfig"
        v-model="queryFormData"
        :isCustomButton="false"
        :isFlex="false">
        <template slot="btn">
          <el-button type="primary" icon="el-icon-search" @click="search">
            查询
          </el-button>
          <el-button
            type="success"
            icon="el-icon-plus"
            @click="openAddDialog('add')">
            新增
          </el-button>
        </template>
      </CustomForm>
    </div>
    <div class="table_wrap" v-loading="loading">
      <table-vue
        :sourceData="sourceData"
        ref="multipleTable"
        :tableColumns="usersTableColumns"></table-vue>
    </div>
    <div class="pagination">
      <el-pagination
        layout="sizes, total, prev, pager, next, jumper"
        background
        :total="paginationOptions.total"
        :page-size="paginationOptions.pageSize"
        :current-page="paginationOptions.currentPage"
        @size-change="sizeChange"
        @current-change="onCurrentChange"></el-pagination>
    </div>
    <!-- 新增弹窗 -->
    <el-dialog
      :title="operateType"
      :visible.sync="addDialog"
      width="45%"
      :close-on-click-modal="false">
      <el-form
        :model="addFormData"
        :rules="addFormRules"
        ref="addForm"
        label-width="100px"
        :inline="true"
        size="mini">
        <el-form-item label="账户类型" prop="accountType">
          <el-select
            v-model="addFormData.accountType"
            placeholder="请选择账户类型"
            @change="accountTypeChange"
            style="width: 100%">
            <el-option
              v-for="item in accountTypeList"
              :key="item.code"
              :label="item.remark"
              :value="item.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="银行卡开户行"
          prop="openBank"
          v-if="
            addFormData.accountType === 'bank_transfer' ||
            addFormData.accountType === 'xyk'
          ">
          <el-input
            v-model="addFormData.openBank"
            placeholder="请输入开户行"
            clearable />
        </el-form-item>
        <el-form-item label="账户名称" prop="name">
          <el-input
            v-model="addFormData.name"
            placeholder="请输入账户名称"
            clearable />
        </el-form-item>
        <el-form-item label="账号" prop="accountNumber">
          <el-input
            v-model="addFormData.accountNumber"
            placeholder="请输入账号"
            clearable />
        </el-form-item>
        <el-form-item label="收款方式" prop="receiverType">
          <el-select
            v-model="addFormData.receiverType"
            placeholder="请选择收款方式"
            style="width: 100%">
            <el-option
              v-for="item in receiverTypeList"
              :key="item.code"
              :label="item.remark"
              :value="item.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主要业务" prop="operation">
          <el-select
            v-model="addFormData.operation"
            placeholder="请选择主要业务"
            style="width: 100%">
            <el-option
              v-for="item in businessTypeList"
              :key="item.key"
              :label="item.value"
              :value="item.key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="币种" prop="currencyType">
          <el-select
            v-model="addFormData.currencyType"
            placeholder="请选择币种"
            style="width: 100%"
            filterable>
            <el-option
              v-for="item in currencyTypeList"
              :key="item.currencyCode"
              :label="`${item.currencyName}(${item.currencyCode})`"
              :value="item.currencyCode"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="日限额" prop="daySumLimited">
          <el-input-number
            :precision="2"
            :min="0"
            v-model="addFormData.daySumLimited"
            placeholder="请输入日限额"
            type="number" />
        </el-form-item>
        <el-form-item label="月限额" prop="monthlySumLimited">
          <el-input-number
            width="100%"
            :precision="2"
            :min="0"
            v-model="addFormData.monthlySumLimited"
            placeholder="请输入月限额"
            type="number" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="addFormData.sort"
            placeholder="请输入排序"
            :min="1"
            type="number" />
        </el-form-item>
        <!-- <el-form-item label="启用状态" prop="isEnable">
          <el-switch
            class="switchStyle"
            :width="100"
            v-model="addFormData.isEnable"
            active-color="#67C23A"
            inactive-color="#F56C6C"
            @change="dialogEnableChange"
            active-text="启用"
            inactive-text="禁用"></el-switch>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="default" @click="addDialog = false" size="small">
          取消
        </el-button>
        <el-button type="primary" @click="addVarify" size="small">
          下一步
        </el-button>
      </div>
    </el-dialog>
    <!-- 详情弹窗 -->
    <el-dialog title="详情" :visible.sync="detailVisible" width="50%">
      <el-descriptions
        class="margin-top"
        :column="3"
        :labelStyle="{ width: '130px' }"
        :contentStyle="{ width: '200px', textAlign: 'center' }"
        border>
        <el-descriptions-item
          label="账户类型"
          :contentStyle="{ textAlign: 'center' }">
          {{
            accountTypeList.find(
              (i) => i.code === detailFormData.accountType
            ) &&
            accountTypeList.find((i) => i.code === detailFormData.accountType)
              .remark
          }}
        </el-descriptions-item>
        <el-descriptions-item label="银行卡开户行">
          {{ detailFormData.openBank || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="账户名称">
          {{ detailFormData.name }}
        </el-descriptions-item>
        <el-descriptions-item label="账号">
          {{ detailFormData.accountNumber }}
        </el-descriptions-item>
        <el-descriptions-item label="收款方式">
          {{
            receiverTypeList.find(
              (i) => i.code === detailFormData.receiverType
            ) &&
            receiverTypeList.find((i) => i.code === detailFormData.receiverType)
              .remark
          }}
        </el-descriptions-item>

        <el-descriptions-item
          label="币种"
          :contentStyle="{ textAlign: 'center' }">
          {{
            (currencyTypeList.find(
              (i) => i.currencyCode === detailFormData.currencyType
            ) &&
              currencyTypeList.find(
                (i) => i.currencyCode === detailFormData.currencyType
              ).currencyName) +
            '(' +
            detailFormData.currencyType +
            ')'
          }}
        </el-descriptions-item>
        <el-descriptions-item label="主要业务">
          {{
            businessTypeList.find((i) => i.key === detailFormData.operation) &&
            businessTypeList.find((i) => i.key === detailFormData.operation)
              .value
          }}
        </el-descriptions-item>
        <el-descriptions-item label="日限额">
          {{ detailFormData.daySumLimited }}
        </el-descriptions-item>
        <el-descriptions-item label="月限额">
          {{ detailFormData.monthlySumLimited }}
        </el-descriptions-item>

        <el-descriptions-item label="启用状态">
          <el-tag type="success" size="small" v-if="detailFormData.isEnable">
            启用
          </el-tag>
          <el-tag type="danger" size="small" v-else>禁用</el-tag>
        </el-descriptions-item>

        <el-descriptions-item label="排序">
          {{ detailFormData.sort }}
        </el-descriptions-item>
        <el-descriptions-item label="支付宝授权状态">
          <span v-if="detailFormData.accountType === 'alipay'">
            <el-tag
              type="success"
              size="small"
              v-if="detailFormData.appAuthToken">
              已授权
            </el-tag>
            <el-tag type="danger" size="small" v-else>未授权</el-tag>
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ detailFormData.createTime }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ detailFormData.updateTime }}
        </el-descriptions-item>
        <el-descriptions-item />
      </el-descriptions>
    </el-dialog>
    <!-- 日志弹窗 -->
    <el-dialog title="操作日志" :visible.sync="logVisible" width="700px">
      <ul style="color: #333; font-size: 12px; height: 400px; overflow: auto">
        <li
          v-for="(item, index) in logFormData"
          :key="index"
          style="
            margin-bottom: 10px;
            display: flex;
            align-items: flex-start;
            vertical-align: middle;
          ">
          <span class="date">
            {{ item.createTime }}
          </span>
          <span style="flex: 1; vertical-align: middle">
            {{ item.description }}
          </span>
        </li>
      </ul>
    </el-dialog>
    <!-- 安全验证弹窗 -->
    <el-dialog
      ref="securityDialog"
      :title="operateType + '-安全验证'"
      :visible.sync="securityVisible"
      width="400px"
      :close-on-click-modal="false"
      @close="resetSecurityForm"
      class="confirm-dialog">
      <el-form
        :model="securityFormData"
        :rules="securityFormRules"
        ref="securityForm"
        label-width="80px">
        <el-form-item
          v-if="currentMethod === 'phone'"
          label="手机号"
          prop="phone">
          <el-input
            v-model="securityFormData.phone"
            placeholder="请输入手机号"
            :disabled="true"
            clearable
            maxlength="11"
            size="small" />
        </el-form-item>

        <el-form-item
          v-if="currentMethod === 'mailbox'"
          label="邮箱"
          prop="mailbox">
          <el-input
            v-model="securityFormData.mailbox"
            placeholder="请输入邮箱"
            :disabled="true"
            clearable
            size="small" />
        </el-form-item>
        <el-form-item
          v-if="currentMethod !== 'superPassword'"
          label="验证码"
          prop="code">
          <div style="display: flex; align-items: center; gap: 10px">
            <el-input
              v-model="securityFormData.code"
              placeholder="请输入验证码"
              clearable
              maxlength="6"
              size="small" />
            <el-button
              size="small"
              @click="sendVerificationCode"
              :loading="
                countdownConfig[currentMethod] &&
                countdownConfig[currentMethod].loading
              ">
              {{
                countdownConfig[currentMethod] &&
                countdownConfig[currentMethod].loading
                  ? `${countdownConfig[currentMethod].countdown}s后重发`
                  : '发送验证码'
              }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item
          v-if="
            currentMethod === 'superPassword' && securitySetting.superPassword
          "
          :label="'超级密码'"
          prop="superPassword">
          <el-input
            :placeholder="'请输入超级密码'"
            v-model="securityFormData.superPassword"
            clearable
            show-password
            size="small" />
        </el-form-item>
      </el-form>
      <el-divider>其他验证方式</el-divider>
      <div class="check">
        <el-button
          icon="el-icon-mobile-phone"
          type="warning"
          size="small"
          v-if="currentMethod !== 'phone' && securitySetting.phone"
          @click="
            currentMethod = 'phone'
            resetSecurityForm()
          "
          style="width: 100%">
          手机验证
        </el-button>
        <el-button
          icon="el-icon-message"
          type="success"
          size="small"
          v-if="currentMethod !== 'mailbox' && securitySetting.mailbox"
          @click="
            currentMethod = 'mailbox'
            resetSecurityForm()
          "
          style="width: 100%">
          邮箱验证
        </el-button>
        <el-button
          icon="el-icon-lock"
          type="info"
          size="small"
          v-if="
            currentMethod !== 'superPassword' && securitySetting.superPassword
          "
          @click="
            currentMethod = 'superPassword'
            resetSecurityForm()
          "
          style="width: 100%">
          超级密码验证
        </el-button>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="securityVisible = false" size="small">
          取消
        </el-button>
        <el-button type="primary" @click="submit" size="small">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="jsx">
import CustomForm from '@/common/components/base/CustomForm.vue'
import tableVue from '@/common/components/base/tableView.vue'
import {
  getAccountTypeListApi,
  getReceiverTypeListApi,
  getCurrencyTypeListApi,
  getSecuritySettingApi,
  getBaseProceedsAccountListApi,
  getBaseProceedsAccountDetailApi,
  getBaseProceedsAccountLogApi,
  updateBaseProceedsAccountEnableApi,
  addBaseProceedsAccountApi,
  updateBaseProceedsAccountApi,
  deleteBaseProceedsAccountApi,
  sendPhoneCodeApi,
  sendEmailCodeApi,
  getBusinessTypeListApi,
  getAuthLinkApi
} from '@/common/api/user/user.js'

export default {
  name: 'baseProceedsAccount',
  components: {
    tableVue,
    CustomForm
  },
  data() {
    const initialFormData = {
      name: '',
      accountNumber: '',
      accountType: '',
      openBank: '',
      receiverType: '',
      currencyType: '',
      daySumLimited: '',
      monthlySumLimited: '',
      operation: '',
      isEnable: false,
      sort: null
    }
    return {
      select: '',
      sourceData: [],
      queryFormData: {},
      accountTypeList: [],
      receiverTypeList: [],
      currencyTypeList: [],
      businessTypeList: [],
      addDialog: false,
      addFormData: { ...initialFormData }, // 使用初始化的表单数据
      addFormRules: {
        name: [
          { required: true, message: '请输入账户名称', trigger: 'change' }
        ],
        accountNumber: [
          { required: true, message: '请输入账号', trigger: 'change' },
          {
            pattern: /^[^\u4e00-\u9fa5]+$/,
            message: '账号不能包含中文字符',
            trigger: 'change'
          }
        ],
        accountType: [
          { required: true, message: '请选择账户类型', trigger: 'change' }
        ],
        openBank: [
          { required: true, message: '请输入开户行', trigger: 'blur' }
        ],
        receiverType: [
          { required: true, message: '请选择收款方式', trigger: 'change' }
        ],
        currencyType: [
          { required: true, message: '请选择币种', trigger: 'change' }
        ],
        daySumLimited: [
          { required: true, message: '请输入日限额', trigger: 'change' },
          { type: 'number', message: '日限额必须为数字', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value <= 0) {
                callback(new Error('日限额必须大于0'))
              } else if (
                this.addFormData.monthlySumLimited &&
                value >= this.addFormData.monthlySumLimited
              ) {
                callback(new Error('日限额必须小于月限额'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        monthlySumLimited: [
          { required: true, message: '请输入月限额', trigger: 'change' },
          { type: 'number', message: '月限额必须为数字', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value <= 0) {
                callback(new Error('月限额必须大于0'))
              } else if (
                this.addFormData.daySumLimited &&
                value <= this.addFormData.daySumLimited
              ) {
                callback(new Error('月限额必须大于日限额'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        operation: [
          { required: true, message: '请输选择主要业务', trigger: 'change' }
        ],
        isEnable: [
          { required: true, message: '请选择启用状态', trigger: 'change' }
        ],
        sort: [
          {
            pattern: /^[1-9]\d*$/,
            message: '请输入大于0的整数',
            trigger: 'blur'
          }
        ]
      },
      detailVisible: false,
      detailFormData: {},
      logVisible: false,
      logFormData: {},
      formId: null,
      paginationOptions: {
        pageSize: 100,
        currentPage: 1,
        total: 0
      },
      details: [],
      loading: false,
      currentMethod: '',
      type: '',
      currentRow: null,
      securityVisible: false,
      securityFormData: {
        phone: '',
        mailbox: '',
        code: '',
        superPassword: ''
      },
      securitySetting: {},
      securityFormRules: {
        securityCode: [
          { required: true, message: '请输入安全验证码', trigger: 'blur' }
        ]
      },
      countdownConfig: {
        phone: { countdown: 0, loading: false, timer: null },
        mailbox: { countdown: 0, loading: false, timer: null }
      }
    }
  },
  async created() {
    this.getList()
    this.getAccountTypeList()
    this.getReceiverTypeList()
    this.getCurrencyTypeList()
    this.getSecuritySetting()
    this.getBusinessTypeList()
  },
  computed: {
    operateType() {
      switch (this.type) {
        case 'add':
          return '新增收款账户'
        case 'edit':
          return '编辑收款账户'
        case 'changeStatus':
          return this.currentRow
            ? `${this.currentRow.isEnable ? '禁用' : '启用'}付款账户`
            : ''
        case 'delete':
          return `删除${this.currentRow.name}账户`
        default:
          return ''
      }
    },
    usersTableColumns() {
      return [
        {
          label: '启用状态',
          key: 'isEnable',
          width: '110',
          render: (item) => (
            <span>
              <el-switch
                class="switchStyle"
                v-model={item.isEnable}
                active-color="#67C23A"
                inactive-color="#F56C6C"
                active-text="启用"
                inactive-text="禁用"
                onChange={(e) => this.handleStatusChange(item, e)}></el-switch>
            </span>
          )
        },
        {
          label: '账户类型',
          key: 'accountType',
          width: '100',
          render: (item) => {
            const accountType = this.accountTypeList.find((i) => i.code === item.accountType)
            return accountType && accountType.remark
          }
        },
        {
          label: '支付宝授权状态',
          key: 'appAuthToken',
          width: '150',
          render: (item) => {
            if (
              item.accountType !== 'alipay' ||
              item.receiverType === 'belowLine'
            ) {
              return null
            }
            if (item.appAuthToken) {
              return (
                <el-link
                  type="primary"
                  onClick={() => this.handleAuth(item.id)}
                  target="_blank">
                  已授权，重新授权
                </el-link>
              )
            } else {
              return (
                <el-link
                  type="danger"
                  onClick={() => this.handleAuth(item.id)}
                  target="_blank">
                  未授权，点击授权
                </el-link>
              )
            }
          }
        },
        {
          label: '银行卡开户行',
          key: 'openBank',
          width: '200'
        },
        {
          label: '账户名称',
          key: 'name',
          width: '150'
        },
        {
          label: '账号',
          key: 'accountNumber',
          width: ''
        },
        {
          label: '收款方式',
          key: 'receiverType',
          width: '150',
          render: (item) => {
            const receiverType = this.receiverTypeList.find(
              (i) => i.code === item.receiverType
            )
            return receiverType && receiverType.remark
          }
        },
        {
          label: '主要业务',
          key: 'operation',
          width: 200,
          render: (item) => {
            return this.businessTypeList.find((i) => i.key === item.operation)
              .value || ''
          }
        },
        {
          label: '币种',
          key: 'currencyType',
          width: '200',
          render: (item) => {
            const i = this.currencyTypeList.find(
              (i) => i.currencyCode === item.currencyType
            )
            return i ? i.currencyName + '(' + i.currencyCode + ')' : ''
          }
        },
        {
          label: '日限额',
          key: 'daySumLimited',
          width: '150'
        },
        {
          label: '月限额',
          key: 'monthlySumLimited',
          width: '150'
        },

        {
          label: '相关操作',
          key: '',
          fixed: 'right',
          width: '100',
          render: (item) => (
            <div style="display: flex;align-items: center; justify-content: space-around; font-size: 17px">
              <i
                title="详情"
                class="el-icon-chat-line-square"
                onClick={() => this.getDetails(item.id)}
                style="cursor: pointer; color: #67C23A;"></i>
              <i
                title="编辑"
                class="el-icon-edit-outline"
                onClick={() => this.openAddDialog('edit', item)}
                style="cursor: pointer; color: #409EFF"></i>
              <i
                title="查看日志"
                class="el-icon-document"
                onClick={() => this.getLog(item.id)}
                style="cursor: pointer; color: orange"></i>
              <i
                title="删除"
                class="el-icon-delete"
                onClick={() => this.handleDelete(item)}
                style="cursor: pointer; color: #F56C6C"></i>
            </div>
          )
        }
      ]
    },
    queryformConfig() {
      return [
        {
          prop: 'isEnable',
          type: 'select',
          name: '状态',
          options: [
            { label: '启用', value: 1 },
            { label: '禁用', value: 0 }
          ]
        },
        {
          prop: 'accountType',
          type: 'select',
          name: '账户类型',
          options: this.accountTypeList.map((item) => ({
            label: item.remark,
            value: item.code
          }))
        },
        {
          prop: 'name',
          type: 'input',
          name: '账户名称'
        },
        {
          prop: 'receiverType',
          type: 'select',
          name: '收款方式',
          options: this.receiverTypeList.map((item) => ({
            label: item.remark,
            value: item.code
          }))
        },
        {
          prop: 'currencyType',
          type: 'select',
          name: '币种',
          filterable: true,
          options: this.currencyTypeList.map((item) => ({
            label: item.currencyName + '(' + item.currencyCode + ')',
            value: item.currencyCode
          }))
        },
        {
          prop: 'operation',
          type: 'select',
          name: '主要业务',
          options: this.businessTypeList.map((item) => ({
            label: item.value,
            value: item.key
          }))
        }
      ]
    }
  },
  methods: {
    sizeChange(value) {
      this.paginationOptions.pageSize = value
      this.getList()
    },
    onCurrentChange(value) {
      this.paginationOptions.currentPage = value
      this.getList()
    },
    selectionChange(selection) {
      if (selection.length > 0) {
        this.select = selection
      }
    },
    search() {
      if (this.queryFormData.timeRange && this.queryFormData.timeRange.length) {
        this.queryFormData.minSubmitTime = this.queryFormData.timeRange[0]
        this.queryFormData.maxSubmitTime = this.queryFormData.timeRange[1]
      }
      this.getList()
    },
    // 获取账户类型列表
    async getAccountTypeList() {
      try {
        const res = await getAccountTypeListApi()
        this.accountTypeList = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 收款方式
    async getReceiverTypeList() {
      try {
        const res = await getReceiverTypeListApi()
        this.receiverTypeList = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 币种列表
    async getCurrencyTypeList() {
      const res = await getCurrencyTypeListApi()
      this.currencyTypeList = res.data
    },
    // 获取主要业务列表
    async getBusinessTypeList() {
      const res = await getBusinessTypeListApi()
      this.businessTypeList = res.data
    },
    // 获取安全设置信息
    async getSecuritySetting() {
      const res = await getSecuritySettingApi()
      this.securitySetting = res.data
      this.securityFormData.phone = res.data.phone || ''
      this.securityFormData.mailbox = res.data.mailbox || ''
    },
    // 查询
    async getList() {
      try {
        this.loading = true
        const { pageSize, currentPage } = this.paginationOptions
        const res = await getBaseProceedsAccountListApi({
          pageSize,
          currentPage,
          ...this.queryFormData
        })
        this.sourceData = res.data.records
        this.paginationOptions.total = res.data.total
        this.loading = false
      } catch (error) {
        console.log(error)
      }
    },
    // 获取详情
    async getDetails(id) {
      try {
        const res = await getBaseProceedsAccountDetailApi(id)
        this.detailFormData = res.data
        this.detailVisible = true
      } catch (error) {
        console.log(error)
      }
    },
    // 获取日志
    async getLog(id) {
      try {
        const res = await getBaseProceedsAccountLogApi(id)
        this.logFormData = res.data
        this.logVisible = true
      } catch (error) {
        console.log(error)
      }
    },
    // 提交
    submit() {
      switch (this.type) {
        case 'add':
        case 'edit':
          this.addSubmit()
          break
        case 'changeStatus':
          this.submitStatusChange()
          break
        case 'delete':
          this.deleteSubmit()
          break
      }
    },
    // 验证安全验证方式
    setVerificationMethod() {
      this.currentMethod = this.securitySetting.superPassword
        ? 'superPassword'
        : this.securitySetting.phone
        ? 'phone'
        : this.securitySetting.mailbox
        ? 'mailbox'
        : null
      if (!this.currentMethod) {
        this.$confirm('请先至安全管理中心设置安全验证方式', '错误提示', {
          confirmButtonText: '前往设置',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.$router.push('/saas/sysSecuritySettings')
          })
          .catch((err) => {
            console.log(err)
          })
        return false
      }
      return true
    },
    // 启用状态变化
    handleStatusChange(row) {
      const flag = row.isEnable
      row.isEnable = !flag
      this.type = 'changeStatus'
      this.currentRow = row
      if (this.setVerificationMethod()) {
        // 未授权支付宝不可启用账户
        if (
          row.isEnable === false &&
          row.accountType === 'alipay' &&
          row.receiverType === 'onLine' &&
          !row.appAuthToken
        ) {
          this.$message.warning('请先授权支付宝')
          return
        }
        this.securityVisible = true
      }
    },
    // 提交启用状态变化
    async submitStatusChange() {
      try {
        const res = await updateBaseProceedsAccountEnableApi({
          id: this.currentRow.id,
          isEnable: this.currentRow.isEnable ? 0 : 1,
          checkType: this.currentMethod,
          ...this.securityFormData,
          operateType: this.operateType
        })

        if (res.code === 200) {
          this.$message.success(res.message)
          this.securityVisible = false
          this.getList()
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 新增 打开弹窗
    openAddDialog(method, row) {
      if (this.setVerificationMethod()) {
        this.addDialog = true
        this.type = method
        this.currentRow = row
        this.$nextTick(() => {
          method === 'add' ? this.resetForm() : (this.addFormData = { ...row })
        })
      }
    },
    // 新增/编辑 账户类型变化
    accountTypeChange(value) {
      if (this.addFormData.isEnable === true) {
        this.addFormData.accountType = this.currentRow.accountType
        this.$message.warning('请先将账户设置为禁用状态，再修改账户类型')
      }
    },
    // 新增/编辑 启用状态变化
    dialogEnableChange() {
      if (
        this.addFormData.accountType === 'alipay' &&
        (!this.currentRow || !this.currentRow.appAuthToken)
      ) {
        this.addFormData.isEnable = false
        this.$message.warning(`请在${this.operateType}后授权支付宝，再启用账户`)
      }
    },
    // 新增 校验
    addVarify() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.securityVisible = true
        }
      })
    },
    // 新增 提交
    async addSubmit() {
      try {
        const apiMethod =
          this.type === 'add'
            ? addBaseProceedsAccountApi
            : updateBaseProceedsAccountApi
        const res = await apiMethod({
          ...this.addFormData,
          checkType: this.currentMethod,
          ...this.securityFormData,
          operateType: this.operateType
        })
        if (res.code === 200) {
          this.$message.success(this.type === 'add' ? '新增成功' : '编辑成功')
          this.addDialog = false
          this.securityVisible = false
          this.resetForm()
          this.getList()
        }
      } catch (error) {
        console.log(error)
      }
    },

    // 删除 打开弹窗
    async handleDelete(row) {
      this.type = 'delete'
      this.currentMethod = 'superPassword'
      this.currentRow = row
      if (this.setVerificationMethod()) {
        this.securityVisible = true
      }
    },

    // 删除 提交
    async deleteSubmit() {
      try {
        const res = await deleteBaseProceedsAccountApi({
          id: this.currentRow.id,
          checkType: this.currentMethod,
          ...this.securityFormData
        })
        if (res.code === 200) {
          this.$message.success(res.message)
          this.securityVisible = false
          this.getList()
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 新增 重置表单
    resetForm() {
      Object.assign(this.addFormData, {
        name: '',
        accountNumber: '',
        accountType: '',
        openBank: '',
        receiverType: '',
        currencyType: '',
        daySumLimited: '',
        monthlySumLimited: '',
        operation: '',
        sort: '',
        isEnable: false
      })
      this.$nextTick(() => {
        this.$refs.addForm.clearValidate()
      })
    },

    // 安全验证表单重置
    resetSecurityForm() {
      Object.assign(this.securityFormData, {
        code: '',
        superPassword: '',
        phone: this.securitySetting.phone || '',
        mailbox: this.securitySetting.mailbox || ''
      })
      this.$nextTick(() => {
        this.$refs.securityForm.clearValidate()
      })
    },
    // 发送验证码
    async sendVerificationCode() {
      this.$refs.securityForm.validateField(
        this.currentMethod,
        async (error) => {
          if (error) return
          const config = this.countdownConfig[this.currentMethod]
          if (!config) return
          if (config.timer) clearTimeout(config.timer)
          config.loading = true
          config.countdown = 60
          const countdownFn = () => {
            if (config.countdown > 0) {
              config.countdown--
              config.timer = setTimeout(countdownFn, 1000)
            } else {
              config.loading = false
              config.timer = null
            }
          }
          countdownFn()

          let data
          if (this.currentMethod === 'phone') {
            data = await sendPhoneCodeApi({
              phone: this.securityFormData.phone,
              operateType: this.operateType
            })
          } else {
            data = await sendEmailCodeApi(
              this.securityFormData.mailbox,
              this.operateType
            )
          }

          if (data) {
            this.$message.success('验证码发送成功')
          } else {
            config.loading = false
            config.countdown = 0
            if (config.timer) clearTimeout(config.timer)
            config.timer = null
          }
        }
      )
    },
    // 获取授权链接
    async handleAuth(id) {
      const res = await getAuthLinkApi(id)
      if (res.code === 200) {
        window.open(res.message, '_blank')
      }
    }
  }
}
</script>
<style scoped lang="less">
.wraper {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.table_wrap {
  flex: 1;
  padding: 0;
}

.circle {
  display: inline-block;
  height: 10px;
  width: 10px;
  border-radius: 5px;
  margin-right: 5px;
}

.my-table .first {
  background-color: red !important;
  color: #fff !important;
}

.switchStyle {
  ::v-deep {
    .el-switch__label {
      position: absolute;
      display: none;
      color: #fff;
      span {
        font-size: 12px !important;
      }
    }
    .el-switch__core {
      background-color: rgba(166, 166, 166, 1);
      width: 55px !important;
    }
    .el-switch__label--left {
      z-index: 9;
      left: 20px;
    }
    .el-switch__label--right {
      z-index: 9;
      right: 20px;
    }
    .el-switch__label.is-active {
      display: block;
    }
  }
}

.resendMsg {
  background-color: #ff9900;
  &:hover {
    background-color: #ffd36a;
  }
}

.text {
  color: #fff;
  border-radius: 4px;
  padding: 1px 5px;
}

.afootStatus {
  background-color: #409eff;
}

.successStatus {
  background-color: #67c23a;
}

.failStatus {
  background-color: #f56c6c;
}

.recharge-record {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  &::v-deep {
    .el-table .el-table__cell {
      padding: 6px 0;
    }
    .el-input__inner {
      padding: 0 4px;
    }
    .el-input--small .el-input__inner {
      height: 30px;
      line-height: 30px;
    }
    .el-icon-time:before {
      content: '';
    }
    .el-dialog__footer {
      text-align: center;
      .el-button--small {
        padding: 9px 50px;
      }
    }
    .el-dialog__body {
      padding: 10px 20px;
    }
    .el-icon-edit:before {
      color: #ff9800;
      font-weight: bold;
    }
    .el-range-editor--small .el-range-separator {
      line-height: 31px;
    }
    .header-row-class-name th {
      background-color: #f8f8f9;
    }
    .el-input-group__append {
      padding-left: 0;
    }
    .el-input-number--mini {
      width: 100%;
    }
  }
}

.confirm-dialog {
  .el-divider--horizontal {
    margin: 30px auto;
    width: 80%;
    .el-divider__text {
      color: #8b8a8a;
    }
  }
  .dialog-footer {
    margin-top: 10px;
  }
}

.check {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  width: 80%;
  margin: 0 auto;
  .el-button + .el-button {
    margin-left: 0;
  }
}
.date::after {
  content: '中';
  display: inline-block;
  width: 0;
  opacity: 0;
  margin-right: 10px;
}
</style>
