
// 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';
import { invoicesDetail, submitInvoice, invoiceEmails, invoicesOrders } from '@/api/parking';

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: 'GVATE', // 发票类型：gvat-增值税普通发票svat-增值税专⽤发票gvate-增值税电⼦普票发票svate-增值税电⼦专⽤发票
        remark: '',
        invoiceTitle: {}, // long|发票抬头id
        parkOrderList: [], // 被选中的缴费记录id
        email: '',
        emailAsDefault: true
      },
      headerInfo: {},
      // 总金额，单位分
      invoiceAmount: 0,
      orderInfo: {},
      type: '', // 当前是活动还是停车
      isSubmitFlag: true, // 发票提交申请的flag,
      pageOptions: null,
      preUrl: '',
      orderQuantity: 0,
      parkingOrder: null,
      pagesize: 10,
      page: 0,
      parkingDetailList: []
    };
  },
  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);
    this.getEmail()
    // console.clear();
    const query = getUrlParams();
    // console.log('是否重新回到改页面', this.pageOptions);
    // console.log('是否重新回到改页面', query);
    // console.log(260, this.$route.query);
    this.pageOptions = query;
    
    console.log('this.pageOptions::', this.pageOptions)
    
    if (this.pageOptions) {
      const options = this.pageOptions;
      // console.log('===>onShow', options);
      // console.log('===>onShow', options.ids);
      console.log(typeof this.invoiceAmount)
      if (this.pageOptions.againInvoiceFlag) {
        this.getInvoicesOrders(options.invoiceId)
      } else {
        this.invoiceAmount = Number(options.money).toFixed(2);
        this.$store.commit('setTempParkingOrder', options.invoiceDetailList);
        this.$store.commit('setTempParkingMoney', this.invoiceAmount);
        // if (typeof options.invoiceDetailList === 'object') {
          this.parkingDetailList = JSON.parse(options.invoiceDetailList)
        // }
        
      }
      
      console.log('this.invoiceAmount', this.invoiceAmount)
      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);
          console.log('this.headerInfo:::', this.headerInfo)
        } 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: {
    getInvoicesOrders: async function (id) {
      try {
        const res = await invoicesOrders(id)
        this.invoiceAmount = res.invoiceTotalAmount
        this.orderQuantity = res.invoicedOrders.length
        this.parkingOrder = res.invoicedOrders
        this.$store.commit('setTempParkingOrder', JSON.stringify(res.invoicedOrders));
        this.$store.commit('setTempParkingMoney', res.invoiceTotalAmount);
        this.ids = res.invoicedOrders.map(item=>{
          return item.id
        })
        console.log('1.28 查看发票关联的订单支付详情：：：：', res)
      } catch {
        uni.showToast({
          title: '服务器开小差了呢，请您稍后再试',
          icon: 'none',
        });
      }
    },
    getEmail: async function () {
      try {
        const res = await invoiceEmails()
        this.condition.email = res.email
        this.condition.emailAsDefault = res.emailAsDefault
        console.log('邮箱：：：：', res)
      } catch {
        uni.showToast({
          title: '服务器开小差了呢，请您稍后再试',
          icon: 'none',
        });
      }
    },
    changeShowMore() {
      this.isShow = !this.isShow;
    },
    changeDefaultEMail() {
      this.emailAsDefault = !this.emailAsDefault;
    },
    changeHeader() {
      this.$router.push({
        path: 'parkingChooseHeader',
        query: {
          ids:this.ids,
          invoiceDetailList: JSON.stringify(this.invoiceDetailList),
          money: this.invoiceAmount
        }
      });
    },
    gotoDetail() {
      this.$router.push({
        path: 'parkingOrderDetail?useParkingOrderCache=true',
        query: {
          invoiceDetailList: this.pageOptions.againInvoiceFlag ? JSON.stringify(this.parkingOrder) : this.pageOptions.invoiceDetailList,
          money: this.invoiceAmount
        }
      });
      // this.$router.push({
      //   path:
      //     '/pages/parkingFee/parkingFeeDetailSuccess?orderNo=' +
      //     this.orderInfo.orderNo,
      // })
    },
    // 查询全部抬头列表信息
    getInvoiceTitle: async function () {
      const self = this;
      const params = {
        page: this.page,
        size: this.pagesize
      };
      self.$md(params);
      try {
        const res = await invoicesDetail(params)
        if (res) {
          console.log('res:::', res)
          const list = res.content;
          let currentIndex = 0;
          list.map((item, index) => {
            if (item.defaultOrNot) currentIndex = index;
          });
          const headerInfo = list[currentIndex] || {};
          self.headerInfo = headerInfo;
        } else {
          Toast({
            message: '服务器开小差了呢，请您稍后再试',
          });
        }
      } catch {
        uni.showToast({
          title: '服务器开小差了呢，请您稍后再试',
          icon: 'none',
        });
      }
      // 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;
      self.parkingOrder = this.pageOptions.invoiceDetailList;
      // self.invoiceAmount = (datas.invoiceAmount / 100).toFixed(2);
      // self.orderInfo = datas.list[0];
      // console.log('self.parkingOrder:::', JSON.parse(self.parkingOrder))
      // 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.emailAsDefault = true;
      //         this.condition.mailbox = res.data.data;
      //       } else {
      //         this.emailAsDefault = 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: async function () {
      const self = this;
      if (!self.condition.email) {
        /* 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;
      // }
      const params = self.condition;
      params.parkOrderList = self.ids.map(item=>{
        return item = {
          id: item
        }
      });

      
      params.invoiceTitle.id = this.headerInfo.id
      params.totalAmount = Number(this.invoiceAmount)
      console.log('params.parkOrderList::', params)
  // params.openid = this.openid;
  // params.groupId = this.groupId;
  // params.vipcode = this.member?.vipcode;
  // console.log('提交发票请求的入参', params);
  if (self.isSubmitFlag) {
  // 勾选默认邮箱埋点
//   if (self.isDefaultEMail) {
//   self.sensorsClick('$SetDefaultEmail', {
//   redirect_path: '',
//   mailbox: self.condition.mailbox,
// });
// }
  self.isSubmitFlag = false;
  console.log(488, '前往开票', params);
  try {
    const res = await submitInvoice(params)
    if (res) {
      Toast({
        message: '开票成功',
      });
      this.$router.replace({
        path: 'parkingReceipt',
      });
    } else {
      Toast({
        message: '服务器开小差了呢，请您稍后再试',
      });
    }
  } catch {
    uni.showToast({
      title: '服务器开小差了呢，请您稍后再试',
      icon: 'none',
    });
  }
//   uni.request({
//   // url: self.$baseURL + 'api/1.0/invoice/addMyInvoiceInfo',
//   url: self.$baseURL + 'api/temporary-parking-service/invoices',
//   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',
// });
// } 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);
},
},
};
