<template>
  <scroll-view
    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"
  >
    <wx-points-commit ref="wxPointsCommit"></wx-points-commit>
<!--    <authorize ref="authorize"></authorize>-->
    <view class="choice" v-if="custTypeId === 0">
      <view
        v-for="(item, index) in invoiceList"
        :key="index"
        :class="index + 1 == tabIndex ? 'actived' : ''"
        @click="invoice(index + 1)"
        >{{ item }}</view
      >
    </view>
    <view
      class="shanghaiClassify"
      :class="{
        blueClassify: custTypeId === 1,
        greenClassify: custTypeId === 2,
      }"
      v-else
    >
      <view
        :class="{ classifyItem: true, isChecked: tabIndex === index + 1 }"
        v-for="(item, index) in invoiceList"
        :key="index"
      >
        <view @click="invoice(index + 1)">{{ item }}</view>
      </view>
    </view>
    <view class="choice_select" v-if="custTypeId === 0"
      ><view :class="tabIndex == 1 ? 'choice_select_ews' : 'choice_select_ew'"
    /></view>
    <!-- 开票列表 -->
    <scroll-view class="choice_card" :style="{ height: height }">
      <view class="suggestion-list">
        <radio-group
          v-if="isJingAn"
          @change="radioChange"
          style="background-color: #f2f2f2"
        >
          <label
            class="uni-list-cell uni-list-cell-pd"
            @click="goToDeatil(item)"
            v-for="(item, index) in list"
            :key="index"
            :index="item.id"
            :activity="total - 1"
          >
            <view class="choice_card_item">
              <view class="choice_card_index choice_card_index1">
                <view v-if="tabIndex == 1"
                  >{{ item.orderno }}-{{ item.carno }}</view
                >
                <view v-else>{{ item.invoiceTitleName }}的停车发票</view>
                <view v-if="tabIndex == 1" style="color: #ed1c24"
                  >￥{{ (item.payfee / 100).toFixed(2) }}</view
                >
                <view v-else style="color: #ed1c24"
                  >￥{{ (item.invoiceAmount / 100).toFixed(2) }}</view
                >
              </view>
              <view
                class="choice_card_index choice_card_index2"
                v-if="tabIndex == 1"
                >{{ item.parkname }}</view
              >
              <view
                class="choice_card_index choice_card_index3"
                v-if="tabIndex == 1"
              >
                <view>入场时间: {{ item.entertime }}</view>
                <view
                  ><radio
                    color="#ED1C24"
                    :value="item.id"
                    :checked="index === current"
                /></view>
              </view>
              <view
                class="choice_card_index choice_card_index2"
                v-if="tabIndex == 1"
              >
                停车时长: {{ item.serviceMin | parkingTime }}
              </view>
              <view
                class="choice_card_index choice_card_index2"
                v-if="tabIndex == 2"
                >税号: {{ item.corporationTax }}</view
              >
              <view
                class="choice_card_index choice_card_index3"
                v-if="tabIndex == 2"
                style="padding-bottom: 20rpx"
              >
                <view
                  >开票时间:
                  {{ item.paperDrewDate ? item.paperDrewDate : '-' }}</view
                >
                <!-- 0：已提交申请(待开票) 1:开票中  2：开票完成 3：开票失败 -->
                <view
                  class="choice_card_status"
                  v-if="item.status === 2"
                  style="color: #8cc63f"
                >
                  开票完成
                  <image
                    class="arrow"
                    :src="arrowIcon"
                    mode="heightFix"
                    style="height: 40rpx"
                  ></image>
                </view>
                <view
                  class="choice_card_status"
                  v-else-if="item.status === 3"
                  style="color: #ed1c24"
                >
                  开票失败
                  <image
                    class="arrow"
                    :src="arrowIcon"
                    mode="heightFix"
                    style="height: 40rpx"
                  ></image>
                </view>
                <view class="choice_card_status" v-else style="color: #f7931e">
                  开票中
                  <image
                    class="arrow"
                    :src="arrowIcon"
                    mode="heightFix"
                    style="height: 40rpx"
                  ></image>
                </view>
              </view>
            </view>
          </label>
        </radio-group>
        <checkbox-group
          v-else
          @change="checkboxChange"
          style="background-color: #f2f2f2"
        >
          <label
            class="uni-list-cell uni-list-cell-pd"
            @click="goToDeatil(item)"
            v-for="(item, index) in list"
            :key="index"
            :index="item.id"
            :activity="total - 1"
          >
            <view class="choice_card_item">
              <view class="choice_card_index choice_card_index1">
                <view v-if="tabIndex == 1"
                  >{{ item.orderno }}-{{ item.carno }}</view
                >
                <view v-else>{{ item.invoiceTitleName }}的停车发票</view>
                <view v-if="tabIndex == 1" style="color: #ed1c24"
                  >￥{{ (item.payfee / 100).toFixed(2) }}</view
                >
                <view v-else style="color: #ed1c24"
                  >￥{{ (item.invoiceAmount / 100).toFixed(2) }}</view
                >
              </view>
              <view
                class="choice_card_index choice_card_index2"
                v-if="tabIndex == 1"
                >{{ item.parkname }}</view
              >
              <view
                class="choice_card_index choice_card_index3"
                v-if="tabIndex == 1"
              >
                <view>入场时间: {{ item.entertime }}</view>
                <view
                  ><checkbox
                    color="#ED1C24"
                    :value="item.id"
                    :checked="item.checkted"
                /></view>
              </view>
              <view
                class="choice_card_index choice_card_index2"
                v-if="tabIndex == 1"
              >
                停车时长: {{ item.serviceMin | parkingTime }}
              </view>
              <view
                class="choice_card_index choice_card_index2"
                v-if="tabIndex == 2"
                >税号: {{ item.corporationTax }}</view
              >
              <view
                class="choice_card_index choice_card_index3"
                v-if="tabIndex == 2"
                style="padding-bottom: 20rpx"
              >
                <view
                  >开票时间:
                  {{ item.paperDrewDate ? item.paperDrewDate : '-' }}</view
                >
                <!-- 0：已提交申请(待开票) 1:开票中  2：开票完成 3：开票失败 -->
                <view
                  class="choice_card_status"
                  v-if="item.status === 2"
                  style="color: #8cc63f"
                >
                  开票完成
                  <image
                    class="arrow"
                    :src="arrowIcon"
                    mode="heightFix"
                    style="height: 40rpx"
                  ></image>
                </view>
                <view
                  class="choice_card_status"
                  v-else-if="item.status === 3"
                  style="color: #ed1c24"
                >
                  开票失败
                  <image
                    class="arrow"
                    :src="arrowIcon"
                    mode="heightFix"
                    style="height: 40rpx"
                  ></image>
                </view>
                <view class="choice_card_status" v-else style="color: #f7931e">
                  开票中
                  <image
                    class="arrow"
                    :src="arrowIcon"
                    mode="heightFix"
                    style="height: 40rpx"
                  ></image>
                </view>
              </view>
            </view>
          </label>
        </checkbox-group>
        <view v-show="isLoadMore" :class="{ noData: !list.length }">
          <image :src="noData" v-if="!list.length" mode="widthFix"></image>
          <text v-if="!list.length">暂无数据</text>
          <uni-load-more :status="loadStatus" v-else></uni-load-more>
        </view>
        <!-- <view class="noData" v-if="!list.length">
                        <text>暂无数据</text>
                    </view> -->
      </view>
    </scroll-view>
    <view class="flewx" v-if="tabIndex == 1">
      <!-- <radio-group class="checkAll" @click="isCheckAll = !isCheckAll">
				<label>
					<radio style="transform: scale(0.7);position: relative;top: -2rpx;"
						color='#1FBB81' value="all" :checked="isCheckAll" /> 本页全选
				</label>
			</radio-group> -->
      <view class="priceBtn">
        <view
          >开票金额
          <text class="price">{{ (totalNum / 100).toFixed(2) }} 元</text></view
        >
        <view
          :class="{
            flewx_index3: true,
            blue_flewx_index3: custTypeId === 1,
            green_flewx_index3: custTypeId === 2,
          }"
          @click="goToInvoicing"
          >去开票</view
        >
      </view>
    </view>
  </scroll-view>
</template>

<script>
const app = getApp();
import arrowIcon from '../static/images/arrows.png';
import noData from '@/static/images/parkingReceipt-noData.png';
import { mapState } from 'vuex';
import authorize from '@/components/authorize/authorize.vue';
import MemberCacheTool from '@/utils/member-cache-tool.js';
import { REG_SOURCE } from '@/constants.js';
import CacheTool from '@/utils/cache-tool.js';
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: [],
      noids: [],
      totalNum: 0.0,
      options: null,
      preUrl: '',
      doneList: [],
      noneList: [],
    };
  },
  components: {
    authorize,
  },
  computed: {
    height() {
      return this.list.length ? 'auto' : '100%';
    },
    ...mapState({
      custTypeId: (state) => state.custTypeId,
    }),
    isJingAn() {
      let mallid = app.globalData.mallid;
      if (!mallid) {
        mallid = uni.getStorageSync('mallid');
      }
      return CacheTool.isJingAnMallid(mallid);
    },
  },
  onLoad(options) {
    // this.getInvoiceList();
    this.options = options;
    // 埋点初始化
    // this.parkingTrack = new this.$trackFactory('invoice_available_list', {});
    // this.parkingTrack.track(1);
    // this.parkingTrack.track(600);
  },
  onShow() {
    const member = uni.getStorageSync('member');
    if (member) {
      this.invoice(1);
    } else {
      const regSource = REG_SOURCE.PARKING;
      app.globalData.regSource = regSource;
      if (this.options?.regSource) {
        app.globalData.regSource = REG_SOURCE[this.options?.regSource];
      }
      if (this.options?.tpName) {
        app.globalData.tpName = this.options?.tpName;
      }
      this.$refs.authorize.login('/pages/parkingFee/parkingFee', () => {
        this.invoice(1);
      });
    }
  },
  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;
      if (e === 1) {
      //   this.parkingTrack.track(600, {
      //     tab_name: '未开票',
      //   });
      // } else {
      //   this.parkingTrack.track(600, {
      //     tab_name: '已开票',
      //   });
      }
      this.current = -1;
      this.ids = [];
      this.totalNum = '0.00';
      this.page = 1;
      this.list = [];
      this.getInvoiceList();
    },
    goToDeatil(item) {
      if (this.tabIndex === 2 && item.status === 2) {
        uni.navigateTo({
          url: '/pages/parkingFee/parkingReceipt/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.parkingTrack.track(100, {
      //   invoice_list_id: this.noids || [],
      //   result_num: this.noneList.length || 0,
      //   type: '停车',
      //   num: this.doneList.length || 0,
      //   total_amount: this.totalNum / 100,
      //   selected_invoice_list_id: this.ids,
      //   selected_invoice_list_price: this.priceList,
      // });
      // uni.setStorageSync('invoice_track', {
      //   invoice_list_id: this.noids || [],
      //   result_num: this.noneList.length || 0,
      //   type: '停车',
      //   num: this.doneList.length || 0,
      //   total_amount: this.totalNum / 100,
      //   selected_invoice_list_id: this.ids,
      //   selected_invoice_list_price: this.priceList,
      // });
      uni.navigateTo({
        url:
          '/pages/parkingFee/parkingReceipt/parkingApplication?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 = {
        page: this.page,
        pageSize: this.pagesize,
      };
      self.$md(data);
      const url =
        this.tabIndex === 1
          // ? 'api/1.0/invoice/myNotInvoicedList'
          // : 'api/1.0/invoice/myInvoicedList';
          ? 'temporary-parking-service/invoices/not-applied'
          :'temporary-parking-service/invoices/completed'
          
          
      uni.request({
        url: self.$baseURL + url,
        method: 'POST',
        data: data,
        header: JSON.parse(uni.getStorageSync('handleUser')),
        success: (res) => {
          if (res.data.code === 0) {
            // 埋点-列表加载成功
            // this.parkingTrack.track(700);
            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(e) {
      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) {
        let totalNum = 0;
        let ids = [];
        let noids = [];
        let doList = [];
        let noList = [];
        let pricelist = [];
        list.forEach((item) => {
          if (item.checked) {
            const payfee = item.payfee;
            totalNum += payfee;
            ids.push(item.id);
            doList.push(item);
            pricelist.push(JSON.stringify(item.payfee));
          } else {
            noids.push(item.id);
            noList.push(item);
          }
        });
        this.ids = ids;
        this.noids = noids;
        this.totalNum = totalNum;
        this.doneList = doList;
        this.noneList = noList;
        this.priceList = pricelist;
        // console.log('11:', this.doneList, this.noneList)
      }
    },
  },
};
</script>

<style lang="less" scoped>
@import '../../../styles/common.less';
.scroll-Y {
  width: 100%;
  display: flex;
  flex-direction: column;
  height: 100vh;
  // padding-bottom: 100rpx;
  background: #f2f2f2;
  .choice {
    width: 750rpx;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 30rpx;
    height: 78rpx;
    position: fixed;
    top: 0;
    left: 0;
    view {
      width: 30%;
      text-align: center;
      height: 78rpx;
      line-height: 78rpx;
    }
    .actived {
      color: #000000;
    }
  }
  .choice_select {
    width: 750rpx;
    height: 10rpx;
    background-color: #fff;
    position: fixed;
    top: 78rpx;
    left: 0;
    view {
      width: 70rpx;
      height: 4rpx;
      border-radius: 25%;
      background-color: #000000;
    }
    .choice_select_ews {
      transform: translateX(230rpx);
      transition-duration: 0.1s;
    }
    .choice_select_ew {
      transform: translateX(455rpx);
      transition-duration: 0.1s;
    }
  }
  .shanghaiClassify {
    position: fixed;
    width: 750rpx;
    z-index: 2;
  }
  .blueClassify {
    .colorClassify('blue');
  }
  .greenClassify {
    .colorClassify('green');
  }
  .choice_card {
    margin: 98rpx 20rpx 0rpx;
    width: 710rpx;
    // background-color: #fff;
    .choice_card_item {
      // border: 2rpx solid #ddd;
      padding: 10rpx 20rpx;
      margin: 20rpx 0;
      border-radius: 20rpx;
      background-color: #fff;
      .choice_card_index {
        // padding-top: 6rpx;
        padding-bottom: 10rpx;
        font-size: 24rpx;
        .choice_card_status {
          display: flex;
          align-items: center;
        }
      }
      .choice_card_index1 {
        display: flex;
        align-items: center;
        justify-content: space-between;
        border: 400;
        border-bottom: 1px solid #f8f8f8;
        padding: 10rpx 0;
        font-size: 28rpx;
        margin-bottom: 10rpx;
      }
      .choice_card_index2 {
        // padding-top: 20rpx;
        color: #bbbbbb;
      }
      .choice_card_index3 {
        display: flex;
        align-items: center;
        justify-content: space-between;
        color: #bbbbbb;
      }
      .choice_card_index4 {
        color: #bbbbbb;
        // padding-bottom: 20rpx;
      }
    }
  }
}
.suggestion-list {
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 15rpx;
}

.flewx {
  width: 100%;
  height: 100rpx;
  background-color: #fff;
  position: fixed;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  // padding-bottom: constant(safe-area-inset-bottom);
  // padding-bottom: env(safe-area-inset-bottom);
  padding-bottom: 20rpx;
  // .checkAll {
  // 	.checkboxItem {
  // 		position: relative;
  // 		top: -2rpx;
  // 	}
  // }
  .priceBtn {
    display: flex;
    align-items: center;
    margin-right: 20rpx;
    justify-content: space-around;
    .price {
      color: #ed1c24;
      font-size: 36rpx;
      margin: 0 10rpx;
    }
    .flewx_index3 {
      width: 150rpx;
      height: 70rpx;
      border-radius: 40rpx;
      text-align: center;
      font-size: 28rpx;
      line-height: 70rpx;
      color: #fff;
      background-image: linear-gradient(to right, #7e50a3, #433c7f);
      margin-left: 50rpx;
      margin-right: 30rpx;
    }
    .blue_flewx_index3 {
      .color-background-color('blue');
    }
    .green_flewx_index3 {
      .color-background-color('green');
    }
  }
}

.uni-input_type {
  width: 42rpx;
  height: 42rpx;
  margin-right: 10rpx;
  border: 1rpx solid #f2f2f2;
  border-radius: 50%;
  image {
    width: 40rpx;
    height: 40rpx;
  }
}
.noData {
  width: 100%;
  padding-top: 15%;
  text-align: center;
  background: #f2f2f2;
  margin: 0 auto;
  image {
    width: 200rpx;
    margin-bottom: 2%;
  }
  text {
    color: #999;
    display: block;
  }
}
</style>
