<template>
  <business-page-layout title="银行卡报备" :show-back="true">
    <view class="page-wrap">
      <view v-if="loading" class="loading">加载中...</view>
      <view v-else>
        <view v-if="reportInfo && reportInfo.id" class="status-card">
          <text class="status-label">报备状态</text>
          <text class="status-value">{{ reportStatusText }}</text>
          <u-button size="mini" class="sync-btn" @click="syncStatus">刷新状态</u-button>
        </view>
        <view v-if="reportInfo && reportInfo.audit_remarks" class="reject-tip">
          驳回原因：{{ reportInfo.audit_remarks }}
        </view>
        <view v-if="showPendingSyncHint" class="pending-tip">
          当前为待审核，如审核结果已久未更新，请先点击「刷新状态」
        </view>

        <view v-if="!hasReport || canSubmitNew" class="form-wrap">
          <view class="tip">{{ formTip }}</view>
          <u-form :model="form" label-width="180">
            <u-form-item label="开户人姓名" :required="true">
              <u-input v-model="form.bank_user_name" placeholder="请输入开户人姓名" />
            </u-form-item>
            <u-form-item label="银行卡号" :required="true">
              <u-input v-model="form.bank_card" type="number" placeholder="请输入银行卡号" />
            </u-form-item>
            <u-form-item label="开户银行" :required="true">
              <u-input v-model="form.bank_name" placeholder="请输入开户银行名称" />
            </u-form-item>
            <u-form-item label="账户类型" :required="true">
              <u-input :value="accountTypeLabel" type="select" placeholder="请选择" @click="showAccountType = true" />
              <u-select v-model="showAccountType" :list="accountTypeOptions" @confirm="onAccountTypeConfirm" />
            </u-form-item>
            <u-form-item label="银联行号">
              <u-input v-model="form.bank_no" placeholder="对公/非62开头卡号必填" />
            </u-form-item>
            <u-form-item label="证件号码">
              <u-input v-model="form.cert_no" placeholder="选填" />
            </u-form-item>
            <u-form-item label="合同附件" :required="true">
              <view class="attachment-row">
                <text v-if="form.attachment" class="attachment-name" @click="previewAttachment">{{ attachmentName }}</text>
                <text v-else class="attachment-placeholder">请上传合同附件</text>
                <u-button size="mini" @click="uploadAttachment">上传</u-button>
              </view>
            </u-form-item>
            <u-form-item label="备注">
              <u-input v-model="form.remark" placeholder="选填" />
            </u-form-item>
            <u-form-item label="摘要">
              <u-input v-model="form.summary" placeholder="选填" />
            </u-form-item>
          </u-form>
          <u-button type="primary" :custom-style="primaryStyle" :loading="submitting" @click="submit">{{ submitButtonText }}</u-button>
        </view>
      </view>
    </view>
  </business-page-layout>
</template>

<script>
import BusinessPageLayout from '@/subPackages/sub_salesperson/components/business-page-layout.vue'
import { getStoreBankCardReportDetail, reportStoreBankCard, syncStoreBankCardStatusByStore, updateStoreBankCard } from '@/api/bankCardReport.js'
import { pickAndUploadImage } from '@/subPackages/sub_salesperson/common/inputFormHelpers.js'
import { uploadToOss } from '@/common/js/oss-upload.js'
import { prepareImagePath } from '@/common/js/image-compress.js'

const ACCOUNT_TYPES = [
  { label: '对公账户', value: '1' },
  { label: '法人账户', value: '2' },
  { label: '授权对公账户', value: '3' },
  { label: '授权个人账户', value: '4' },
]

export default {
  components: { BusinessPageLayout },
  data() {
    return {
      storeId: 0,
      storeInputId: 0,
      loading: true,
      submitting: false,
      reportInfo: null,
      showAccountType: false,
      form: {
        bank_user_name: '',
        bank_card: '',
        bank_name: '',
        account_type: '2',
        bank_no: '',
        cert_no: '',
        attachment: '',
        remark: '',
        summary: '',
        use_type: '2',
      },
      primaryStyle: {
        backgroundColor: '#6acdbb',
        color: '#ffffff',
        borderColor: '#6acdbb',
        marginTop: '32rpx',
      },
    }
  },
  computed: {
    accountTypeOptions() {
      return ACCOUNT_TYPES
    },
    accountTypeLabel() {
      const item = ACCOUNT_TYPES.find((o) => o.value === this.form.account_type)
      return item ? item.label : '请选择'
    },
    hasReport() {
      return !!(this.reportInfo && this.reportInfo.id)
    },
    canSubmitNew() {
      if (!this.hasReport) return true
      return [3, 4].includes(Number(this.reportInfo.report_status))
    },
    isRejectedResubmit() {
      return this.hasReport && [3, 4].includes(Number(this.reportInfo.report_status))
    },
    showPendingSyncHint() {
      return this.hasReport && Number(this.reportInfo.report_status) === 1
    },
    formTip() {
      if (this.isRejectedResubmit) {
        return '审核未通过，请修改信息后重新上传合同附件并提交'
      }
      return '新报备需上传合同附件，字段与 PC 端一致'
    },
    submitButtonText() {
      return this.isRejectedResubmit ? '重新提交报备' : '提交报备'
    },
    reportStatusText() {
      const s = Number(this.reportInfo?.report_status)
      if (s === 2) return '有效'
      if (s === 3) return '审核不通过'
      if (s === 4) return '无效'
      if (s === 1) return '待审核'
      return this.reportInfo?.report_status_text || '未知'
    },
    attachmentName() {
      if (!this.form.attachment) return ''
      return this.form.attachment.split('/').pop() || '已上传'
    },
  },
  onLoad(q) {
    this.storeId = Number(q.store_id || 0)
    this.storeInputId = Number(q.store_input_id || 0)
    this.loadDetail()
  },
  methods: {
    loadDetail() {
      if (!this.storeId) {
        this.loading = false
        return
      }
      this.loading = true
      getStoreBankCardReportDetail(this.storeId)
        .then((w) => {
          if (w.ok && w.data) {
            this.reportInfo = w.data
            this.applyDraft(w.data)
            if (Number(w.data.report_status) === 1 && w.data.id) {
              this.syncStatus({ silent: true })
            }
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    applyDraft(data) {
      if (!data) return
      const rejectedResubmit = data.id && [3, 4].includes(Number(data.report_status))
      if (data.id && !rejectedResubmit) return
      this.form.bank_user_name = data.bank_user_name || ''
      this.form.bank_card = data.bank_card || ''
      this.form.bank_name = data.bank_name || ''
      this.form.account_type = String(data.account_type || data.bank_account_type || '2')
      this.form.bank_no = data.bank_no || ''
      this.form.cert_no = data.cert_no || ''
      this.form.remark = data.remark || ''
      this.form.summary = data.summary || ''
      this.form.attachment = rejectedResubmit ? '' : (data.attachment || '')
    },
    onAccountTypeConfirm(e) {
      const item = e[0]
      if (item) this.form.account_type = String(item.value)
    },
    uploadAttachment() {
      uni.showActionSheet({
        itemList: ['相册/拍照', '选择文件'],
        success: (res) => {
          if (res.tapIndex === 0) {
            pickAndUploadImage().then((url) => {
              this.form.attachment = url
            }).catch(() => {})
          } else {
            this.chooseAndUploadFile()
          }
        },
      })
    },
    chooseAndUploadFile() {
      uni.chooseMessageFile({
        count: 1,
        type: 'file',
        success: async (res) => {
          const file = res.tempFiles && res.tempFiles[0]
          if (!file) return
          uni.showLoading({ title: '上传中...', mask: true })
          try {
            const prepared = await prepareImagePath({ path: file.path, size: file.size })
            const uploadPath = prepared ? prepared.path : file.path
            const result = await uploadToOss({ filePath: uploadPath })
            this.form.attachment = result.url
          } catch (e) {
            uni.showToast({ title: e.message || '上传失败', icon: 'none' })
          } finally {
            uni.hideLoading()
          }
        },
      })
    },
    previewAttachment() {
      if (!this.form.attachment) return
      const url = this.form.attachment
      if (/\.(jpg|jpeg|png|gif|webp)$/i.test(url)) {
        uni.previewImage({ urls: [url] })
      } else {
        uni.setClipboardData({ data: url })
        uni.showToast({ title: '链接已复制', icon: 'none' })
      }
    },
    validateForm() {
      const f = this.form
      if (!f.bank_user_name?.trim()) return this.toast('请输入开户人姓名')
      if (!f.bank_card?.trim()) return this.toast('请输入银行卡号')
      if (!f.bank_name?.trim()) return this.toast('请输入开户银行')
      if (!f.account_type) return this.toast('请选择账户类型')
      if (!f.attachment?.trim()) return this.toast('请上传合同附件')
      return true
    },
    toast(msg) {
      uni.showToast({ title: msg, icon: 'none' })
      return false
    },
    submit() {
      if (!this.validateForm()) return
      this.submitting = true
      const payload = {
        store_id: this.storeId,
        store_input_id: this.storeInputId,
        ...this.form,
        bank_account_type: this.mapAccountTypeToStore(this.form.account_type),
      }
      const request = this.isRejectedResubmit
        ? updateStoreBankCard({ ...payload, id: this.reportInfo.id })
        : reportStoreBankCard(payload)
      request
        .then((w) => {
          if (w.ok) {
            uni.showToast({
              title: this.isRejectedResubmit ? '报备已重新提交' : '报备已提交',
              icon: 'success',
            })
            setTimeout(() => this.loadDetail(), 500)
          } else {
            uni.showToast({ title: (w.res && w.res.msg) || '提交失败', icon: 'none' })
          }
        })
        .finally(() => {
          this.submitting = false
        })
    },
    mapAccountTypeToStore(accountType) {
      const map = { '1': 1, '2': 2, '3': 1, '4': 2 }
      return map[String(accountType)] || 2
    },
    syncStatus(options = {}) {
      syncStoreBankCardStatusByStore(this.storeId).then((w) => {
        if (w.ok) {
          this.reportInfo = w.data
          this.applyDraft(w.data)
          if (!options.silent) {
            uni.showToast({ title: '已刷新', icon: 'success' })
          }
        }
      })
    },
  },
}
</script>

<style scoped>
.page-wrap { padding: 24rpx; }
.loading { text-align: center; color: #86909c; padding: 80rpx 0; }
.status-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 28rpx;
  margin-bottom: 24rpx;
  display: flex;
  align-items: center;
  gap: 16rpx;
  flex-wrap: wrap;
}
.status-label { color: #86909c; font-size: 26rpx; }
.status-value { color: #1d2129; font-size: 30rpx; font-weight: 600; flex: 1; }
.reject-tip {
  background: #fff2f0;
  border-radius: 12rpx;
  color: #cf1322;
  font-size: 24rpx;
  line-height: 1.5;
  margin-bottom: 24rpx;
  padding: 20rpx 24rpx;
}
.pending-tip {
  background: #fffbe6;
  border-radius: 12rpx;
  color: #ad6800;
  font-size: 24rpx;
  line-height: 1.5;
  margin-bottom: 24rpx;
  padding: 20rpx 24rpx;
}
.form-wrap { background: #fff; border-radius: 16rpx; padding: 24rpx; }
.tip { font-size: 24rpx; color: #86909c; margin-bottom: 24rpx; line-height: 1.5; }
.attachment-row { display: flex; align-items: center; gap: 16rpx; width: 100%; }
.attachment-name { flex: 1; font-size: 24rpx; color: #165dff; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.attachment-placeholder { flex: 1; font-size: 26rpx; color: #c0c4cc; }
</style>
