<template>
  <view class="xd-wallet-chose">
    <xd-down-drawer :show.sync="xdDownDrawer" :isBodyClose="false">
      <view class="title" >选择{{showName}}</view>
      <view class="wallet_body_wrap">
        <view class="wallet_body">
          <view class="wallet_total">
            <view class="_title">全部{{showName}}</view>
            <view class="_money">{{totalAmount/100}}</view>
          </view>
          <view class="wallet_list" :key="renderChecked">
            <view class="wallet_item"
              v-for="(item, i) in showWalletList" :key="i"
              @click="handleChange(!(item.wallet_use_price > 0), item)"
            >
            <view>
              <view class="label">
                <view class="label_tit">{{item.wallet_name}}</view>
                <view class="label_sub">（剩余{{item.amount/100}}）</view>
              </view>
              <view class="label_company" v-if="item.customer_name">{{ item.customer_name }}</view>
            </view>
              
              <view class="value">
                <view class="val_sub" v-if="item.wallet_use_price > 0">
                  本单<view class="red">已减 <xd-unit :price="item.wallet_use_price" :isOld="false" :fontSize="24" :iconSize="0.3"></xd-unit></view>
                </view>
                <xd-radio
                  :value="item.wallet_use_price > 0"
                  :isClickEvent="false"
                  :isOld="false"
                ></xd-radio>
              </view>
            </view>
          </view>
        </view>
        <view style="height: 100rpx;"></view>
        <view
          v-show="xdDownDrawer"
          class="bottom_btn"
          :style="alert_bottom"
        >
          <xd-button width="680rpx" type="primary" radius="50rpx" @click="handleChose">确认</xd-button>
        </view>
      </view>
    </xd-down-drawer>
  </view>
</template>
<script>
  import XdDownDrawer from "@/components/XdDownDrawer/XdDownDrawer"
  import XdRadio from "@/components/XdRadio/XdRadio"
  import XdButton from "@/components/XdButton/XdButton"
  import XdUnit from "@/components/XdUnit/XdUnit"
  export default {
    name: "XdWalletChose",
    components: {
      XdDownDrawer,
      XdRadio,
      XdButton,
      XdUnit
    },
    props: {
      show: {
        type: Boolean,
        default: false
      },
      layoutInfo: {},
      getUserWalletList: {
        type: Function
      },
      useBindedWallet: {
        type: Function
      },
      hadChoseWallet:{
        type: null | Array
      },
      defaultUseFirst: {
        type: Boolean,
        default: false
      }
    },
    watch: {
      show(n, o){
        this.xdDownDrawer = n;
      },
      xdDownDrawer(n, o){
        console.log('xdDownDrawer show', n, o, this.hadChoseWallet);
        if(n){
          if(!this.hadChoseWallet){
            this.selectedWalletList =  [];
            this.walletPayPrice = 0;
          }else{
            // 重新打开时，根据 hadChoseWallet 恢复选中状态
            this.selectedWalletList = this.hadChoseWallet.map(w => ({...w}));
            this.walletPayPrice = this.selectedWalletList.reduce((sum, item) => sum + (item.wallet_use_price || 0), 0);
          }
        }
        this.$emit('update:show', n);
        this.$emit("onAlert");
      },
    },
    computed: {
      showWalletList(){
        let combineList = this.walletList.map(item => {
          let cur = this.selectedWalletList.find(ii => ii.wallet_virtual_number == item.wallet_virtual_number);
          if(cur) return Object.assign({}, item, cur);
          else item['wallet_use_price'] = 0;
          return item;
        })
        return combineList;
      },
      alert_bottom(){
        return this.fixedStyle({paddingBottom: 24, zIndex: 110})
      },
    },
    data(){
      return {
        xdDownDrawer: false,
        walletList: [],
        selectedWalletList: [],
        showName: "",
        totalAmount: "",
        needPayPrice: "",
        walletPayPrice: "",
        renderChecked: "renderChecked"
      }
    },
    created(){
      let callThis = this;
      // #ifdef MP
      callThis = this.$parent;
      // #endif

      callThis.getUserWalletList((res) => {
        console.log("getUserWalletList", res.walletList);
        this.walletList = res.list.map(item => {
          item.checked = false;
          return item;
        });
        this.showName = res.show_name;
        this.totalAmount = res.total_amount
        this.$emit("onInit", res.total_amount)

        if(this.defaultUseFirst){
          setTimeout(() => {
            this.handleChoseDefault();
          }, 300)
        }

      })
    },
    methods: {
      handleChoseDefault(afterCb){
        if(this.showWalletList.length===0) return;
        let item = this.showWalletList[0];
        if(item.amount <= 0) return;
        this.handleChange(true, item, () => {
          this.handleChose();
          if(afterCb) afterCb();
        }, true);
      },
      clearChecked(){
        this.walletPayPrice = 0;
        this.selectedWalletList = []
        this.handleChose();
      },
      handleChose(){
        let data = {
          walletPayPrice: this.walletPayPrice,
          selectedWalletList: this.selectedWalletList,
          needPayPrice: this.needPayPrice
        }
        this.$emit("onChose", data)
      },
      handleChange(flag, row, cb, hideLoading=false){
        console.log(flag);
        console.log(this.walletList);
        if(flag){
          let callThis = this;
          // #ifdef MP
          callThis = this.$parent;
          // #endif
          if(!hideLoading) this.$xdShowLoading({})
          callThis.useBindedWallet({
            wallet_type: row.wallet_type,
            wallet_nnid: row.wallet_nnid,
            customer_id: row.customer_id,
            selected_wallet_list_json: JSON.stringify(this.selectedWalletList),
          }, (res) => {
            this.$xdHideLoading();
            console.log("selected_wallet_list", res)
            let selected_wallet_list = res.selected_wallet_list;
            this.selectedWalletList = selected_wallet_list;
            this.needPayPrice = res.need_pay_price;
            this.walletPayPrice = res.wallet_total_use_price;
            this.renderChecked = Date.now();
            if(cb) cb();
          }, (err) => {
            this.$xdHideLoading();
            this.renderChecked = Date.now();
          });
        }else{
          this.selectedWalletList = this.selectedWalletList.filter(item => {
            return item.wallet_virtual_number != row.wallet_virtual_number
          })
          this.walletPayPrice = this.walletPayPrice - row.wallet_use_price;
          if(cb) cb();
          // this.$set(row, "wallet_use_price",  0);
        }
      },
      fixedStyle(options = {}, type = 'bottom') {
        let paddingBottom = options.paddingBottom || options.height || 0;
        if (options.paddingBottom) delete options.paddingBottom;
        if (options.height) delete options.height;
        let obj = Object.assign({}, {
          top: 0, left: 0, right: 0, bottom: 0, zIndex: 100,
        }, options);
        let style = 'position: fixed';
        style = `${style};left:${obj.left}rpx`;
        style = `${style};right:${obj.right}rpx`;
        style = `${style};z-index:${obj.zIndex}`;
        if (type === 'bottom') {
          let padding = (this.layoutInfo.bottomHeight + this.layoutInfo.footerHeight + paddingBottom) * this.$rpxNum;
          style = `${style}; padding-bottom:calc(${padding}px + constant(safe-area-inset-bottom));`;
          style = `${style}; padding-bottom:calc(${padding}px + env(safe-area-inset-bottom));`;
          style = `${style};bottom:0;`;
        }
        if (type === 'top') {
          style = `${style};top:${obj.top}rpx`;
        }
        return style;
      },
    }
  }
</script>

<style lang="less" scoped>

  .xd-wallet-chose{
    ::v-deep .xd-up-drawer__content{
      background-color: #F8F8F8;
    }
    .title{
      height: 100rpx;
      line-height: 100rpx;
      background:#F8F8F8;
      text-align: center;
      font-size: 32rpx;
      color: #333333;
    }
    .wallet_body_wrap{
      padding: 24rpx;
      padding-bottom: 150rpx;
    }
    .wallet_body{
      max-height: 70vh;
      overflow: auto;
      background-color: #FFFFFF;
      border-radius: 16rpx;
      .wallet_total{
        padding: 32rpx 48rpx;
        border-bottom: 1px solid #F2F2F2;
        ._title{
          color: #333333;
          font-size: 24rpx;
          font-weight: 400;
          margin-bottom: 12rpx;
        }
        ._money{
          color: #333333;
          font-size: 48rpx;
          font-weight: 500;
        }
      }
      .wallet_list{
        .wallet_item{
          display: flex;
          align-items: flex-start;
          justify-content: space-between;
          padding: 32rpx 48rpx;
          font-size: 28rpx;
          color: #333333;
          .label{
            display: flex;
            align-items: center;
            .label_tit{
              margin-right: 16rpx;
            }
            .label_sub{
              color: var(--g-theme-mainColor);
              font-size: 24rpx;
            }
            &_company{
              color: #999999;
              font-size: 24rpx;
              margin-top: 10rpx;
            }
          }
          .value{
            display: flex;
            align-items: center;
            .val_sub{
              color: #333333;
              margin-right: 24rpx;
              font-size: 24rpx;
              line-height: 40rpx;
              display: flex;
              .red{
                color: #FF7070;
                display: flex;
              }
            }
          }
        }
      }

    }
    .bottom_btn{
      position: fixed;
      width: 100%;
      padding-top: 24rpx;
      background: #FFFFFF;
      box-shadow: 0 0 0px 1px rgba(0, 0, 0, 0.1);
      transition: 500ms all;
      padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
      padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    }
  }
</style>