<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <!-- 结算账户 新增/编辑 -->
  <view class="Mall4j page-allinpay-store-account">
    <view class="uni-forms-box">
      <uni-forms
        ref="accountFormRef"
        :model-value="accounts"
        :rules="rules"
        validate-trigger="submit"
      >
        <!-- 账户类型 -->
        <view class="setting-info-item">
          <uni-forms-item key="bankCardPro">
            <view class="title">
              <text class="star">
                *
              </text>
              <text class="txt">
                {{ $t('zhangHuLeiXing') }}
              </text>
            </view>
            <view class="radio-con">
              <radio-group @change="onChangeAccountType">
                <radio
                  v-if="!(baseInfoForm.companyInfoProcessStatus === 0 || baseInfoForm.companyInfoProcessStatus === 3)"
                  style="transform:scale(0.8);"
                  value="0"
                  color="#082BA6"
                  :disabled="!(legalCardNumber<1)"
                  :checked="accounts.bankCardPro === 0"
                >
                  <text class="radio-txt">
                    {{ $t('faRenZhangHu') }}
                  </text>
                </radio>
                <radio
                  style="transform:scale(0.8)"
                  value="1"
                  color="#082BA6"
                  :disabled="!(cardNumber<10)"
                  :checked="accounts.bankCardPro === 1"
                >
                  <text class="radio-txt">
                    {{ $t('duiGongZhangHu') }}
                  </text>
                </radio>
              </radio-group>
            </view>
          </uni-forms-item>
        </view>
        <!-- 银行名称 -->
        <view
          v-if="accounts.bankCardPro===1"
          class="setting-info-item"
        >
          <uni-forms-item
            key="parentBankName"
            name="parentBankName"
          >
            <view class="title">
              <text class="star">
                *
              </text>
              <text class="txt">
                {{ $t('yinHangMingCheng') }}
              </text>
            </view>
            <view class="bank-select-plus">
              <jp-select-plus
                v-model="selectBank"
                show-name="bankName"
                keys="bankId"
                :is-line="false"
                color="#004EA2"
                :placeholder="$t('qingXuanZe')"
                is-search
                :list="bankList"
                @to-confirm="onChangeBank"
              />
            </view>
          </uni-forms-item>
        </view>

        <!-- 开户行 -->
        <view
          v-if="accounts.bankCardPro===1"
          class="setting-info-item"
        >
          <uni-forms-item
            key="bankName"
            name="bankName"
          >
            <view class="title">
              <text class="star">
                *
              </text>
              <text class="txt">
                {{ $t('kaiHuZhiHangMingCheng') }}
              </text>
            </view>
            <view class="input-box">
              <uni-easyinput
                v-model="accounts.bankName"
                :placeholder="$t('ruZhongGuoGongShangYinHangGuFenYouXianGongSiBeiJingYingTaoYuanZhiHang')"
                maxlength="20"
                @blur="onCheckInput('bankName')"
              />
            </view>
          </uni-forms-item>
        </view>

        <!-- 账户 -->
        <view
          v-if="accounts.bankCardPro===1"
          class="setting-info-item"
        >
          <uni-forms-item
            key="accountNo"
            name="accountNo"
          >
            <view class="title">
              <text class="star">
                *
              </text>
              <text class="txt">
                {{ $t('qingShuRuQiYeDuiGongZhangHu') }}
              </text>
            </view>
            <view
              name="accountNo"
              class="input-box"
            >
              <uni-easyinput
                v-model="accounts.accountNo"
                :placeholder="$t('qingShuRuZhangHuMing')"
                maxlength="19"
                @blur="onCheckInput('accountNo')"
              />
            </view>
          </uni-forms-item>
        </view>

        <!-- 支付行号 -->
        <view
          v-if="accounts.bankCardPro===1"
          class="setting-info-item"
        >
          <uni-forms-item
            key="unionBank"
            name="unionBank"
          >
            <view class="title">
              <text class="star">
                *
              </text>
              <text class="txt">
                {{ $t('zhiFuHangHao') }}
              </text>
            </view>
            <view class="input-box">
              <uni-easyinput
                v-model="accounts.unionBank"
                type="number"
                :placeholder="$t('qingShuRuZhiFuHangHao')"
                maxlength="12"
                @blur="onCheckInput('unionBank')"
              />
            </view>
          </uni-forms-item>
        </view>

        <!-- 法人账户开始 -->
        <view
          v-if="accounts.bankCardPro===0"
          class="setting-info-item"
        >
          <uni-forms-item
            key="cardNo"
            name="cardNo"
          >
            <view class="title">
              <text class="star">
                *
              </text>
              <text class="txt">
                {{ $t('zhangHu') }}
              </text>
            </view>
            <view class="input-box">
              <uni-easyinput
                v-model="accounts.cardNo"
                :placeholder="$t('qingShuRuYinHangKaHao')"
                maxlength="19"
                @blur="onCheckInput('cardNo')"
              />
            </view>
          </uni-forms-item>
        </view>
        <view
          v-if="accounts.bankCardPro===0"
          class="setting-info-item"
        >
          <uni-forms-item
            key="identityNo"
            name="identityNo"
          >
            <view class="title">
              <text class="star">
                *
              </text>
              <text class="txt">
                {{ $t('shenFenZheng') }}
              </text>
            </view>
            <view class="input-box">
              <uni-easyinput
                v-model="accounts.identityNo"
                :placeholder="$t('qingShuRuShenFenZhengHao')"
                maxlength="20"
                @blur="onCheckInput('identityNo')"
              />
            </view>
          </uni-forms-item>
        </view>
        <view
          v-if="accounts.bankCardPro===0"
          class="setting-info-item"
        >
          <uni-forms-item
            key="mobile"
            name="mobile"
          >
            <view class="title">
              <text class="star">
                *
              </text>
              <text class="txt">
                {{ $t('shouJiHao') }}
              </text>
            </view>
            <view class="input-box">
              <uni-easyinput
                v-model="accounts.mobile"
                :placeholder="$t('qingShuRuYinHangYuCunShouJiHao')"
                maxlength="11"
                @blur="onCheckInput('mobile')"
              />
            </view>
          </uni-forms-item>
        </view>
      </uni-forms>
    </view>
    <!-- 添加账户 -->
    <view class="account-footer">
      <button
        type="default"
        hover-class="none"
        @tap="onSubmit()"
      >
        {{ $t('queDing') }}
      </button>
    </view>
  </view>
</template>

<!-- eslint-disable n/no-callback-literal -->
<script setup>
import { checkIDCard } from '@/utils/validate'

onShow(() => {
  uni.setNavigationBarTitle({
    title: $t('jieSuanZhangHu')
  })
})

const selectBank = ref(0)
const rules = ref({
  parentBankName: {
    rules: [
      { required: true, errorMessage: $t('qingXuanZeYinHangMingCheng') }
    ]
  },
  bankName: {
    rules: [
      { required: true, errorMessage: $t('qingShuRuYinHangKaiHuHang') },
      {
        validateFunction: (rule, value, data, callback) => {
          if (value.length < 2 || value.length > 20) {
            callback($t('yinHangKaiHuHangChangDuZai_220GeZiFu'))
            return false
          }
          return true
        }
      }
    ]
  },
  accountNo: {
    rules: [
      { required: true, errorMessage: $t('qiYeDuiGongZhangHuBuNengWeiKong') }
    ]
  },
  unionBank: {
    rules: [
      { required: true, errorMessage: $t('qingShuRuZhiFuHangHao-0') },
      {
        validateFunction: (rule, value, data, callback) => {
          if (value.length < 12 || value.length > 12) {
            callback($t('qingShuRu_12WeiShuZi'))
            return false
          }
          return true
        }
      }
    ]
  },
  mobile: {
    rules: [
      { required: true, errorMessage: $t('shouJiHaoBuNengWeiKong') },
      {
        validateFunction: (rule, value, data, callback) => {
          const reg = /^1[0-9]{10}$/
          if (!reg.test(value)) {
            callback($t('qingShuRuZhengQueDeShouJiHao'))
            return false
          }
          return true
        }
      }
    ]
  },
  cardNo: {
    rules: [
      { required: true, errorMessage: $t('qingShuRuZhangHu') },
      {
        validateFunction: (rule, value, data, callback) => {
          const reg = /^([0-9]{1})(\d{12,18})$/
          if (!reg.test(value)) {
            callback($t('qingShuRuZhengQueDeYinHangKaHao'))
            return false
          }
          return true
        }
      }
    ]
  },
  identityNo: {
    rules: [
      { required: true, errorMessage: $t('shenFenZhengHaoMaBuNengWeiKong') },
      {
        validateFunction: (rule, value, data, callback) => {
          if (!value || !checkIDCard(value)) {
            callback($t('qingShuRuZhengQueDeYinHangKaHao-0'))
            return false
          }
          return true
        }
      }
    ]
  }
})

onLoad(() => {
  // 头部导航标题
  uni.setNavigationBarTitle({
    title: $t('xinZengZhangHu')
  })
  onGetBankList()
  onGetShopBankCardList()
  onGetShopDetailnfo()
})
/**
 * 获取店铺信息
 */
const baseInfoForm = ref({})// 店铺信息
const onGetShopDetailnfo = () => {
  const params = {
    url: '/shop/shopDetail/info',
    method: 'GET'
  }
  http.request(params).then(({ data }) => {
    baseInfoForm.value = data
  })
}

/**
 * 获取店铺下的账户列表
 */
const legalCardNumber = ref(0)
const cardNumber = ref(0)
// 编辑账户信息
const accounts = reactive({
  parentBankName: '',
  openingBank: '',
  cardNo: '',
  bankCardPro: 1,
  mobile: '', // 银行预存手机号
  unionBank: '', // 支付行号
  accountNo: '', // 企业对公账户
  identityNo: '' // 身份证号
})
const onGetShopBankCardList = () => {
  const params = {
    url: '/shop/shopBankCard/getShopBankCardList',
    method: 'GET'
  }
  uni.showLoading({
    mask: true
  })
  http.request(params).then(({ data }) => {
    if (data && data.length > 0) {
      legalCardNumber.value = data.filter(item => item.bankCardPro === 0).length
      cardNumber.value = data.length - legalCardNumber.value
      accounts.bankCardPro = cardNumber.value < 10 ? 1 : 0
    }
    uni.hideLoading()
  })
}
/**
 * 切换单选
 */
const onChangeAccountType = (val) => {
  accounts.bankCardPro = Number(val.detail.value)
}
/**
 * 检查输入框空格
 */
const onCheckInput = (type) => {
  const reg = /^\s+$/g
  if (type === 'bankName' && reg.test(accounts.bankName)) {
    accounts.bankName = ''
  }
  if (type === 'openingBank' && reg.test(accounts.openingBank)) {
    accounts.openingBank = ''
  }
  if (type === 'recipientName' && reg.test(accounts.recipientName)) {
    accounts.recipientName = ''
  }
  if (type === 'cardNo' && reg.test(accounts.cardNo)) {
    accounts.cardNo = ''
  }
}

/**
 *  添加银行卡信息
 */
let isAddBankCard = false// 是否正在添加银行卡
const onAddShopBankCard = () => {
  if (isAddBankCard) {
    return
  }
  isAddBankCard = true
  let dataForm
  let url
  if (accounts.bankCardPro === 1) {
    // 对公账户
    dataForm = {
      accountNo: accounts.accountNo,
      bankName: accounts.bankName,
      parentBankName: accounts.parentBankName,
      unionBank: accounts.unionBank
    }
    url = '/shop/allinpay/company/bindCompanyAccount'
  } else {
    // 法人账户
    dataForm = {
      cardNo: accounts.cardNo,
      phone: accounts.mobile,
      identityNo: accounts.identityNo
    }
    url = '/shop/allinpay/company/applyBindBankCard'
  }
  const params = {
    url,
    data: dataForm,
    method: 'POST'
  }
  http.request(params).then(() => {
    isAddBankCard = false
    uni.redirectTo({
      url: '/package-settings/pages/store-settings-financial/store-settings-financial'
    })
  }).catch((err) => {
    isAddBankCard = false
    uni.showToast({
      title: err.msg,
      icon: 'none',
      duration: 1500
    })
  })
}

// 重新提交申请
const applySubmit = ref(false) // 是否正在提交申请
const onResubmitApply = () => {
  if (applySubmit.value) {
    return
  }
  applySubmit.value = true
  uni.showLoading()
  http.request({
    url: '/shop/shopBankCard/allinpaySaveAndApplyShop',
    method: 'post',
    data: accounts
  }).then(() => {
    uni.showToast({
      title: $t('tiJiaoShenQingChengGong'),
      icon: 'none',
      duration: 1500,
      complete: () => {
        applySubmit.value = false
        uni.hideLoading()
        setTimeout(() => {
          uni.redirectTo({
            url: '/pages/store-settings/store-settings'
          })
        }, 1500)
      }
    })
  })
}

/**
 * 提交表单
 */
const accountFormRef = ref(null)
const onSubmit = () => {
  accountFormRef.value.validate().then(() => {
    if (baseInfoForm.value.companyInfoProcessStatus === 0 || baseInfoForm.value.companyInfoProcessStatus === 3) {
      onResubmitApply()
    } else {
      onAddShopBankCard()
    }
  })
}

const bankList = ref([])
const onGetBankList = () => {
  http.request({
    url: '/publicBank/list',
    method: 'get'
  }).then(({ data }) => {
    bankList.value = data.map((item) => {
      return {
        ...item,
        bankId: item.bankId + ''
      }
    })
  })
}

const onChangeBank = (val) => {
  if (val && val.length > 0) {
    accounts.parentBankName = val[0].bankName
  }
}
</script>
<style lang="scss" scoped>
@use './allinpay-store-account.scss';
</style>
