<template>
  <div class="app-container">
    <!-- 列表区 -->
    <el-card shadow="never" class="table-card">
      <div slot="header" class="card-header">
        <span class="card-title">收款账户</span>
      </div>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['agri:seller:finance:payAccount:add']"
          >添加账户</el-button>
        </el-col>
        <right-toolbar :showSearch="false" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="accountList" :empty-text="emptyTableText">
        <el-table-column label="收款方式" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.accountTypeText || accountTypeLabel(scope.row.accountType) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="真实姓名" align="center" prop="realName" width="120" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.realName || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="账号" align="center" min-width="180" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.accountNoMask || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="添加时间" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="140" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['agri:seller:finance:payAccount:edit']">编辑</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['agri:seller:finance:payAccount: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" />
    </el-card>

    <!-- 添加/编辑弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="520px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="small">
        <el-form-item label="收款方式" prop="accountType">
          <el-radio-group v-model="form.accountType" :disabled="isEdit" @change="handleAccountTypeChange">
            <el-radio v-for="item in accountTypeOptions" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入真实姓名" maxlength="64" show-word-limit />
        </el-form-item>
        <el-form-item :label="accountNoLabel" prop="accountNo">
          <el-input v-model="form.accountNo" :placeholder="accountNoPlaceholder" maxlength="128" />
          <p v-if="isEdit && form.accountNoMask" class="form-tip">当前账号：{{ form.accountNoMask }}（修改请填写完整账号）</p>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSellerPayAccounts,
  addSellerPayAccount,
  updateSellerPayAccount,
  delSellerPayAccount
} from "@/api/agri/seller/finance/payAccount"
import { getSellerContext } from "@/api/agri/seller/context"
import { setSellerShopContext } from "@/utils/sellerShop"

const ACCOUNT_TYPE_MAP = {
  "1": "银行卡",
  "2": "支付宝",
  "3": "微信"
}

export default {
  name: "AgriSellerFinancePayAccount",
  data() {
    const validateAccountNo = (rule, value, callback) => {
      if (!value || !String(value).trim()) {
        callback(new Error(this.accountNoRequiredMsg))
        return
      }
      if (this.form.accountType === "1" && !/^\d+$/.test(String(value).trim())) {
        callback(new Error("请输入正确的银行卡号"))
        return
      }
      callback()
    }
    return {
      loading: false,
      total: 0,
      accountList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      open: false,
      title: "",
      isEdit: false,
      form: {},
      accountTypeOptions: [
        { value: "1", label: "银行卡" },
        // { value: "2", label: "支付宝" },
        { value: "3", label: "微信" }
      ],
      rules: {
        accountType: [{ required: true, message: "请选择收款方式", trigger: "change" }],
        realName: [{ required: true, message: "请填写真实姓名", trigger: "blur" }],
        accountNo: [{ validator: validateAccountNo, trigger: "blur" }]
      }
    }
  },
  computed: {
    emptyTableText() {
      return "暂无收款账户，请先添加"
    },
    accountNoLabel() {
      if (this.form.accountType === "1") {
        return "银行卡号"
      }
      if (this.form.accountType === "2") {
        return "支付宝号"
      }
      if (this.form.accountType === "3") {
        return "微信号"
      }
      return "账号"
    },
    accountNoPlaceholder() {
      if (this.form.accountType === "1") {
        return "请输入银行卡号"
      }
      if (this.form.accountType === "2") {
        return "请输入支付宝号"
      }
      if (this.form.accountType === "3") {
        return "请输入微信号"
      }
      return "请先选择收款方式"
    },
    accountNoRequiredMsg() {
      if (this.form.accountType === "1") {
        return "请填写银行卡号"
      }
      if (this.form.accountType === "2") {
        return "请填写支付宝号"
      }
      if (this.form.accountType === "3") {
        return "请填写微信号"
      }
      return "请填写账号"
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    accountTypeLabel(type) {
      return ACCOUNT_TYPE_MAP[type] || "—"
    },
    /** 初始化：加载店铺上下文后拉列表 */
    initPage() {
      this.loadShopContext().then(() => {
        this.getList()
      }).catch(() => {
        this.getList()
      })
    },
    /** 加载商家端当前店铺上下文 */
    loadShopContext() {
      return getSellerContext().then(response => {
        const data = response.data || {}
        if (data.shopId != null) {
          setSellerShopContext(data.shopId, data.shopName)
        }
      })
    },
    /** 查询账户列表 */
    getList() {
      this.loading = true
      listSellerPayAccounts(this.queryParams).then(response => {
        this.accountList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 重置表单 */
    reset() {
      this.form = {
        accountId: undefined,
        accountType: "1",
        realName: undefined,
        accountNo: undefined,
        accountNoMask: undefined
      }
      this.isEdit = false
      if (this.$refs.form) {
        this.resetForm("form")
      }
    },
    /** 打开添加弹窗 */
    handleAdd() {
      this.reset()
      this.title = "添加账户"
      this.open = true
    },
    /** 打开编辑弹窗 */
    handleUpdate(row) {
      this.reset()
      this.isEdit = true
      this.title = "编辑账户"
      this.form = {
        accountId: row.accountId,
        accountType: row.accountType,
        realName: row.realName,
        accountNo: undefined,
        accountNoMask: row.accountNoMask
      }
      this.open = true
    },
    /** 切换收款方式时清空账号校验 */
    handleAccountTypeChange() {
      this.form.accountNo = undefined
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate("accountNo")
        }
      })
    },
    /** 提交添加/编辑 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return
        }
        const payload = {
          accountType: this.form.accountType,
          realName: String(this.form.realName).trim(),
          accountNo: String(this.form.accountNo).trim()
        }
        if (this.form.accountId != null) {
          payload.accountId = this.form.accountId
          updateSellerPayAccount(payload).then(() => {
            this.$modal.msgSuccess("保存成功")
            this.open = false
            this.getList()
          })
        } else {
          addSellerPayAccount(payload).then(() => {
            this.$modal.msgSuccess("添加成功")
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 删除账户 */
    handleDelete(row) {
      const name = row.accountTypeText || this.accountTypeLabel(row.accountType)
      const mask = row.accountNoMask || ""
      this.$modal.confirm(`确认删除该${name}账户「${mask}」吗？删除后不可在提现时选择，已提交的提现单不受影响。`).then(() => {
        return delSellerPayAccount(row.accountId)
      }).then(() => {
        this.$modal.msgSuccess("删除成功")
        this.getList()
      }).catch(() => {})
    },
    /** 关闭弹窗 */
    cancel() {
      this.open = false
      this.reset()
    }
  }
}
</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.card-title {
  font-weight: 600;
  font-size: 15px;
}
.mb8 {
  margin-bottom: 8px;
}
.form-tip {
  margin: 6px 0 0;
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
}
</style>
