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

<script>
// const app = getApp()
const app = {};
import arrowIcon from '../static/images/arrows.png';
import { mapState } from 'vuex';
// import MemberCacheTool from '@/utils/member-cache-tool.js';
import uni from '@/utils/uniHooks';
import { getUrlParams } from '@/utils/index.js';
import { Dialog, Toast } from 'vant';

export default {
  data() {
    return {
      picUrl: this.$picUrl,
      globalData: app.globalData,
      arrowIcon: arrowIcon,
      isShow: false,
      isDefaultEMail: false,
      ids: [],
      condition: {
        // openid: this.openid,
        // groupId: this.groupId,
        // vipcode: this.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,
    };
  },
  created() {
    // const options = this.$route.query;
    // console.log('===>onLoad', options);
    // this.pageOptions = options;
    // 埋点本地化
    this.preUrl = uni.getStorageSync('previousUrl');
    uni.setStorageSync(
      'previousUrl',
      '/pages/parkingFee/parkingReceipt/parkingApplication.vue'
    );
  },
  mounted() {
    // console.log(253, this.ids);
    setTimeout(() => {
      uni.setNavigationBarTitle({
        title: '发票申请',
      });
    }, 300);
    // console.clear();
    const query = getUrlParams();
    // console.log('是否重新回到改页面', this.pageOptions);
    // console.log('是否重新回到改页面', query);
    // console.log(260, this.$route.query);
    this.pageOptions = query;
    if (this.pageOptions) {
      const options = this.pageOptions;
      // console.log('===>onShow', options);
      // console.log('===>onShow', options.ids);

      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 =
            typeof ids === 'string'
              ? ids.indexOf('[') > -1
                ? JSON.parse(ids)
                : [ids]
              : ids;
        }
        this.orderQuantity = this.ids.length;
        // console.log('获取订单信息');
        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,
      groupId: (state) => state.groupId,
      openid: (state) => state.openid,
      mallId: (state) => state.mallId,
      kipUserId: (state) => state.kipUserId,
      userInfo: (state) => state.userInfo,
      member: (state) => state.member,
    }),
  },
  methods: {
    changeShowMore() {
      this.isShow = !this.isShow;
    },
    changeDefaultEMail() {
      this.isDefaultEMail = !this.isDefaultEMail;
    },
    changeHeader() {
      this.$router.push({
        path: 'parkingChooseHeader?ids=' + this.ids,
      });
    },
    gotoDetail() {
      this.$store.commit('setTempParkingOrder', this.parkingOrder);
      this.$router.push({
        path: 'parkingOrderDetail?useParkingOrderCache=true',
      });
      // this.$router.push({
      //   path:
      //     '/pages/parkingFee/parkingFeeDetailSuccess?orderNo=' +
      //     this.orderInfo.orderNo,
      // })
    },
    // 查询全部抬头列表信息
    getInvoiceTitle() {
      const self = this;
      const params = {
        vipcode: this.member?.vipcode,
      };
      self.$md(params);
      // console.log(265, '开票信息', params);
      // console.log(
      //   265,
      //   '开票信息 path: ',
      //   self.$baseURL + 'api/1.0/invoiceTitle/page'
      // );
      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',
            // });
            Toast({
              message: res.data.msg,
            });
          }
        },
        fail: () => {
          Toast({
            message: '服务器开小差了呢，请您稍后再试',
          });
          /* uni.showToast({
            title: '服务器开小差了呢，请您稍后再试',
            icon: 'none',
          }); */
        },
      });
    },
    // 根据选中的停车缴费记录id获取详情信息
    getParkOrderInfo() {
      // 如果当前是活动开票的话，则不差详情
      if (this.type) return;
      const self = this;
      // console.log('根据选中的停车缴费记录id获取详情信息', this.ids);
      self.$md(this.ids);
      // console.log(
      //   'getParkOrderInfo',
      //   self.$baseURL + 'api/1.0/invoice/myParkOrderListByIds'
      // );
      // return;
      uni.request({
        url: self.$baseURL + 'api/1.0/invoice/myParkOrderListByIds',
        method: 'POST',
        data: typeof this.ids === 'string' ? [this.ids] : this.ids,
        header: JSON.parse(uni.getStorageSync('handleUser')),
        success: (res) => {
          if (res.data.code === 0) {
            const datas = res.data.data;
            console.log('387387387387387387387获取详情信息', 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',
            }); */
            Toast({
              message: res.data.msg,
            });
          }
        },
        fail: () => {
          /* uni.showToast({
            title: '服务器开小差了呢，请您稍后再试',
            icon: 'none',
          }); */
          Toast({
            message: '服务器开小差了呢，请您稍后再试',
          });
        },
      });
    },
    // 获取用户邮箱信息
    getInvoiceEmailInfo() {
      const self = this;
      // const openId = MemberCacheTool.getOpenId(app);
      var data = {
        openid: this.openId,
        groupId: this.groupId,
        vipcode: this.member?.vipcode,
      };
      self.$md(data);
      // console.log(
      //   '获取用户邮箱信息',
      //   self.$baseURL + 'api/1.0/invoice/getInvoiceEmailInfo'
      // );
      // console.log(421, 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',
            }); */
            Toast({
              message: res.data.msg,
            });
          }
        },
        fail: () => {
          Toast({
            title: '服务器开小差了呢，请您稍后再试',
          });
          /* uni.showToast({
            title: '服务器开小差了呢，请您稍后再试',
            icon: 'none',
          }); */
        },
      });
    },
    submit() {
      const self = this;
      if (!self.condition.mailbox) {
        /* uni.showToast({
          title: '请输入电子邮箱地址',
          duration: 2000,
          icon: 'none',
        }); */
        Toast({
          message: '请输入电子邮箱地址',
        });
        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;

      params.openid = this.openid;
      params.groupId = this.groupId;
      params.vipcode = this.member?.vipcode;
      // console.log('提交发票请求的入参', params);
      self.$md(params);
      if (self.isSubmitFlag) {
        // 勾选默认邮箱埋点
        if (self.isDefaultEMail) {
          self.sensorsClick('$SetDefaultEmail', {
            redirect_path: '',
            mailbox: self.condition.mailbox,
          });
        }
        self.isSubmitFlag = false;
        console.log(488, '前往开票', params);
        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);
            if (res.data.code === 0) {
              // 因为合并开票接口中无法判断是否是一个CO（一个发票id可以直接进发票详情）还是两个CO，所以统一返回到发票列表页面 ？
              this.$router.replace({
                path: 'parkingReceipt',
              });
              // this.$router.replace({
              //   path:
              //     '/pages/parkingFee/parkingReceipt/parkingInvoiceApply?id=' +
              //     res.data.data.id,
              // })
            } else {
              /* uni.showToast({
                title: res.data.msg,
                duration: 2000,
                icon: 'none',
              }); */
              Toast({
                message: res.data.msg,
              });
            }
          },
          fail: () => {
            self.isSubmitFlag = true;
            /* uni.showToast({
              title: '服务器开小差了呢，请您稍后再试',
              icon: 'none',
            }); */
            oast({
              message: '服务器开小差了呢，请您稍后再试',
            });
          },
        });
      }
    },
    // 埋点方法
    sensorsClick(eventName, params) {
      let optionsQuery = uni.getStorageSync('options_query');
      let fixedParams = {
          cta_itemno: '',
          cta_name: '',
          previous_path: this.preUrl || '',
          $location: uni.getStorageSync('mallid'),
          $brand_id: uni.getStorageSync('groupId'),
          $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);
    },
  },
};
</script>

<style lang="less" scoped>
@import '../../../styles/common.less';

.scroll-Y {
  width: 100%;
  display: flex;
  flex-direction: column;
  // height: 88vh;
  background-color: #f4f7ff;
  // padding: 30px 20px;
  box-sizing: border-box;

  .push-box {
    padding: 30px 20px;
    width: 750px;
    box-sizing: border-box;
    margin-bottom: 180px;
  }

  .choose-invoice-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    // padding: 20px 30px;
    padding: 32px;
    font-size: 28px;
    background: #fafbff;
    border: 1px solid #d8dae0;
    margin-bottom: 24px;
    border-radius: 4px;

    .invoice-header-info {
      flex: 1;

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

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

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

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

  .part {
    // background-color: #ffffff;

    background: #fafbff;
    // padding-left: 30px;
    margin-bottom: 20px;
    border-radius: 4px;
    padding: 30px;
    border: 1px solid #d8dae0;

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

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

      .part-item-value {
        flex: 1;
        color: #999;
        text-align: right;
        display: flex;
        align-items: center;
        .van-field__control {
          text-align: right;
        }
      }
    }

    .is-show-more {
      .part-item {
        padding-top: 32px;
      }
    }

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

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

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

    .default-email {
      justify-content: flex-start;
      color: #999999;
      margin-top: 20px;
      // font-size: 28PX;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #999999;
      padding-bottom: 0;
      .text {
        font-size: 28px;
        font-weight: 400;
        color: #999999;
        line-height: 40px;
      }
      // line-height: 80PX;
      // /deep/ .van-checkbox__icon {
      //   font-size: 25PX;
      // }
      // /deep/ .van-checkbox__label {
      //   line-height: 80PX;
      // }
    }
  }

  .top {
    padding-top: 20px;
    padding-bottom: 0 !important;
  }

  .middle {
    // padding: 20px 0;

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

    .purple {
      color: #064c8a;
    }
  }

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

  .textarea-remark {
    margin-bottom: 20px;

    > textarea {
      background-color: #fafbff;
      width: 100%;
      padding: 32px;
      // padding: 10px 20px;
      border-radius: 4px;
      box-sizing: border-box;

      border-color: #d8dae0;
    }
  }

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

  .lines {
    border-bottom: 1px solid #d8dae0;
  }

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

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

  .header-name {
    padding: 0 !important;
    border: unset !important;
  }
}
.push-btn {
  width: 100%;
  height: 170px;
  background-color: #fff;
  // padding: 0 41px;
  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 20px 0 hsla(0, 6%, 58%, 0.6);
  -moz-box-shadow: 0 0 20px 0 hsla(0, 6%, 58%, 0.6);
  // width: 100%;
  // padding: 20px 0;
  // position: fixed;
  // bottom: 0px;
  // height: 110px;
  // 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 20px 0 hsla(0, 6%, 58%, 0.6);
  // -moz-box-shadow: 0 0 20px 0 hsla(0, 6%, 58%, 0.6);

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

  .push-again-btn {
    // background-image: linear-gradient(to right, #7d4ea1, #40397c);
    background: #064c8a;
  }

  .blue-push-again-btn {
    .color-background-color('blue');
  }

  .green-push-again-btn {
    .color-background-color('green');
  }

  .disable-btn {
    background-color: #bdbdbd;
  }
}
</style>
