<template>
  <BasePage>
    <div class="cashoutaccount">

      <div class="ca_content">
        <van-cell-group class="list">
          <van-swipe-cell v-for="i in data" :key="i.id">
            <van-cell>
              <template #title>
                <div class="item">
                  <img :src="i.bankspname === '支付宝' ? '/img/aliicon.png' : '/img/bankcardicon.png'" alt="">
                  <div>
                    <span>
                      {{ i.bankspname === '支付宝' ? '支付宝账号' : i.bankspname }}（{{ i.bankid === 91 ? i.bankcellphone
                        : i.bankcardnumber }}）
                    </span>
                    <p v-if="i.bankid === 91">
                      2小时内到账
                    </p>
                    <p v-else>
                      {{ i.realname }}
                    </p>
                  </div>
                </div>
              </template>
            </van-cell>
            <template #right>
              <van-button style="height: 100%;" square text="删除" type="danger" class="delete-button"
                @click="deleted(i)" />
            </template>
          </van-swipe-cell>
        </van-cell-group>
      </div>


      <div class="ca_bottom">
        <div class="tips">
          <p>
            <span>注意：</span>绑定添加银行卡必须保证银行卡号、银行预留手机号要同一个人信息才能添加成功，仅限 <span>“添加成功”</span> 状态的银行卡才可用于提现，添加不成功的银行卡无法用于提现！
          </p>
        </div>

        <div class="btn_box">
          <!-- <button class="alipay" @click="showAddAliPayPopup = true">
            添加支付宝
          </button> -->
          <button class="bankcard" @click="showAddPopup = true">
            添加银行卡
          </button>

          <div class="toCashout" @click="$navigate('Cashout')">
            <b>去提现</b>
          </div>

        </div>
      </div>

      <van-action-sheet v-model:show="showAddAliPayPopup" :title="'新增支付宝账户'" style="min-height: 70vw;">
        <div class="bankcard-edit">
          <van-form @submit="save" label-align="top">
            <van-cell-group inset>
              <van-field v-model="tempData.realname" label="真实姓名" placeholder="请输入支付宝账号绑定真实姓名"
                :rules="[{ required: true, message: '请填写真实姓名' }]" clearable required />
              <van-field v-model="tempData.bankcellphone" label="支付宝账号" placeholder="请输入支付宝账号"
                :rules="[{ required: true, message: '请填写支付宝账号' }]" clearable required />
              <div class="w" style="position: fixed;left:0;bottom: 0;padding: 3.333vw;border-top:1px solid #f5f5f5">
                <van-button color="#ea3e23" block round style="width: 100%" type="primary" native-type="save"
                  :loading="saving">保存</van-button>
              </div>
            </van-cell-group>
          </van-form>
        </div>
      </van-action-sheet>

      <van-action-sheet v-model:show="showAddPopup" :title="'新增银行卡'">
        <div class="bankcard-edit">
          <van-form @submit="saveBanks" label-align="top">
            <van-cell-group inset>
              <van-field v-model="tempData.realname" label="姓名" placeholder="请输入真实姓名"
                :rules="[{ required: true, message: '请填写真实姓名' }]" clearable required />
              <van-field v-model="tempData.idnumber" label="身份证" placeholder="请输入身份证号"
                :rules="[{ required: true, message: '请输入身份证号' }]" clearable required :formatter="formatter" />
              <van-field v-model="tempData.certbegindate" label="身份证起始日期" placeholder="请选择身份证起始日期"
                :rules="[{ required: true, message: '请选择身份证起始日期' }]" clearable required is-link
                @click="tempData.obj = 'certbegindate'; showDate = true;" readonly />

              <van-field class="maxDate" name="radio" label="身份证截止日期" required>
                <template #input>
                  <van-radio-group v-model="checked" direction="horizontal">
                    <van-radio :name="0">短期</van-radio>
                    <van-radio :name="1">长期</van-radio>
                  </van-radio-group>
                </template>
              </van-field>
              <van-field v-model="tempData.certenddate" v-if="!checked" label=" " placeholder="请选择身份证截止日期"
                :rules="[{ required: true, message: '请选择身份证起截止日期' }]" clearable is-link
                @click="tempData.obj = 'certenddate'; showDate = true;" readonly />
              <van-field v-model="tempData.bankcellphone" label="手机号" placeholder="请输入手机号"
                :rules="[{ required: true, message: '请填写手机号' }]" type="phone" clearable required
                :formatter="formatter" />
              <van-field v-model="tempData.bankcardnumber" label="银行卡号" placeholder="请输入银行卡号"
                :rules="[{ required: true, message: '请填写银行卡号' }]" clearable required :formatter="formatter" />
              <van-field v-model="tempData.bankname" label="银行名称" placeholder="请选择银行名称"
                :rules="[{ required: true, message: '请选择银行名称' }]" readonly required is-link
                @click="showBankPicker = true" />
              <van-field v-model="regionName" label="开户地区" placeholder="请选择开户地区"
                :rules="[{ required: true, message: '请选择开户地区' }]" clearable required is-link @click="showRegion = true;"
                readonly />
              <van-cell>
                <template #title>
                  <van-button color="#ea3e23" style="width: 100%" round type="primary" native-type="saveBanks"
                    :loading="saving">保存</van-button>
                </template>
              </van-cell>
            </van-cell-group>
          </van-form>
        </div>
      </van-action-sheet>

      <van-popup v-model:show="showDate" position="bottom">
        <van-date-picker v-model="currentDate" title="选择年月日" :columns-type="['year', 'month', 'day']"
          :min-date="minDate" :max-date="maxDate" @confirm="onconfirm" @cancel="showDate = false" />
      </van-popup>

      <van-popup v-model:show="showRegion" round position="bottom">
        <van-cascader v-model="region" title="请选择地区" :options="areaList" :field-names="defaultProps" @change="onChange"
          @finish="onFinish" @close="showRegion = false" />
      </van-popup>

      <van-popup v-model:show="showBankPicker" round position="bottom">
        <van-picker title="选择银行" :columns="bankColumns" @confirm="onBankConfirm" @cancel="showBankPicker = false" />
      </van-popup>
    </div>
  </BasePage>


</template>

<script>
import { useCascaderAreaData } from '@vant/area-data'
export default {
  name: 'CashoutAccount',
  mounted() {
    this.init();
    this.getBankId()
  },
  data() {
    return {
      showAddAliPayPopup: false,
      showAddPopup: false,
      showBankPicker: false,
      tempData: {},
      saving: false,
      checked: 0,
      data: {},
      showDate: false,
      showRegion: false,
      currentDate: [`${new Date().getFullYear()}`, `${new Date().getMonth() + 1}`],
      minDate: new Date('1900/01/01'),
      maxDate: new Date('2099/12/31'),
      regionName: '',
      region: '',
      bankidGroup: {},
      areaList: useCascaderAreaData(),
      defaultProps: {
        text: 'text',
        value: 'value',
        children: 'children',
      },
    }
  },
  computed: {
    bankColumns() {
      return this.bankidGroup.map(item => ({ text: item.name, value: item.id }));
    }
  },
  methods: {
    init() {
      this.$get('/v1/client/DUserbankcardsClient').then(data => {
        this.data = data.data;
      }).catch(err => {
        this.$showFailToast(err.message);
      });
    },
    formatter(value) {
      return value.replace(/\s/g, '');
    },
    getBankId() {
      this.$get('/v1/client/DBanksClient').then(res => {
        this.bankidGroup = res.data;
      })
    },
    onChange({ selectedOptions }) {
      this.tempData.provid = selectedOptions[0]?.value || '';
    },
    onFinish({ selectedOptions }) {
      this.showRegion = false;
      this.regionName = selectedOptions.map(item => item.text).join('/');
      this.tempData.provid = selectedOptions[0]?.value || '';
      this.tempData.areaid = selectedOptions[1]?.value || selectedOptions[0]?.value || '';
    },
    onBankConfirm({ selectedValues }) {
      const bank = this.bankidGroup.find(item => item.id === selectedValues[0]);
      if (bank) {
        this.tempData.bankid = bank.id;
        this.tempData.bankname = bank.name;
      }
      this.showBankPicker = false;
    },
    onconfirm({ selectedValues }) {
      const date = selectedValues.join('-');
      if (this.tempData.obj === 'certbegindate') {
        this.tempData.certbegindate = date;
      } else if (this.tempData.obj === 'certenddate') {
        this.tempData.certenddate = date;
      }
      this.showDate = false;
    },
    save() {
      this.saving = true;
      this.$post('/v1/client/DUserbankcardsClient', { ...this.tempData, bankid: 91 }).then(data => {
        this.$showSuccessToast('添加成功');
        this.tempData = {};
        // this.$refs.BaseList.refresh();
        this.showAddAliPayPopup = false;
        this.init();
      }).catch(err => {
        this.$showFailToast(err.message);
      }).finally(() => {
        this.saving = false;
      });
    },
    saveBanks() {
      if (!this.$validPhone(this.tempData.bankcellphone)) {
        this.$showFailToast('手机号格式错误');
        return;
      }
      if (!this.$validIdCard(this.tempData.idnumber)) {
        this.$showFailToast('身份证格式错误');
        return;
      }

      this.saving = true;
      const params = {
        "realname": this.tempData.realname,
        "idnumber": this.tempData.idnumber,
        "bankid": this.tempData.bankid || 0,
        "bankname": this.tempData.bankname || '',
        "bankcardnumber": this.tempData.bankcardnumber,
        "bankcellphone": this.tempData.bankcellphone,
        "sort": 0,
        "certtype": '00',
        "certvaliditytype": this.checked === 1 ? "1" : "0",
        "certbegindate": this.tempData.certbegindate ? this.tempData.certbegindate.replaceAll('-', '') : '',
        "certenddate": this.checked === 1 ? '' : (this.tempData.certenddate ? this.tempData.certenddate.replaceAll('-', '') : ''),
        "cardtype": "1",
        "provid": this.tempData.provid || '',
        "areaid": this.tempData.areaid || '',
        "isshopreceive": Boolean(this.$ls.get('isshop'))
        // "isshopreceive": false

      };

      this.$post('/v1/client/DUserbankcardsClient', params).then(res => {
        this.$showSuccessToast('添加成功');
        this.tempData = {};
        this.regionName = '';
        this.region = '';
        this.checked = 0;
        this.init();
        this.showAddPopup = false;
      }).catch(err => {
        this.$showFailToast(err.message);
      }).finally(() => {
        this.saving = false;
      });
    },
    deleted(e) {
      this.$del(`/v1/client/DUserbankcardsClient/${e.id}`).then(data => {
        this.$showSuccessToast('删除成功');
        this.init();
      }).catch(err => {
        this.$showFailToast(err.message);
      });
    },
  }
}
</script>