<template>
  <scroll-view class="scroll-Y" scroll-y>
    <wx-points-commit ref="wxPointsCommit"></wx-points-commit>

    <scroll-view class="push-box">
      <view class="choose-invoice-header lines" @click="changeHeader">
        <view class="invoice-header-info" v-if="headerInfo.invoiceTitleName">
          <view
            class="invoice-header-name"
            :class="headerInfo.invoiceTitleType == 1 ? 'header-name' : ''"
          >
            <view>
              {{ headerInfo.invoiceTitleName }}
              <text class="isDefault" v-if="headerInfo.setDefault == 1"
                >默认</text
              >
            </view>
            <image
              class="invoice-header-arrow"
              :src="arrowIcon"
              mode="widthFix"
            ></image>
          </view>
          <view v-if="headerInfo.invoiceTitleType == 0" class="duty-paragraph"
            >税号：{{ headerInfo.corporationTax }}</view
          >
        </view>
        <view class="invoice-header-info" v-else>
          <view class="invoice-header-name">
            <view>请选择发票抬头</view>
            <image
              class="invoice-header-arrow"
              :src="arrowIcon"
              mode="widthFix"
            ></image>
          </view>
          <view class="duty-paragraph">未选择发票抬头</view>
        </view>
      </view>
      <view class="tab-header" v-if="headerInfo.invoiceTitleName"
        >发票详情</view
      >
      <view class="part" v-if="headerInfo.invoiceTitleName">
        <view class="invoice-header">
          <!-- <view class="part-item">
          			<text class="part-item-key">开票订单号</text>
          			<text class="part-item-value">{{ orderInfo.orderNo }}</text>
          		</view> -->
          <view class="part-item">
            <text class="part-item-key">发票类型</text>
            <text class="part-item-value">增值税普通发票</text>
          </view>
          <view class="part-item">
            <text class="part-item-key">抬头类型</text>
            <text class="part-item-value">{{
              headerInfo.invoiceTitleType === 0 ? '单位' : '个人/非企业单位'
            }}</text>
          </view>
          <view
            class="part-item"
            :class="headerInfo.invoiceTitleType == 1 ? 'header-name' : ''"
          >
            <text class="part-item-key">抬头名称</text>
            <text class="part-item-value">{{
              headerInfo.invoiceTitleName
            }}</text>
          </view>
          <view
            class="part-item lines"
            v-if="headerInfo.invoiceTitleType === 0"
          >
            <text class="part-item-key">公司税号</text>
            <text class="part-item-value">{{ headerInfo.corporationTax }}</text>
          </view>
        </view>
        <view class="invoice-more" v-if="headerInfo.invoiceTitleType === 0">
          <view class="tab-title show-more" @click="changeShowMore">
            <text class="c">更多信息</text>
            <!--  :class="!isShowMore ? 'toBottom' : 'toRight'" -->
            <view class="arrow-box">
              <image :src="arrowIcon" mode="widthFix"></image>
            </view>
          </view>
          <view class="is-show-more" v-if="isShow">
            <view class="part-item">
              <text class="part-item-key">公司地址</text>
              <text class="part-item-value">{{
                headerInfo.companyAddress
              }}</text>
            </view>
            <view class="part-item">
              <text class="part-item-key">公司电话</text>
              <text class="part-item-value">{{ headerInfo.companyTel }}</text>
            </view>
            <view class="part-item">
              <text class="part-item-key">开户银行</text>
              <text class="part-item-value">{{ headerInfo.depositBank }}</text>
            </view>
            <view class="part-item top">
              <text class="part-item-key">开户账户</text>
              <text class="part-item-value">{{
                headerInfo.accountNumber
              }}</text>
            </view>
          </view>
        </view>
      </view>
      <view class="part middle">
        <view class="part-item lines">
          <text class="part-item-key">总金额</text>
          <text class="part-item-value"
            ><text class="purple">{{ invoiceAmount }} 元</text></text
          >
        </view>
        <view class="part-item top" v-if="type == ''">
          <text class="part-item-key"
            >共<text class="purple">{{ orderQuantity }}笔</text>缴费记录</text
          >
          <view class="part-item-value" @click="gotoDetail">
            <text>查看详情</text>
            <image
              class="invoice-header-arrow"
              :src="arrowIcon"
              mode="widthFix"
            ></image>
          </view>
        </view>
      </view>
      <view class="tab-header">接收方式</view>
      <view class="part footer">
        <view class="part-item lines">
          <text class="part-item-key">电子邮箱</text>
          <view class="part-item-value">
            <!-- sota_xu@hafengkeji.com -->
            <input
              type="text"
              placeholder="请输入电子邮箱"
              v-model="condition.mailbox"
            />
          </view>
        </view>
        <view class="part-item default-email top" @click="changeDefaultEMail">
          <label>
            <radio
              style="transform: scale(0.7); position: relative; top: -2rpx"
              color="#ED1C24"
              value="all"
              :checked="isDefaultEMail"
            />
            保存电子邮箱为默认邮箱
          </label>
        </view>
      </view>
      <view class="tab-header">备注</view>
      <view class="textarea-remark">
        <textarea
          placeholder-style="color:#999999"
          placeholder="选填"
          v-model="condition.remark"
        />
      </view>
    </scroll-view>
    <view class="push-btn">
      <view
        v-if="headerInfo.invoiceTitleName"
        :class="{
          btn: true,
          'push-again-btn': true,
          'blue-push-again-btn': custTypeId === 1,
          'green-push-again-btn': custTypeId === 2,
        }"
        @click="submit"
        >提交</view
      >
      <view v-else class="btn disable-btn" disabled>请选择发票抬头</view>
    </view>
  </scroll-view>
</template>

<script>
const app = getApp();
import arrowIcon from '../static/images/arrows.png';
import { mapState } from 'vuex';
import MemberCacheTool from '@/utils/member-cache-tool.js';
export default {
  data() {
    return {
      picUrl: this.$picUrl,
      globalData: app.globalData,
      arrowIcon: arrowIcon,
      isShow: false,
      isDefaultEMail: false,
      ids: [],
      condition: {
        openid: MemberCacheTool.getOpenId(app),
        groupId: app.globalData.groupId,
        vipcode: app.globalData.member.vipcode,
        invoiceName: '', // 否|发票名称
        invoiceCategory: 0, // 发票类型 0：停车缴费  1:活动
        invoiceType: 0, // 发票类型：0:增值税普通电子发票
        remark: '',
        invoiceTitleId: 0, // long|发票抬头id
        ids: [], // 被选中的缴费记录id
        isDefaultEmail: '1', // 是|邮箱是否默认 0：否 1：是
        mailbox: '',
      },
      headerInfo: {},
      // 总金额，单位分
      invoiceAmount: 0,
      orderInfo: {},
      type: '', // 当前是活动还是停车
      isSubmitFlag: true, // 发票提交申请的flag,
      pageOptions: null,
      preUrl: '',
      orderQuantity: 0,
      parkingOrder: null,
    };
  },
  onLoad(options) {
    console.log('===>onLoad', options);
    this.pageOptions = options;
    // 埋点初始化
    this.parkingTrack = new this.$trackFactory('invoice_apply', {});
    this.parkingTrack.track(1);
    // 埋点本地化
    this.invoice_track = uni.getStorageSync('invoice_track');
    // console.log('this.invoice_track::::', this.invoice_track)
    this.preUrl = uni.getStorageSync('previousUrl');
    uni.setStorageSync(
      'previousUrl',
      '/pages/parkingFee/parkingReceipt/parkingApplication.vue'
    );
  },
  onShow() {
    if (this.pageOptions) {
      const options = this.pageOptions;
      console.log('===>onShow', options);
      if (options.type && options.money) {
        this.type = options.type;
        this.invoiceAmount = options.money;
      }
      if (options.ids) {
        const ids = options.ids;
        if (ids.indexOf(',') > -1) {
          this.ids = ids.split(',');
        } else {
          this.ids = [ids];
        }
        this.orderQuantity = this.ids.length;
        this.getParkOrderInfo();
        this.getInvoiceEmailInfo();
      }
      if (options.header) {
        if (typeof options.header == 'string') {
          this.headerInfo = JSON.parse(options.header);
        } else if (typeof options.header == 'object') {
          this.headerInfo = options.header;
        }
      } else {
        this.getInvoiceTitle();
      }
    }
  },
  computed: {
    ...mapState({
      custTypeId: (state) => state.custTypeId,
    }),
  },
  methods: {
    changeShowMore() {
      this.isShow = !this.isShow;
    },
    changeDefaultEMail() {
      this.isDefaultEMail = !this.isDefaultEMail;
    },
    changeHeader() {
      uni.navigateTo({
        url:
          '/pages/parkingFee/parkingReceipt/parkingChooseHeader?id=' +
          this.ids[0],
      });
    },
    gotoDetail() {
      this.$store.commit('setTempParkingOrder', this.parkingOrder);
      uni.navigateTo({
        url: '/pages/parkingFee/parkingReceipt/parkingOrderDetail?useParkingOrderCache=true',
      });
      // uni.navigateTo({
      //   url:
      //     '/pages/parkingFee/parkingFeeDetailSuccess?orderNo=' +
      //     this.orderInfo.orderNo,
      // })
    },
    // 查询全部抬头列表信息
    getInvoiceTitle() {
      const self = this;
      const params = {
        vipcode: this.globalData.member.vipcode,
      };
      self.$md(params);
      uni.request({
        url: self.$baseURL + 'api/1.0/invoiceTitle/page',
        method: 'GET',
        data: params,
        header: JSON.parse(uni.getStorageSync('handleUser')),
        success: (res) => {
          // console.log(res.data)
          if (res.data.code === 0) {
            const list = res.data.data;
            let currentIndex = 0;
            list.map((item, index) => {
              if (item.setDefault == 1) currentIndex = index;
            });
            const headerInfo = list[currentIndex] || {};
            self.headerInfo = headerInfo;
            console.log('发票抬头--', self.headerInfo);
          } else {
            uni.showToast({
              title: res.data.msg,
              duration: 2000,
              icon: 'none',
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '服务器开小差了呢，请您稍后再试',
            icon: 'none',
          });
        },
      });
    },
    // 根据选中的停车缴费记录id获取详情信息
    getParkOrderInfo() {
      // 如果当前是活动开票的话，则不差详情
      if (this.type) return;
      const self = this;
      self.$md(this.ids);
      uni.request({
        url: self.$baseURL + 'api/1.0/invoice/myParkOrderListByIds',
        method: 'POST',
        data: this.ids,
        header: JSON.parse(uni.getStorageSync('handleUser')),
        success: (res) => {
          if (res.data.code === 0) {
            const datas = res.data.data;
            // console.log('获取详情信息', datas)
            self.parkingOrder = datas;
            self.invoiceAmount = (datas.invoiceAmount / 100).toFixed(2);
            self.orderInfo = datas.list[0];
          } else {
            uni.showToast({
              title: res.data.msg,
              duration: 2000,
              icon: 'none',
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '服务器开小差了呢，请您稍后再试',
            icon: 'none',
          });
        },
      });
    },
    // 获取用户邮箱信息
    getInvoiceEmailInfo() {
      const self = this;
      const openId = MemberCacheTool.getOpenId(app);
      var data = {
        openid: openId,
        groupId: app.globalData.groupId,
        vipcode: app.globalData.member.vipcode,
      };
      self.$md(data);
      uni.request({
        url: self.$baseURL + 'api/1.0/invoice/getInvoiceEmailInfo',
        method: 'POST',
        data: data,
        header: JSON.parse(uni.getStorageSync('handleUser')),
        success: (res) => {
          if (res.data.code === 0) {
            console.log('获取用户邮箱信息', res.data);
            if (res.data.data) {
              this.isDefaultEMail = true;
              this.condition.mailbox = res.data.data;
            } else {
              this.isDefaultEMail = false;
              this.condition.mailbox = '';
            }
          } else {
            uni.showToast({
              title: res.data.msg,
              duration: 2000,
              icon: 'none',
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '服务器开小差了呢，请您稍后再试',
            icon: 'none',
          });
        },
      });
    },
    submit() {
      const self = this;
      if (!self.condition.mailbox) {
        uni.showToast({
          title: '请输入电子邮箱地址',
          duration: 2000,
          icon: 'none',
        });
        return false;
      }
      // const re = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
      // if (re.test(self.condition.mailbox)) {
      //     uni.showToast({
      //         title: '电子邮箱格式有误，请输入正确的电子邮箱',
      //         duration: 2000,
      //         icon: 'none'
      //     });
      //     return false;
      // }
      if (self.type && self.type == 'activity') {
        self.condition.invoiceCategory = 1;
      }
      const params = self.condition;
      params.ids = self.ids;
      params.isDefaultEmail = self.isDefaultEMail ? '1' : '0';
      params.invoiceTitleId = self.headerInfo.id;
      console.log('params::::', params);
      // console.log('提交发票请求的入参', params);
      self.$md(params);
      if (self.isSubmitFlag) {
        self.isSubmitFlag = false;
        uni.request({
          url: self.$baseURL + 'api/1.0/invoice/addMyInvoiceInfo',
          method: 'POST',
          data: params,
          header: JSON.parse(uni.getStorageSync('handleUser')),
          success: (res) => {
            console.log('提交发票请求', res.data);
            this.parkingTrack.track(100, {
              type: '停车',
              selected_invoice_list_id: params.ids,
              selected_invoice_list_price:
                this.invoice_track.selected_invoice_list_price,
              num: this.invoice_track.num,
              title_type: this.headerInfo.invoiceTitleType === 0 ? 2 : 1,
              detail: `${this.headerInfo.invoiceTitleName},${this.headerInfo.corporationTax}`,
              receive_email: this.condition.mailbox,
            });
            if (res.data.code === 0) {
              this.parkingTrack.track(200);
              // 因为合并开票接口中无法判断是否是一个CO（一个发票id可以直接进发票详情）还是两个CO，所以统一返回到发票列表页面
              uni.redirectTo({
                url: '/pages/parkingFee/parkingReceipt/parkingReceipt',
              });
            } else {
              this.parkingTrack.track(400);
              uni.showToast({
                title: res.data.msg,
                duration: 2000,
                icon: 'none',
              });
            }
          },
          fail: () => {
            this.parkingTrack.track(400);
            self.isSubmitFlag = true;
            uni.showToast({
              title: '服务器开小差了呢，请您稍后再试',
              icon: 'none',
            });
          },
        });
      }
    },
  },
};
</script>

<style lang="less" scoped>
@import '../../../styles/common.less';
.scroll-Y {
  width: 100%;
  display: flex;
  flex-direction: column;
  // height: 88vh;
  background-color: #f1f1f1;
  // padding: 30rpx 20rpx;
  box-sizing: border-box;
  .push-box {
    padding: 30rpx 20rpx;
    width: 750rpx;
    box-sizing: border-box;
    margin-bottom: 180rpx;
  }
  .choose-invoice-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    // padding: 20rpx 30rpx;
    padding: 32rpx;
    font-size: 28rpx;
    background-color: #ffffff;
    margin-bottom: 20rpx;
    border-radius: 20rpx;

    .invoice-header-info {
      flex: 1;

      .invoice-header-name {
        color: #333333;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 32rpx;
        border-bottom: 1px solid #f8f8f8;

        .isDefault {
          color: #8cc63f;
          border: 1px solid #8cc63f;
          margin-left: 30rpx;
          border-radius: 20rpx;
          display: inline-block;
          padding: 0 21rpx;
        }
      }

      .duty-paragraph {
        color: #999;
        margin-top: 32rpx;
      }
    }
  }

  .tab-header {
    color: #808080;
    padding: 10rpx 20rpx 20rpx;
  }

  .part {
    background-color: #ffffff;
    // padding-left: 30rpx;
    margin-bottom: 25rpx;
    border-radius: 20rpx;
    padding: 32rpx;

    .part-item {
      font-size: 28rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 32rpx;

      .part-item-key {
        color: #333333;
        min-width: 146rpx;
      }

      .part-item-value {
        color: #999;
        text-align: right;
        display: flex;
        align-items: center;
      }
    }
    .is-show-more {
      .part-item {
        padding-top: 32rpx;
      }
    }

    .tab-title {
      color: #676767;
      padding-top: 30rpx;
    }

    .show-more {
      display: flex;
      justify-content: space-between;
      align-content: center;
      // padding-right: 30rpx;

      .arrow-box {
        // transform: rotate(90deg);
        // transition-duration:0.1s;
        > image {
          width: 30rpx;
        }
      }
    }

    .default-email {
      justify-content: flex-start;
      color: #999999;
    }
  }

  .top {
    padding-top: 32rpx;
    padding-bottom: 0 !important;
  }

  .middle {
    // padding: 20rpx 0;

    > .part-item {
      background-color: #ffffff;
      // padding-left: 30rpx;
    }

    .purple {
      color: #ed1c24;
    }
  }

  .footer {
    // padding-top: 20rpx;
    border-radius: 20rpx;
  }

  .textarea-remark {
    margin-bottom: 20rpx;
    > textarea {
      background-color: #fff;
      width: 100%;
      padding: 32rpx;
      // padding: 10rpx 20rpx;
      border-radius: 20rpx;
      box-sizing: border-box;
    }
  }

  .push-btn {
    width: 100%;
    height: 170rpx;
    background-color: #fff;
    // padding: 0 41rpx;
    position: fixed;
    bottom: 0;
    z-index: 999;
    box-sizing: border-box;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    box-shadow: 0 0 10px 0 hsla(0, 6%, 58%, 0.6);
    -webkit-box-shadow: 0 0 20rpx 0 hsla(0, 6%, 58%, 0.6);
    -moz-box-shadow: 0 0 20rpx 0 hsla(0, 6%, 58%, 0.6);
    // width: 100%;
    // padding: 20rpx 0;
    // position: fixed;
    // bottom: 0rpx;
    // height: 110rpx;
    // padding-bottom: constant(safe-area-inset-bottom);
    // padding-bottom: env(safe-area-inset-bottom);
    // box-shadow: 0 0 10px 0 hsla(0, 6%, 58%, 0.6);
    // -webkit-box-shadow: 0 0 20rpx 0 hsla(0, 6%, 58%, 0.6);
    // -moz-box-shadow: 0 0 20rpx 0 hsla(0, 6%, 58%, 0.6);

    .btn {
      // margin: 20rpx 60rpx;
      color: #ffffff;
      border-radius: 50rpx;
      text-align: center;
      // padding: 20rpx 0;
      height: 80rpx;
      line-height: 80rpx;
      width: 90%;
      margin: 0 auto;
      margin-top: 25rpx;
    }

    .push-again-btn {
      background-image: linear-gradient(to right, #7d4ea1, #40397c);
    }
    .blue-push-again-btn {
      .color-background-color('blue');
    }
    .green-push-again-btn {
      .color-background-color('green');
    }

    .disable-btn {
      background-color: #bdbdbd;
    }
  }

  .invoice-header-arrow {
    width: 30rpx;
  }

  .lines {
    border-bottom: 2rpx solid #ececec;
  }

  .toBottom {
    transform: rotate(90deg);
    transition-duration: 0.1s;
  }

  .toRight {
    transform: rotate(-90deg);
    transition-duration: 0.1s;
  }
  .header-name {
    padding: 0 !important;
    border: unset !important;
  }
}
</style>
