<template>
  <div
    class="scroll-Y"
    id="slideview"
    scroll-y
    lower-threshold="50"
    scroll-top="0"
    scroll-left="0"
    enable-flex="true"
    scroll-with-animation="false"
    enable-back-to-top="false"
    @scrolltolower="scrollLower"
  >
    <!--    <authorize ref="authorize"></authorize>-->
    <div class="choice" v-if="custTypeId === 0">
      <!-- <LoginDom></LoginDom> -->
      <div
        v-for="(item, index) in invoiceList"
        :key="index"
        :class="index + 1 === tabIndex ? 'actived' : ''"
        @click="invoice(index + 1)"
      >
        {{ item }}
      </div>
    </div>
    <div class="shanghaiClassify" v-else>
      <div
        :class="{ classifyItem: true, isChecked: tabIndex === index + 1 }"
        v-for="(item, index) in invoiceList"
        :key="index"
      >
        <div @click="invoice(index + 1)">{{ item }}</div>
      </div>
    </div>
    <div class="choice_select" v-if="custTypeId === 0">
      <div :class="tabIndex == 1 ? 'choice_select_ews' : 'choice_select_ew'" />
    </div>
    <!-- 开票列表 -->
    <scroll-view class="choice_card" :style="{ height: height }">
      <div class="suggestion-list">
        <van-checkbox-group v-model="ids" @change="checkboxChange">
          <label
            class="uni-list-cell uni-list-cell-pd"
            @click.stop="goToDeatil(item)"
            v-for="(item, index) in list"
            :key="index"
            :index="item.id"
            :activity="total - 1"
          >
            <div class="choice_card_item">
              <div class="carno-box">
                <div
                  :class="['carno', ids.indexOf(item.id) > -1 && 'active']"
                  v-if="tabIndex == 1"
                >
                  <span>{{ item.carno }}</span>
                </div>
                <div class="invoiceTitleName" v-else>
                  {{ item.invoiceTitleName }}的停车发票&nbsp;<van-icon
                    name="arrow"
                    color="#D8DAE0"
                  />
                </div>
                <div
                  :class="[
                    'payfee',
                    (ids.indexOf(item.id) > -1 || tabIndex == 2) && 'active',
                  ]"
                >
                  ￥{{
                    (
                      item[tabIndex == 1 ? 'payfee' : 'invoiceAmount'] / 100
                    ).toFixed(2)
                  }}
                </div>
              </div>
              <div class="line"></div>
              <!-- 未开票 -->
              <div class="my-not-invoiced-list" v-if="tabIndex == 1">
                <div class="left">
                  <div class="choice_card_index">{{ item.parkname }}</div>
                  <div class="choice_card_index">
                    订单号: {{ item.orderno }}
                  </div>
                  <div class="choice_card_index">
                    入场时间: {{ item.entertime }}
                  </div>
                  <div class="choice_card_index mb0">
                    停车时长: {{ item.serviceMin | parkingTime }}
                  </div>
                </div>
                <div class="right" @click.stop>
                  <van-checkbox
                    color="#ED1C24"
                    :name="item.id"
                    icon-size="20"
                    checked-color="#064C8A"
                  />
                </div>
              </div>
              <!-- 已开票 -->
              <div
                class="my-not-invoiced-list my-invoiced-list"
                v-if="tabIndex == 2"
              >
                <div class="left">
                  <div class="choice_card_index">
                    税号: {{ item.corporationTax }}
                  </div>
                  <div class="choice_card_index">
                    开票时间:
                    {{ item.paperDrewDate ? item.paperDrewDate : '-' }}
                  </div>
                  <!-- <div class="choice_card_index mb0">
                    停车时长: <span>{{ item.serviceMin | parkingTime }}</span>  _{{
                      item.serviceMin
                    }}
                  </div> -->
                </div>
                <div class="right">
                  <!-- 0：已提交申请(待开票) 1:开票中  2：开票完成 3：开票失败 -->
                  <div class="choice_card_status">
                    {{
                      ['已提交申请(待开票)', '开票中', '开票完成', '开票失败'][
                        item.status ? item.status : 1
                      ]
                    }}
                  </div>
                </div>
              </div>
            </div>
          </label>
        </van-checkbox-group>
        <div v-show="isLoadMore" :class="{ noData: !list.length }">
          <img :src="noData" v-if="!list.length" mode="widthFix" />
          <span v-if="!list.length">暂无数据</span>
          <div v-else class="no-more-data">没有更多了</div>
        </div>
      </div>
    </scroll-view>
    <div class="flewx" v-if="tabIndex == 1">
      <div class="priceBtn">
        <div>
          开票金额
          <span class="price">{{ (totalNum / 100).toFixed(2) }} 元</span>
        </div>
        <div
          :class="{
            flewx_index3: true,
            blue_flewx_index3: custTypeId === 1,
            green_flewx_index3: custTypeId === 2,
          }"
          @click="goToInvoicing"
        >
          去开票
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// const app = getApp()
const app = {};
import moment from 'moment';
import arrowIcon from '../static/images/arrows.png';
import noData from '@/static/images/parkingReceipt-noData.png';
import { mapState } from 'vuex';
import LoginDom from '@/components/Login/Login.vue';
// import authorize from '@/components/authorize/authorize.vue'
import MemberCacheTool from '@/utils/member-cache-tool.js';
import { REG_SOURCE } from '@/constants.js';
import uni from '@/utils/uniHooks';
import { myNotInvoicedList } from '../list';
import { wxToLoginCallback } from '@/utils/index';

export default {
  data() {
    return {
      globalData: app.globalData,
      picUrl: this.$picUrl,
      baseUrl: this.$baseURL,
      arrowIcon: arrowIcon,
      noData: noData,
      tabIndex: 1,
      invoiceList: ['未开票', '已开票'],
      list: [],
      isCheckTickets: [],
      total: 0,
      isLoadMore: false,
      loadStatus: 'loading',
      pagesize: 10,
      page: 1,
      current: -1,
      isCheckAll: 0,
      ids: [],
      totalNum: 0.0,
      options: null,
      preUrl: '',
    };
  },
  components: {
    // authorize,
    LoginDom,
  },
  computed: {
    height() {
      return this.list.length ? 'auto' : '100%';
    },
    ...mapState({
      custTypeId: (state) => state.custTypeId,
      groupId: (state) => state.groupId,
      openid: (state) => state.openid,
      mallId: (state) => state.mallId,
      kipUserId: (state) => state.kipUserId,
      userInfo: (state) => state.userInfo,
      member: (state) => state.member,
      mobile: (state) => state.mobile,
    }),
  },
  created() {
    // this.getInvoiceList();
    // this.options = options
    // 埋点本地化
    this.preUrl = uni.getStorageSync('previousUrl');
    uni.setStorageSync(
      'previousUrl',
      '/pages/parkingFee/parkingReceipt/parkingReceipt.vue'
    );
  },
  mounted() {
    // const member = uni.getStorageSync('member')
    setTimeout(() => {
      uni.setNavigationBarTitle({
        title: '停车发票',
      });
    }, 300);
    if (JSON.stringify(this.member) !== '{}') {
      this.invoice(1);
    } else {
      wxToLoginCallback('parkingReceipt', () => {
        this.$router.back();
      });
    }
  },
  watch: {},
  filters: {
    parkingTime(val) {
      const days = parseInt(val / 60 / 24);
      const hours = parseInt((val / 60) % 24);
      const minutes = parseInt(val % 60);
      if (days > 0) {
        return `${days}天 ${hours}小时 ${minutes}分钟`;
      }
      if (hours > 0) {
        return `${hours}小时 ${minutes}分钟`;
      }
      return `${minutes}分钟`;
    },
  },
  methods: {
    invoice(e) {
      this.tabIndex = e;
      this.current = -1;
      this.ids = [];
      this.totalNum = '0.00';
      this.page = 1;
      this.list = [];
      // 埋点
      const params = {
        redirect_url: '',
        type_tab: e == 1 ? 'UnInvoicedTab' : 'InvoicedTab',
      };
      this.sensorsClick('$ClickParkingReceiptTab', params);
      this.getInvoiceList();
    },
    // 埋点方法
    sensorsClick(eventName, params) {
      let optionsQuery = uni.getStorageSync('options_query');
      let fixedParams = {
          cta_itemno: '',
          cta_name: '',
          previous_url: this.preUrl || '',
          $brand_id: uni.getStorageSync('groupId'),
          $location: uni.getStorageSync('mallid'),
          $channel: optionsQuery.channel || '',
          // $utm_lbs: this.optionsQuery.utm_lbs || '',
          $utm_channel: optionsQuery.utm_channel || '',
          $utm_method: optionsQuery.utm_method || '',
          $utm_source: optionsQuery.utm_source || '',
          $utm_function: optionsQuery.utm_function || '',
          $utm_user: optionsQuery.utm_user || '',
        },
        finalParams = Object.assign(fixedParams, params);
      this.$sensors.track(eventName, finalParams);
    },
    goToDeatil(item) {
      if (this.tabIndex === 2 && item.status === 2) {
        this.$router.push({
          path: 'parkingInvoice?id=' + item.id,
        });
      }
    },
    goToInvoicing() {
      if (this.ids.length <= 0) {
        uni.showToast({
          title: '请选择您要开票的记录',
          icon: 'none',
        });
        return false;
      }
      if (this.totalNum <= 0) {
        uni.showToast({
          title: '请选择金额大于0的缴费记录',
          icon: 'none',
        });
        return false;
      }
      this.$router.push({
        path: 'parkingApplication',
        query: {
          ids: this.ids,
        },
      });
    },
    radioChange: function (evt) {
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].id === evt.detail.value) {
          this.current = i;
          this.ids = [this.list[i].id];
          this.totalNum = this.list[i].payfee;
          break;
        }
      }
    },
    scrollLower() {
      console.log('到底了........');
      if (!this.isLoadMore) {
        this.isLoadMore = true;
        this.page += 1;
        this.getInvoiceList();
      }
    },
    getInvoiceList() {
      const self = this;
      // const openId = MemberCacheTool.getOpenId(app)
      var data = {
        openId: this.openid,
        mallid: this.mallId,
        vipcode: this.member?.vipcode,
        page: this.page,
        pageSize: this.pagesize,
      };
      // console.log(273, data);
      // return;

      self.$md(data);
      const url =
        this.tabIndex === 1
          ? 'api/1.0/invoice/myNotInvoicedList'
          : 'api/1.0/invoice/myInvoicedList';
      uni.request({
        url: self.$baseURL + url,
        method: 'POST',
        data: data,
        header: JSON.parse(uni.getStorageSync('handleUser')),
        success: (res) => {
          console.log(379, res);
          // const res = {
          //   data: myNotInvoicedList
          // }
          if (res.data.code === 0) {
            if (res.data.data) {
              this.total = res.data.data.length;
              this.list = this.list.concat(res.data.data);
              // 返回数据量小于pagesize，则表示此为最后一页
              if (res.data.data.length < this.pagesize) {
                this.isLoadMore = true;
                this.loadStatus = 'nomore';
              } else {
                this.isLoadMore = false;
              }
            } else {
              this.isLoadMore = true;
              this.loadStatus = 'nomore';
            }
          } else {
            uni.showToast({
              title: res.data.msg,
              duration: 2000,
              icon: 'none',
            });
            this.isLoadMore = false;
            if (this.page > 1) {
              this.page -= 1;
            }
          }
        },
        fail: () => {
          uni.showToast({
            title: '服务器开小差了呢，请您稍后再试',
            icon: 'none',
          });
          this.isLoadMore = false;
          if (this.page > 1) {
            this.page -= 1;
          }
        },
      });
    },
    checkboxChange(ids) {
      console.log(423, ids);
      this.calculatePrice(ids);
      return;
      const itemId = e.detail.value;
      let list = this.list;
      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        if (itemId.includes(item.id)) {
          this.$set(item, 'checked', true);
        } else {
          this.$set(item, 'checked', false);
        }
      }
      this.calculatePrice(list);
    },
    calculatePrice(list) {
      if (list && list.length > 0) {
        this.totalNum = this.list.reduce((total, item) => {
          if (list.indexOf(item.id) > -1) {
            console.log(442, item.payfee);
            total = total + item.payfee;
          }
          return total;
        }, 0);
      } else {
        this.totalNum = 0;
      }
      /* console.log(439, this.list)
      return
      if (list && list.length > 0) {
        let totalNum = 0;
        let ids = [];
        list.forEach(item => {
          if (item.checked) {
            const payfee = item.payfee;
            totalNum += payfee;
            ids.push(item.id)
          }
        });
        this.ids = ids;
        this.totalNum = totalNum;
      } */
    },
  },
};
</script>

<style lang="less" scoped>
.scroll-Y {
  width: 100%;
  display: flex;
  flex-direction: column;
  height: 100vh;
  // padding-bottom: 100px;
  background: #f4f7ff;

  .choice {
    width: 750px;
    background-color: #fafbff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 30px;
    height: 88px;
    position: fixed;
    top: 0;
    left: 0;

    div {
      width: 30%;
      text-align: center;
      height: 78px;
      line-height: 78px;
    }

    .actived {
      color: #064c8a;
    }
  }

  .choice_select {
    width: 750px;
    height: 10px;
    background-color: #fafbff;
    position: fixed;
    top: 74px;
    left: 0;

    div {
      width: 64px;
      height: 4px;
      border-radius: 2px;
      background-color: #064c8a;
    }

    .choice_select_ews {
      transform: translateX(230px);
      transition-duration: 0.1s;
    }

    .choice_select_ew {
      transform: translateX(455px);
      transition-duration: 0.1s;
    }
  }

  .shanghaiClassify {
    position: fixed;
    width: 750px;
    z-index: 2;
  }

  .blueClassify {
    .colorClassify('blue');
  }

  .greenClassify {
    .colorClassify('green');
  }

  .choice_card {
    margin: 112px 20px 0px;
    width: 710px;

    // background-color: #fff;
    .choice_card_item {
      // border: 2px solid #ddd;
      background: #fafbff;
      border-radius: 4px;
      border: 1px solid #d8dae0;
      padding: 36px 30px 30px 30px;
      // margin: 20px 0;
      margin-bottom: 30px;
      // border-radius: 20px;
      // background-color: #fff;

      .carno-box {
        display: flex;
        justify-content: space-between;
        margin-bottom: 18px;

        .carno {
          font-size: 36px;
          font-weight: 600;
          color: #999999;
          line-height: 50px;
        }

        .payfee {
          font-size: 30px;
          font-weight: 600;
          color: #999999;
          line-height: 42px;
        }
        .active {
          color: #333333;
        }
      }

      .line {
        width: 100%;
        border-bottom: 1px solid #d8dae0;
        margin-bottom: 20px;
      }

      .my-not-invoiced-list {
        display: flex;
        justify-content: space-between;
        .left {
          flex: 1;
        }
        .right {
          flex: 0 0 40px;
          font-size: 40px;
          align-items: center;
          display: flex;
        }
      }
      .my-invoiced-list {
        align-items: flex-end;
        .right {
          flex: 0 0 150px;
          font-size: 30px;
          font-weight: 400;
          color: #064c8a;
          line-height: 42px;
        }
      }

      .choice_card_index {
        font-size: 28px;
        font-weight: 400;
        color: #999999;
        line-height: 40px;
        margin-bottom: 12px;
        &.mb0 {
          margin-bottom: 0;
        }
        .choice_card_status {
          display: flex;
          white-space: nowrap;
          align-items: center;
        }
      }

      .choice_card_index1 {
        display: flex;
        align-items: center;
        justify-content: space-between;
        //border: 400;
        border-bottom: 1px solid #f8f8f8;
        padding: 10px 0;
        font-size: 28px;
        margin-bottom: 10px;
      }

      .choice_card_index2 {
        // padding-top: 20px;
        color: #bbbbbb;
      }

      .choice_card_index3 {
        display: flex;
        align-items: center;
        justify-content: space-between;
        color: #bbbbbb;
      }

      .choice_card_index4 {
        color: #bbbbbb;
        // padding-bottom: 20px;
      }
    }
  }
}

.suggestion-list {
  display: flex;
  flex-direction: column;
  // background: #fff;
  border-radius: 15px;
}

.flewx {
  width: 100%;
  height: 150px;
  background-color: #fafbff;
  position: fixed;
  bottom: 0;
  display: flex;
  align-items: center;
  // justify-content: space-between;
  padding-bottom: 20px;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);

  // .checkAll {
  // 	.checkboxItem {
  // 		position: relative;
  // 		top: -2px;
  // 	}
  // }
  .priceBtn {
    width: 100%;
    padding: 0 30px;
    display: flex;
    align-items: center;
    margin-right: 20px;
    justify-content: space-between;
    font-size: 28px;
    font-weight: 400;
    color: #333333;

    .price {
      font-size: 36px;
      font-weight: 600;
      color: #333333;
      line-height: 50px;
    }

    .flewx_index3 {
      width: 150px;
      height: 70px;
      border-radius: 40px;
      text-align: center;
      font-size: 28px;
      line-height: 70px;
      color: #fff;
      background: #064c8a;
      border-radius: 45px;
      font-size: 34px;
      font-weight: 400;
      color: #ffffff;
    }

    .blue_flewx_index3 {
      .color-background-color('blue');
    }

    .green_flewx_index3 {
      .color-background-color('green');
    }
  }
}

.uni-input_type {
  width: 42px;
  height: 42px;
  margin-right: 10px;
  border: 1px solid #f2f2f2;
  border-radius: 50%;

  img {
    width: 40px;
    height: 40px;
  }
}

.noData {
  width: 100%;
  padding-top: 15%;
  text-align: center;
  // background: #f2f2f2;
  margin: 0 auto;

  img {
    width: 200px;
    margin-bottom: 2%;
  }

  span {
    color: #999;
    display: block;
  }
}

.no-more-data {
  margin-top: 40px;
  text-align: center;
  font-size: 29px;
  font-weight: 400;
  color: #999999;
  line-height: 41px;
}
</style>
