<template>
  <div class="app-container account-page">
    <div class="board">
      <el-form
        v-show="showSearch"
        ref="queryForm"
        :model="queryParams"
        size="small"
        class="query-form"
        label-width="96px"
      >
        <el-row :gutter="16">
          <el-col :span="6">
            <el-form-item label="所属人类型">
              <el-select v-model="queryParams.ownerType" placeholder="请选择所属人类型" clearable style="width: 100%">
                <el-option label="员工" value="EMPLOYEE" />
                <el-option label="员工关系人" value="RELATION" />
                <el-option label="中介" value="INTERMEDIARY" />
                <el-option label="外部人员" value="EXTERNAL" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="员工姓名">
              <el-input v-model="queryParams.staffName" placeholder="请输入员工姓名" clearable style="width: 100%" @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="账户范围">
              <el-select v-model="queryParams.bankScope" placeholder="请选择账户范围" clearable style="width: 100%">
                <el-option label="行内" value="INTERNAL" />
                <el-option label="行外" value="EXTERNAL" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关系类型">
              <el-select v-model="queryParams.relationType" placeholder="请选择关系类型" clearable style="width: 100%">
                <el-option v-for="item in relationTypeOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="账户姓名">
              <el-input v-model="queryParams.accountName" placeholder="请输入账户姓名" clearable style="width: 100%" @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="账户类型">
              <el-select v-model="queryParams.accountType" placeholder="请选择账户类型" clearable style="width: 100%">
                <el-option label="银行账户" value="BANK" />
                <el-option label="证券账户" value="SECURITIES" />
                <el-option label="支付账户" value="PAYMENT" />
                <el-option label="其他" value="OTHER" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否实控">
              <el-select v-model="queryParams.isActualControl" placeholder="请选择是否实控" clearable style="width: 100%">
                <el-option label="是" :value="1" />
                <el-option label="否" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="风险等级">
              <el-select v-model="queryParams.riskLevel" placeholder="请选择风险等级" clearable style="width: 100%">
                <el-option label="LOW" value="LOW" />
                <el-option label="MEDIUM" value="MEDIUM" />
                <el-option label="HIGH" value="HIGH" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 100%">
                <el-option label="正常" :value="1" />
                <el-option label="已销户" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="openCreateDialog"
            v-hasPermi="['ccdi:accountInfo:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            v-hasPermi="['ccdi:accountInfo:import']"
          >导入</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
      </el-row>

      <el-table v-loading="loading" :data="rows" stripe border class="account-table">
        <el-table-column label="员工姓名" prop="staffName" min-width="120">
          <template slot-scope="scope">{{ scope.row.staffName || '-' }}</template>
        </el-table-column>
        <el-table-column label="所属人类型" prop="ownerType" width="132" align="center">
          <template slot-scope="scope">
            <el-tag :type="ownerTypeTagType(scope.row.ownerType)" size="mini" effect="plain">
              {{ ownerTypeLabel(scope.row.ownerType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="关系类型" prop="relationType" width="90" align="center">
          <template slot-scope="scope">{{ scope.row.relationType || '-' }}</template>
        </el-table-column>
        <el-table-column label="证件号" prop="ownerId" min-width="170" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.ownerId || scope.row.relationCertNo || '-' }}</template>
        </el-table-column>
        <el-table-column label="账户姓名" prop="accountName" min-width="120">
          <template slot-scope="scope">{{ scope.row.accountName || '-' }}</template>
        </el-table-column>
        <el-table-column label="账户号码" prop="accountNo" min-width="180" />
        <el-table-column label="账户类型" prop="accountType" width="110" align="center">
          <template slot-scope="scope">{{ accountTypeLabel(scope.row.accountType) }}</template>
        </el-table-column>
        <el-table-column label="账户范围" prop="bankScope" width="96" align="center">
          <template slot-scope="scope">
            <el-tag size="mini" :type="bankScopeTagType(scope.row.bankScope)" effect="plain">{{ bankScopeLabel(scope.row.bankScope) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="开户机构" prop="openBank" min-width="160" show-overflow-tooltip />
        <el-table-column label="是否实控" prop="isActualControl" width="92" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.isActualControl === null || scope.row.isActualControl === undefined">-</span>
            <el-tag v-else size="mini" :type="scope.row.isActualControl ? 'success' : 'danger'">
              {{ scope.row.isActualControl ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="月均笔数" prop="avgMonthTxnCount" width="90" align="center">
          <template slot-scope="scope">{{ scope.row.avgMonthTxnCount === null || scope.row.avgMonthTxnCount === undefined ? '-' : scope.row.avgMonthTxnCount }}</template>
        </el-table-column>
        <el-table-column label="月均金额" prop="avgMonthTxnAmount" min-width="120" align="right">
          <template slot-scope="scope">{{ formatAmount(scope.row.avgMonthTxnAmount) }}</template>
        </el-table-column>
        <el-table-column label="频率等级" prop="txnFrequencyLevel" width="96" align="center">
          <template slot-scope="scope">
            <span v-if="!scope.row.txnFrequencyLevel">-</span>
            <el-tag v-else size="mini" :type="frequencyTagType(scope.row.txnFrequencyLevel)">{{ scope.row.txnFrequencyLevel }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="风险等级" prop="txnRiskLevel" width="96" align="center">
          <template slot-scope="scope">
            <span v-if="!scope.row.txnRiskLevel">-</span>
            <el-tag v-else size="mini" effect="dark" :type="riskTagType(scope.row.txnRiskLevel)">{{ scope.row.txnRiskLevel }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="80" align="center">
          <template slot-scope="scope">
            <el-tag size="mini" :type="scope.row.status === 1 ? 'success' : 'danger'">{{ scope.row.status === 1 ? '正常' : '已销户' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" size="mini" icon="el-icon-view" @click="openDetailDialog(scope.row)">详情</el-button>
            <el-button
              type="text"
              size="mini"
              icon="el-icon-edit"
              @click="openEditDialog(scope.row)"
              v-hasPermi="['ccdi:accountInfo:edit']"
            >编辑</el-button>
            <el-button
              type="text"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['ccdi:accountInfo:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </div>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="1160px" append-to-body>
      <el-form ref="dialogForm" :model="form" :rules="rules" label-width="120px">
        <div class="form-section">
          <div class="section-head"><span>归属信息</span></div>
          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="所属人类型" prop="ownerType">
                <el-radio-group v-model="form.ownerType" :disabled="dialogMode === 'detail'" @change="handleOwnerTypeChange">
                  <el-radio label="EMPLOYEE">员工</el-radio>
                  <el-radio label="RELATION">员工关系人</el-radio>
                  <el-radio label="INTERMEDIARY">中介</el-radio>
                  <el-radio label="EXTERNAL">外部人员</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item v-if="isInternalOwner" label="员工姓名" prop="staffId">
                <el-select v-model="form.staffId" placeholder="请选择员工" filterable clearable style="width: 100%" :disabled="dialogMode === 'detail'" @change="handleStaffChange">
                  <el-option v-for="item in staffOptions" :key="item.staffId" :label="item.name" :value="item.staffId" />
                </el-select>
              </el-form-item>
              <el-form-item v-else :label="manualOwnerNameLabel" prop="accountName">
                <el-input v-model="form.accountName" :placeholder="manualOwnerNamePlaceholder" :disabled="dialogMode === 'detail'" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否本人账户">
                <el-input :value="form.ownerType === 'EMPLOYEE' ? '是' : '否'" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="16" v-if="form.ownerType === 'RELATION'">
            <el-col :span="8">
              <el-form-item label="关系人姓名" prop="relationId">
                <el-select v-model="form.relationId" placeholder="请选择关系人" clearable style="width: 100%" :disabled="dialogMode === 'detail'" @change="fillRelationMeta">
                  <el-option v-for="item in relationOptions" :key="item.id" :label="item.relationName" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关系类型">
                <el-input v-model="form.relationType" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关系人证件号">
                <el-input v-model="form.relationCertNo" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="证件号" prop="ownerId">
                <el-input
                  v-if="!isRelationOwner"
                  v-model="form.ownerId"
                  :placeholder="ownerIdPlaceholder"
                  :disabled="dialogMode === 'detail' || isEmployeeOwner"
                />
                <el-input v-else :value="form.relationCertNo" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section">
          <div class="section-head"><span>账户信息</span></div>
          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="账户号码" prop="accountNo">
                <el-input v-model="form.accountNo" :disabled="dialogMode === 'detail'" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="账户类型" prop="accountType">
                <el-select v-model="form.accountType" style="width: 100%" :disabled="dialogMode === 'detail'">
                  <el-option label="银行账户" value="BANK" />
                  <el-option label="证券账户" value="SECURITIES" />
                  <el-option label="支付账户" value="PAYMENT" />
                  <el-option label="其他" value="OTHER" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="账户范围" prop="bankScope">
                <el-select v-model="form.bankScope" style="width: 100%" :disabled="dialogMode === 'detail'">
                  <el-option label="行内" value="INTERNAL" />
                  <el-option label="行外" value="EXTERNAL" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="账户姓名" prop="accountName" v-if="isInternalOwner">
                <el-input v-model="form.accountName" :disabled="dialogMode === 'detail'" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户机构" prop="openBank">
                <el-input v-model="form.openBank" :disabled="dialogMode === 'detail'" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="银行代码">
                <el-input v-model="form.bankCode" :disabled="dialogMode === 'detail'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="币种">
                <el-input v-model="form.currency" :disabled="dialogMode === 'detail'" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="状态" prop="status">
                <el-select v-model="form.status" style="width: 100%" :disabled="dialogMode === 'detail'">
                  <el-option label="正常" :value="1" />
                  <el-option label="已销户" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="生效日期" prop="effectiveDate">
                <el-date-picker v-model="form.effectiveDate" type="date" value-format="yyyy-MM-dd" style="width: 100%" :disabled="dialogMode === 'detail'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="失效日期" prop="invalidDate">
                <el-date-picker v-model="form.invalidDate" type="date" value-format="yyyy-MM-dd" style="width: 100%" :disabled="dialogMode === 'detail'" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section accent-section">
          <div class="section-head"><span>分析信息</span></div>
          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="是否实控账户">
                <el-select v-model="form.isActualControl" style="width: 100%" :disabled="analysisReadonly">
                  <el-option label="是" :value="1" />
                  <el-option label="否" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="月均交易笔数">
                <el-input-number v-model="form.avgMonthTxnCount" :min="0" :disabled="analysisReadonly" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="月均交易金额">
                <el-input-number v-model="form.avgMonthTxnAmount" :min="0" :precision="2" :disabled="analysisReadonly" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="16">
            <el-col :span="6">
              <el-form-item label="频率等级">
                <el-select v-model="form.txnFrequencyLevel" style="width: 100%" :disabled="analysisReadonly">
                  <el-option label="LOW" value="LOW" />
                  <el-option label="MEDIUM" value="MEDIUM" />
                  <el-option label="HIGH" value="HIGH" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="风险等级">
                <el-select v-model="form.txnRiskLevel" style="width: 100%" :disabled="riskLevelReadonly">
                  <el-option label="LOW" value="LOW" />
                  <el-option label="MEDIUM" value="MEDIUM" />
                  <el-option label="HIGH" value="HIGH" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="16">
            <el-col :span="6">
              <el-form-item label="借方单笔最高额">
                <el-input-number v-model="form.debitSingleMaxAmount" :min="0" :precision="2" :disabled="analysisReadonly" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="贷方单笔最高额">
                <el-input-number v-model="form.creditSingleMaxAmount" :min="0" :precision="2" :disabled="analysisReadonly" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="借方日累计最高额">
                <el-input-number v-model="form.debitDailyMaxAmount" :min="0" :precision="2" :disabled="analysisReadonly" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="贷方日累计最高额">
                <el-input-number v-model="form.creditDailyMaxAmount" :min="0" :precision="2" :disabled="analysisReadonly" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{ dialogMode === 'detail' ? '关 闭' : '取 消' }}</el-button>
        <el-button v-if="dialogMode !== 'detail'" type="primary" @click="submitForm">保 存</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
      @close="handleImportDialogClose"
      v-loading="upload.isUploading"
      element-loading-text="正在导入数据,请稍候..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.7)"
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx,.xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
        <div slot="tip" class="el-upload__tip">
          <span>仅允许导入 xls、xlsx 文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" :loading="upload.isUploading">确 定</el-button>
        <el-button @click="upload.open = false" :disabled="upload.isUploading">取 消</el-button>
      </div>
    </el-dialog>

    <import-result-dialog
      :visible.sync="importResultVisible"
      :content="importResultContent"
      title="导入结果"
      @close="handleImportResultClose"
    />
  </div>
</template>

<script>
import ImportResultDialog from '@/components/ImportResultDialog.vue'
import { getToken } from '@/utils/auth'
import {
  addAccountInfo,
  delAccountInfo,
  getAccountInfo,
  listAccountInfo,
  listAccountRelationOptions,
  listAccountStaffOptions,
  updateAccountInfo
} from '@/api/ccdiAccountInfo'

const RELATION_TYPES = ['配偶', '父亲', '母亲', '子女', '兄弟姐妹', '朋友', '同事', '其他']

function createEmptyForm() {
  return {
    id: null,
    ownerType: 'EMPLOYEE',
    ownerId: '',
    staffId: undefined,
    relationId: undefined,
    relationType: '',
    relationName: '',
    relationCertNo: '',
    accountNo: '',
    accountType: 'BANK',
    bankScope: 'EXTERNAL',
    accountName: '',
    openBank: '',
    bankCode: '',
    currency: 'CNY',
    status: 1,
    effectiveDate: '',
    invalidDate: '',
    isActualControl: 1,
    avgMonthTxnCount: 0,
    avgMonthTxnAmount: 0,
    txnFrequencyLevel: 'MEDIUM',
    debitSingleMaxAmount: 0,
    creditSingleMaxAmount: 0,
    debitDailyMaxAmount: 0,
    creditDailyMaxAmount: 0,
    txnRiskLevel: 'LOW'
  }
}

function applyIntermediaryRiskLevel(form) {
  if (form.ownerType === 'INTERMEDIARY') {
    form.txnRiskLevel = 'HIGH'
  }
}

export default {
  name: 'CcdiAccountInfo',
  components: { ImportResultDialog },
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      rows: [],
      dialogVisible: false,
      dialogMode: 'create',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        staffName: '',
        ownerType: '',
        bankScope: '',
        relationType: '',
        accountName: '',
        accountType: '',
        isActualControl: undefined,
        riskLevel: '',
        status: undefined
      },
      form: createEmptyForm(),
      staffOptions: [],
      relationOptions: [],
      relationTypeOptions: RELATION_TYPES,
      upload: {
        open: false,
        title: '导入账户数据',
        isUploading: false,
        headers: { Authorization: 'Bearer ' + getToken() },
        url: process.env.VUE_APP_BASE_API + '/ccdi/accountInfo/importData'
      },
      importResultVisible: false,
      importResultContent: '',
      rules: {
        ownerType: [{ required: true, message: '请选择所属人类型', trigger: 'change' }],
        staffId: [{ validator: (rule, value, callback) => {
          if (this.isInternalOwner && !value) {
            callback(new Error('请选择员工'))
            return
          }
          callback()
        }, trigger: 'change' }],
        relationId: [{ validator: (rule, value, callback) => {
          if (this.form.ownerType === 'RELATION' && !value) {
            callback(new Error('请选择关系人'))
            return
          }
          callback()
        }, trigger: 'change' }],
        ownerId: [{ validator: (rule, value, callback) => {
          if (!this.isInternalOwner && !value) {
            callback(new Error('请输入证件号'))
            return
          }
          callback()
        }, trigger: 'blur' }],
        accountNo: [{ required: true, message: '请输入账户号码', trigger: 'blur' }],
        accountType: [{ required: true, message: '请选择账户类型', trigger: 'change' }],
        bankScope: [{ required: true, message: '请选择账户范围', trigger: 'change' }],
        accountName: [{ required: true, message: '请输入账户姓名', trigger: 'blur' }],
        openBank: [{ required: true, message: '请输入开户机构', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        effectiveDate: [{ required: true, message: '请选择生效日期', trigger: 'change' }],
        invalidDate: [{ validator: (rule, value, callback) => {
          if (value && this.form.effectiveDate && value < this.form.effectiveDate) {
            callback(new Error('失效日期不能早于生效日期'))
            return
          }
          callback()
        }, trigger: 'change' }]
      }
    }
  },
  computed: {
    isEmployeeOwner() {
      return this.form.ownerType === 'EMPLOYEE'
    },
    isRelationOwner() {
      return this.form.ownerType === 'RELATION'
    },
    isIntermediaryOwner() {
      return this.form.ownerType === 'INTERMEDIARY'
    },
    isInternalOwner() {
      return this.isEmployeeOwner || this.isRelationOwner
    },
    manualOwnerNameLabel() {
      return this.form.ownerType === 'INTERMEDIARY' ? '中介名称' : '外部人员姓名'
    },
    manualOwnerNamePlaceholder() {
      return this.form.ownerType === 'INTERMEDIARY' ? '请输入中介名称' : '请输入外部人员姓名'
    },
    ownerIdPlaceholder() {
      return this.form.ownerType === 'INTERMEDIARY' ? '请输入中介证件号' : '请输入身份证号'
    },
    analysisReadonly() {
      return this.dialogMode === 'detail' || this.form.bankScope === 'INTERNAL'
    },
    riskLevelReadonly() {
      return this.analysisReadonly || this.isIntermediaryOwner
    },
    dialogTitle() {
      if (this.dialogMode === 'detail') return '账户详情'
      if (this.dialogMode === 'edit') return '编辑账户'
      return '新增账户'
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listAccountInfo(this.queryParams).then(response => {
        this.rows = response.rows || []
        this.total = response.total || 0
      }).finally(() => {
        this.loading = false
      })
    },
    async loadStaffOptions(query = '') {
      const response = await listAccountStaffOptions(query)
      this.staffOptions = response.data || []
    },
    async loadRelationOptions(staffId) {
      if (!staffId) {
        this.relationOptions = []
        return
      }
      const response = await listAccountRelationOptions(staffId)
      this.relationOptions = response.data || []
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        staffName: '',
        ownerType: '',
        bankScope: '',
        relationType: '',
        accountName: '',
        accountType: '',
        isActualControl: undefined,
        riskLevel: '',
        status: undefined
      }
      this.resetForm('queryForm')
      this.getList()
    },
    handleImport() {
      this.upload.open = true
    },
    importTemplate() {
      this.download('ccdi/accountInfo/importTemplate', {}, `账户库导入模板_${new Date().getTime()}.xlsx`)
    },
    handleFileUploadProgress() {
      this.upload.isUploading = true
    },
    handleFileSuccess(response) {
      this.upload.isUploading = false
      this.upload.open = false
      this.$refs.upload.clearFiles()
      if (response.code !== 200) {
        this.$modal.msgError(response.msg || '导入失败')
        return
      }
      const importData = response.data || {}
      this.importResultContent = this.buildImportResultHtml(importData)
      this.importResultVisible = true
      this.getList()
    },
    buildImportResultHtml(importData) {
      const totalCount = importData.totalCount || 0
      const successCount = importData.successCount || 0
      const failureCount = importData.failureCount || 0
      let html = '<div style="padding: 10px;">'
      html += `<p><strong>导入完成</strong></p><p>总数：${totalCount} 条</p><p>成功：${successCount} 条</p><p>失败：${failureCount} 条</p>`
      html += '</div>'
      return html
    },
    submitFileForm() {
      this.$refs.upload.submit()
    },
    handleImportDialogClose() {
      this.upload.isUploading = false
      this.$refs.upload && this.$refs.upload.clearFiles()
    },
    handleImportResultClose() {
      this.importResultVisible = false
      this.importResultContent = ''
    },
    formatAmount(value) {
      if (value === null || value === undefined || value === '') return '-'
      return Number(value).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
    },
    accountTypeLabel(type) {
      return { BANK: '银行账户', SECURITIES: '证券账户', PAYMENT: '支付账户', OTHER: '其他' }[type] || type
    },
    bankScopeLabel(scope) {
      return { INTERNAL: '行内', EXTERNAL: '行外' }[scope] || scope
    },
    bankScopeTagType(scope) {
      return scope === 'INTERNAL' ? 'success' : 'warning'
    },
    ownerTypeLabel(type) {
      return { EMPLOYEE: '员工', RELATION: '员工关系人', INTERMEDIARY: '中介', EXTERNAL: '外部人员' }[type] || type
    },
    ownerTypeTagType(type) {
      return { EMPLOYEE: 'success', RELATION: 'info', INTERMEDIARY: 'danger', EXTERNAL: 'warning' }[type] || 'info'
    },
    riskTagType(level) {
      return { LOW: 'success', MEDIUM: 'warning', HIGH: 'danger' }[level] || 'info'
    },
    frequencyTagType(level) {
      return { LOW: 'info', MEDIUM: '', HIGH: 'danger' }[level] || 'info'
    },
    async openCreateDialog() {
      this.dialogMode = 'create'
      this.form = createEmptyForm()
      this.relationOptions = []
      await this.loadStaffOptions()
      this.dialogVisible = true
      this.$nextTick(() => this.clearDialogValidate())
    },
    async openEditDialog(row) {
      await this.openDialog('edit', row.id)
    },
    async openDetailDialog(row) {
      await this.openDialog('detail', row.id)
    },
    async openDialog(mode, id) {
      this.dialogMode = mode
      await this.loadStaffOptions()
      const response = await getAccountInfo(id)
      const data = response.data || {}
      if (data.ownerType === 'RELATION' && data.staffId) {
        await this.loadRelationOptions(data.staffId)
      } else {
        this.relationOptions = []
      }
      this.form = Object.assign(createEmptyForm(), data, {
        staffId: data.staffId || undefined,
        relationId: data.relationId || undefined,
        invalidDate: data.invalidDate || ''
      })
      if (mode !== 'detail') {
        applyIntermediaryRiskLevel(this.form)
      }
      this.dialogVisible = true
      this.$nextTick(() => this.clearDialogValidate())
    },
    handleOwnerTypeChange(value) {
      if (value !== 'RELATION') {
        this.form.relationId = undefined
        this.form.relationType = ''
        this.form.relationName = ''
        this.form.relationCertNo = ''
        this.relationOptions = []
      }
      if (!this.isInternalOwner) {
        this.form.staffId = undefined
        this.form.relationId = undefined
        this.form.relationType = ''
        this.form.relationName = ''
        this.form.relationCertNo = ''
        this.form.accountName = ''
        this.form.ownerId = ''
      } else if (value === 'EMPLOYEE' && this.form.staffId) {
        this.handleStaffChange(this.form.staffId)
      } else if (value === 'RELATION' && this.form.staffId) {
        this.loadRelationOptions(this.form.staffId)
        this.form.accountName = ''
        this.form.ownerId = ''
      }
      applyIntermediaryRiskLevel(this.form)
    },
    async handleStaffChange(staffId) {
      const staff = this.staffOptions.find(item => item.staffId === staffId)
      if (this.form.ownerType === 'EMPLOYEE') {
        this.form.accountName = staff ? staff.name : ''
        this.form.ownerId = staff ? (staff.idCard || '') : ''
      } else if (this.form.ownerType === 'RELATION') {
        this.form.relationId = undefined
        this.form.relationType = ''
        this.form.relationName = ''
        this.form.relationCertNo = ''
        this.form.accountName = ''
        this.form.ownerId = ''
        await this.loadRelationOptions(staffId)
      }
    },
    fillRelationMeta(relationId) {
      const relation = this.relationOptions.find(item => item.id === relationId)
      if (!relation) return
      this.form.relationType = relation.relationType
      this.form.relationName = relation.relationName
      this.form.relationCertNo = relation.relationCertNo
      this.form.ownerId = relation.relationCertNo
      this.form.accountName = relation.relationName
    },
    buildPayload() {
      applyIntermediaryRiskLevel(this.form)
      return {
        id: this.form.id,
        ownerType: this.form.ownerType,
        ownerId: this.form.ownerId,
        accountNo: this.form.accountNo,
        accountType: this.form.accountType,
        bankScope: this.form.bankScope,
        accountName: this.form.accountName,
        openBank: this.form.openBank,
        bankCode: this.form.bankCode,
        currency: this.form.currency,
        status: this.form.status,
        effectiveDate: this.form.effectiveDate,
        invalidDate: this.form.invalidDate || null,
        isActualControl: this.form.isActualControl,
        avgMonthTxnCount: this.form.avgMonthTxnCount,
        avgMonthTxnAmount: this.form.avgMonthTxnAmount,
        txnFrequencyLevel: this.form.txnFrequencyLevel,
        debitSingleMaxAmount: this.form.debitSingleMaxAmount,
        creditSingleMaxAmount: this.form.creditSingleMaxAmount,
        debitDailyMaxAmount: this.form.debitDailyMaxAmount,
        creditDailyMaxAmount: this.form.creditDailyMaxAmount,
        txnRiskLevel: this.form.txnRiskLevel
      }
    },
    clearDialogValidate() {
      if (this.$refs.dialogForm) {
        this.$refs.dialogForm.clearValidate()
      }
    },
    submitForm() {
      this.$refs.dialogForm.validate(valid => {
        if (!valid) return
        const payload = this.buildPayload()
        const request = this.dialogMode === 'edit' ? updateAccountInfo(payload) : addAccountInfo(payload)
        request.then(() => {
          this.$modal.msgSuccess(this.dialogMode === 'edit' ? '修改成功' : '新增成功')
          this.dialogVisible = false
          this.getList()
        })
      })
    },
    handleDelete(row) {
      this.$modal.confirm('是否确认删除账户号码为“' + row.accountNo + '”的数据项？').then(() => {
        return delAccountInfo(row.id)
      }).then(() => {
        this.$modal.msgSuccess('删除成功')
        this.getList()
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.query-form ::v-deep .el-row {
  display: flex;
  flex-wrap: wrap;
}

.query-form ::v-deep .el-col {
  float: none;
}

.query-form ::v-deep .el-form-item {
  margin-right: 0;
}

.account-page {
  min-height: calc(100vh - 84px);
  background: #f5f7fa;
}

.board {
  padding: 20px;
  border-radius: 8px;
  background: #fff;
  border: 1px solid #ebeef5;
}

.account-table ::v-deep .el-table__header th {
  background: #f8f8f9;
  color: #515a6e;
}

.form-section {
  margin-bottom: 18px;
  padding: 18px 18px 4px;
  border-radius: 8px;
  background: #f9fafb;
  border: 1px solid #ebeef5;
}

.accent-section {
  background: #f9fafb;
}

.section-head {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 16px;
}

.section-head span {
  color: #303133;
  font-size: 16px;
  font-weight: 700;
}

</style>
