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

  https://www.mall4j.com/

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

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

<template>
  <!-- 财务信息 -->
  <view class="Mall4j page-store-settings-financial">
    <view
      v-if="paySettlementType !== 1"
      class="head"
    >
      <view class="tit">
        {{ $t('jieSuanZhangHu') }}
      </view>
      <view class="tips">
        {{ $t('yiTianJia-0') }}<text class="stress">
          {{ settlementAccounts.length }}
        </text>{{ $t('geZhangHuZuiDuoKeTianJia') }}<text class="stress">
          {{ maxNum }}
        </text>{{ $t('ge-0') }}
      </view>
    </view>
    <view
      v-else
      class="allinpay-head"
    >
      <view class="tit">
        <text>{{ $t('jieSuanZhangHu-0') }}</text>
        <view class="alinpay-btns">
          <view
            v-if="!(legalAcctProtocolNo&&acctProtocolNo)"
            class="text-btn"
            @tap="onShowSignDialog"
          >
            {{ $t('qianDingXieYi') }}
          </view>
          <view
            class="text-btn"
            @click="onShowMobileDialog"
          >
            {{ mobile ? $t('jieChuBangDing') : $t('bangDingShouJi') }}
          </view>
        </view>
      </view>
      <view class="tips">
        {{ $t('yiTianJia') }} <text class="stress">
          {{ cardNumber }}
        </text>
        {{ $t('geJieSuanZhangHuZuiDuoKeTianJia') }} <text class="stress">
          10
        </text>
        {{ $t('geJieSuanZhangHu') }} <text>
          {{ $t('key-1') }} <text class="stress">
            1
          </text>
          {{ $t('geFaRenZhangHu') }}
        </text>
        <text v-if="mobile">
          {{ $t('bangDingShouJiHao') }}<text class="stress">
            {{ mobile }}
          </text>
        </text>
      </view>
    </view>

    <!-- 账户列表 -->
    <view class="account-list">
      <view
        v-for="item in settlementAccounts"
        :key="item.cardNo"
        class="account-item"
        @tap="onPutShopBankCard(item.shopBankCardId)"
      >
        <view class="ac-top">
          {{ item.bankName }}<text class="tag">
            {{ item.isDefault ? $t('moRenZhangHu-0') : "" }}
          </text>
        </view>
        <view class="ac-bottom">
          <view class="account-num">
            {{ item.cardNo }}
          </view>
          <view class="account-info">
            <view class="account-info-content">
              <view class="name">
                {{ item.recipientName }}
                <view
                  v-if="paySettlementType===1 && item.bankCardPro===0"
                  class="legalTip"
                >
                  {{ $t('faRen') }}
                </view>
              </view>
              <text>{{ item.openingBank }}</text>
            </view>
            <view class="operating-btn">
              <view
                v-if="paySettlementType===1 && item.bankCardPro===0"
                class="isDefault unbind-btn"
                @tap.stop="onUnbindBankCard(item.cardNo,item.shopBankCardId)"
              >
                {{ $t('jieBang') }}
              </view>
              <view v-if="baseInfoForm.shopStatus !== 5">
                <view
                  v-if="item.isDefault"
                  :class="{'m-disable':!$isAuthorities('shop:shopBankCard:noDefault')}"
                  class="isDefault"
                  @tap.stop="onSetNotDefault(item.shopBankCardId)"
                >
                  {{ $t('quXiaoMoRen') }}
                </view>
                <view
                  v-if="!item.isDefault"
                  :class="{'m-disable':!$isAuthorities('shop:shopBankCard:default')}"
                  class="isDefault"
                  @tap.stop="onSetDefault(item.shopBankCardId)"
                >
                  {{ $t('sheWeiMoRen') }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view
      v-if="settlementAccounts.length === 5 && paySettlementType !== 1"
      class="warm-tips"
    >
      {{ $t('tiShiZhangHuTianJiaYiDaDaoShangXianQingXianShanChuQiZhongYiGeZaiTianJia') }}
    </view>

    <!-- 添加 -->
    <view
      v-if=" $isAuthorities('shop:shopBankCard:save')&&(settlementAccounts.length < 5 && baseInfoForm.shopStatus !== 5 || (paySettlementType === 1 && (legalCardNumber<1 || cardNumber<10)))"
      class="add-btn"
      @tap="onAddAccount"
    >
      {{ $t('tianJiaXinZhangHu') }}
    </view>

    <!-- 绑定/解绑手机 -->
    <mobule-add-or-update
      v-if="mobileDialogVisible"
      ref="mobileAddOrUpdateRef"
      :is-have-mobile="!!mobile"
      @refresh-data-form="onQueryCompany"
    />

    <!-- 签约协议 -->
    <sign-acct-protocol
      v-if="signDialogVisible"
      ref="signAcctProtocolRef"
      :acct-protocol-no="acctProtocolNo"
      :legal-acct-protocol-no="legalAcctProtocolNo"
      :mobile="mobile"
      :legal-card-number="legalCardNumber"
    />
  </view>
</template>

<script setup>
import MobuleAddOrUpdate from '../../components/mobule-add-or-update/mobile-add-or-update.vue'
import SignAcctProtocol from '../../components/sign-acct-protocol/sign-acct-protocol.vue'

const paySettlementType = uni.getStorageSync('bbcPaySettlementType')

const $isAuthorities = util.isAuthorities
// 结算账户数目最大值
const maxNum = 5
// 账户列表
const settlementAccounts = ref([])
const baseInfoForm = ref({
  shopStatus: 0
})
let companyInfoProcessStatus = null
onShow(() => {
  onGetShopBankCardList()
  onGetShopDetailnfo()

  if (paySettlementType === 1 && companyInfoProcessStatus !== 0 && companyInfoProcessStatus !== 3) {
    // 查询企业信息
    onQueryCompany()
  }
  uni.setNavigationBarTitle({
    title: $t('caiWuXinXi')
  })
})

const acctProtocolNo = ref('') // 签约提现协议号
onLoad((options) => {
// #ifdef H5
  if (paySettlementType !== 1) {
    return
  }
  // 获取内存中的签约编号
  const acctProtocolNo = uni.getStorageSync('bbcAllinpayAcctProtocolNo')
  // 以下代码为H5页面签约成功执行, 小程序在App.vue的onShow中,APP则在单独的页面redirect.vue中
  // 如果本次签约和存储中的签约编号不一致，则需要提示签约成功并更新签约编号，否则不提示，避免重复提示签约成功
  if (Number(options.isSignSuccess) === 1 && options.bizContent && acctProtocolNo !== options.bizContent.acctProtocolNo) {
    uni.showToast({
      title: $t('qianYueChengGong'),
      icon: 'none',
      duration: 1000
    })
    // 上方已经重新获取通联会员信息，所以不用再次请求
    uni.setStorageSync('bbcAllinpayAcctProtocolNo', options.bizContent.acctProtocolNo)
  } else if (Number(options.isSignSuccess) === 0) {
    uni.showToast({
      title: $t('qianYueShiBai-0'),
      icon: 'none',
      duration: 1000
    })
  }
  // #endif
})

/**
 * 获取店铺信息
 */
const legalAcctProtocolNo = ref('') // 法人签约提现协议号
const onGetShopDetailnfo = () => {
  const params = {
    url: '/shop/shopDetail/info',
    method: 'GET'
  }
  http.request(params).then(({ data: res }) => {
    baseInfoForm.value = res
    companyInfoProcessStatus = res.companyInfoProcessStatus
  })
}
/**
   * 添加结算账户
   */
const onAddAccount = () => {
  if (paySettlementType === 1) {
    uni.redirectTo({
      url: '/package-settings/pages/allinpay-store-account/allinpay-store-account'
    })
    return
  }
  uni.redirectTo({
    url: '/package-settings/pages/store-settings-account/store-settings-account'
  })
}
/**
 * 获取店铺下的账户列表
 */
const legalCardNumber = ref(0) // 法人账户数量
const cardNumber = ref(0) // 非法人账户数量
const onGetShopBankCardList = () => {
  const params = {
    url: '/shop/shopBankCard/getShopBankCardList',
    method: 'GET'
  }
  uni.showLoading({
    mask: true
  })
  http.request(params).then(({ data: res }) => {
    if (paySettlementType === 1 && res && res.length > 0) {
      legalCardNumber.value = res.filter(item => item.bankCardPro === 0).length
      cardNumber.value = res.length - legalCardNumber.value
    }
    settlementAccounts.value = res
    uni.hideLoading()
  })
}
/**
 * 编辑账户信息
 *  @param {Number} shopBankCardId  账户id
 */
const onPutShopBankCard = (shopBankCardId) => {
  if (paySettlementType === 1) {
    return
  }
  uni.redirectTo({
    url: '/package-settings/pages/store-settings-account/store-settings-account?id=' + shopBankCardId + '&isNotEdit=' + (baseInfoForm.value.shopStatus === 5 ? 1 : 0)
  })
}
/**
 * 设为默认账户
 * @param {Number} shopBankCardId  账户id
 */
const onSetDefault = (shopBankCardId) => {
  http.request({
    url: '/shop/shopBankCard/setDefault',
    method: 'PUT',
    data: { shopBankCardId }
  }).then(() => {
    uni.hideToast()
    uni.showToast({
      title: $t('sheZhiChengGong'),
      success: () => {
        onGetShopBankCardList()
      }
    })
  })
}
/**
 * 取消默认账户
 * @param {Number} shopBankCardId  账户id
 */
const onSetNotDefault = (shopBankCardId) => {
  http.request({
    url: '/shop/shopBankCard/setNotDefault?shopBankCardId=' + shopBankCardId,
    method: 'PUT'
  }).then(() => {
    uni.hideToast()
    uni.showToast({
      title: $t('sheZhiChengGong-0'),
      success: () => {
        onGetShopBankCardList()
      }
    })
  })
}

// 查询企业信息（通联）
const mobile = ref('')
const onQueryCompany = () => {
  http.request({
    url: '/shop/allinpay/company/getCompanyInfo',
    method: 'get'
  }).then(({ data }) => {
    mobile.value = data.phone
    acctProtocolNo.value = data.acctProtocolNo // 签约信息
    legalAcctProtocolNo.value = data.legalAcctProtocolNo // 签约信息
  })
}

// 绑定/解绑手机号
const mobileAddOrUpdateRef = ref(null)
const mobileDialogVisible = ref(false)
const onShowMobileDialog = () => {
  mobileDialogVisible.value = true
  nextTick(() => {
    mobileAddOrUpdateRef.value.init(mobile.value)
  })
}

// 签约协议
const signAcctProtocolRef = ref(null)
const signDialogVisible = ref(false)
const onShowSignDialog = () => {
  signDialogVisible.value = true
  onQueryCompany()
  nextTick(() => {
    signAcctProtocolRef.value.init()
  })
}
// 解绑银行卡
const onUnbindBankCard = (cardNo, shopBankCardId) => {
  uni.showModal({
    title: $t('tiShi'),
    content: $t('shiFouJieBangFaRenZhangHao'),
    success: (modalRes) => {
      if (modalRes.confirm) {
        http.request({
          url: '/shop/allinpay/company/unbindBankCard',
          method: 'PUT',
          data: { cardNo, shopBankCardId }
        }).then(() => {
          uni.hideToast()
          uni.showToast({
            title: $t('jieBangChengGong'),
            success: () => {
              setTimeout(() => {
                onGetShopBankCardList()
              }, 1500)
            }
          })
        })
      }
    }
  })
}
</script>

<style lang="scss" scoped>
@use './store-settings-financial.scss';
</style>
