<template>
  <div>
    <scroll-view class="scroll-Y" scroll-y>
      <div>
        <div class="choose-invoice-header" v-if="list.length">
          <van-radio-group class="radios">
            <label
              class="uni-list-cell uni-list-cell-pd radio-label lines"
              v-for="(item, index) in list"
              :key="index"
              :index="item.id"
              @click="chooseHeader(item, index)"
            >
              <div class="invoice-header-info">
                <div class="invoice-header-text">
                  <div class="invoice-header-name">
                    <div class="invoice-header-name-text">
                      {{ item.invoiceTitleName
                      }}<span class="isDefault" v-if="item.setDefault === 1"
                        >默认</span
                      >
                    </div>
                    <div class="invoice-header-name-icon">
                      <div
                        class="edit-header"
                        @click.stop="changeHeader('edit', item.id)"
                      >
                        <img
                          class="invoice-header-arrow"
                          :src="editwIcon"
                          mode="widthFix"
                        />
                      </div>
                      <div class="edit-header" @click.stop="delHeader(item.id)">
                        <img
                          class="invoice-header-arrow"
                          :src="delwIcon"
                          mode="widthFix"
                        />
                      </div>
                    </div>
                  </div>
                  <div class="duty-paragraph">
                    税号 {{ item.corporationTax }}
                  </div>
                </div>
              </div>
            </label>
          </van-radio-group>
        </div>
        <div class="choose-invoice-header noData" v-else>
          <img class="noDataImg" :src="noDataIcon" mode="widthFix" />
          <div class="">您还没添加发票抬头</div>
        </div>
      </div>
    </scroll-view>
    <div class="footer">
      <div
        :class="{
          'push-again-btn': true,
          'blue-push-again-btn': custTypeId === 1,
          'green-push-again-btn': custTypeId === 2,
        }"
        @click="changeHeader('add')"
      >
        添加抬头
      </div>
    </div>
  </div>
</template>

<script>
// const app = getApp()
const app = {};
import editwIcon from '../static/images/edit.png';
import delwIcon from '../static/images/delete.png';
import noDataIcon from '../static/images/nodataicon.png';
import { mapState } from 'vuex';
import uni from '@/utils/uniHooks';

export default {
  data() {
    return {
      picUrl: this.$picUrl,
      editwIcon: editwIcon,
      delwIcon: delwIcon,
      noDataIcon: noDataIcon,
      globalData: app.globalData,
      current: -1,
      ids: '',
      list: [],
      preUrl: '',
    };
  },
  created() {
    const options = this.$route.query;
    if (options.ids) this.ids = options.ids;
    // 埋点本地化
    this.preUrl = uni.getStorageSync('previousUrl');
    uni.setStorageSync(
      'previousUrl',
      '/pages/parkingFee/parkingReceipt/parkingChooseHeader.vue'
    );
  },
  mounted() {
    // console.log('全剧信息', this.globalData);
    this.getInvoiceTitle();
  },
  onBackPress() {
    console.log('===> 点击返回按钮');
    const pages = getCurrentPages();
    const prePage = pages[pages.length - 2];
    const options = {
      header: this.list[this.current] || {},
    };
    // TODO 开票界面选择了 A,两个列表中如果有当前是 A，删除 A之后，点击返回按钮 开票界面 A 还存在
    prePage.$vm.pageOptions = options;
  },
  computed: {
    ...mapState({
      custTypeId: (state) => state.custTypeId,
      member: (state) => state.member,
    }),
  },
  methods: {
    changeHeader(type, id) {
      if (id)
        this.$router.push({
          path: 'parkingChangeHeader?type=' + type + '&id=' + id,
        });
      else
        this.$router.push({
          path: 'parkingChangeHeader?type=' + type,
        });
    },
    // 埋点方法
    sensorsClick(eventName, params) {
      let optionsQuery = uni.getStorageSync('options_query');
      let fixedParams = {
          cta_itemno: '',
          cta_name: '',
          previous_path: 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);
    },
    // 删除抬头
    delHeader(id) {
      const self = this;
      self.$md([id]);
      uni.showModal({
        content: '确认要删除该发票抬头吗？',
        success: function (res) {
          if (res.confirm) {
            uni.request({
              url: self.$baseURL + 'api/1.0/invoiceTitle',
              method: 'delete',
              data: [id],
              header: JSON.parse(uni.getStorageSync('handleUser')),
              success: (res) => {
                console.log('删除抬头', res.data);
                if (res.data.code === 0) {
                  // 删除抬头埋点
                  self.sensorsClick('$ClickDeleteIcon', {
                    redirect_path: '',
                    delete_header_id: id,
                  });
                  self.getInvoiceTitle();
                } else {
                  uni.showToast({
                    title: res.data.msg,
                    duration: 2000,
                    icon: 'none',
                  });
                }
              },
              fail: () => {
                uni.showToast({
                  title: '服务器开小差了呢，请您稍后再试',
                  icon: 'none',
                });
              },
            });
          }
        },
      });
    },
    // 选择抬头
    chooseHeader(item, index) {
      console.log(178, item, index);
      this.current = index;
      if (!this.ids || !this.ids.length) return false;
      // const pages = getCurrentPages();
      // const prePage = pages[pages.length - 2];
      // const options = {
      //   header: this.list[index] || {},
      // };
      // prePage.$vm.pageOptions = options;
      // this.$router.back();
      this.$router.replace({
        path:
          'parkingApplication?ids=' +
          this.ids +
          '&header=' +
          JSON.stringify(item),
      });
    },
    // 查询全部抬头列表信息
    getInvoiceTitle() {
      const self = this;
      const params = {
        vipcode: this.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) {
            this.list = res.data.data;
            if (this.list.length) {
              this.list.map((item, index) => {
                if (item.setDefault === 1) this.current = index;
              });
              if (this.current == -1) this.current = 0;
            }
          } else {
            uni.showToast({
              title: res.data.msg,
              duration: 2000,
              icon: 'none',
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '服务器开小差了呢，请您稍后再试',
            icon: 'none',
          });
        },
      });
    },
  },
};
</script>

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

.scroll-Y {
  width: 100%;
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f4f7ff;

  .choose-invoice-header {
    padding: 20px 30px;

    .radios {
      width: 100%;

      .radio-label {
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-radius: 10px;
        background-color: #ffffff;
        margin-bottom: 20px;

        .invoice-header-info {
          flex: 1;
          display: flex;
          justify-content: flex-start;
          align-items: center;

          .invoice-header-text {
            width: 100%;
            padding: 0 20px;

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

              .isDefault {
                color: #8cc63f;
                border: 2px solid #8cc63f;
                margin-left: 16px;
                border-radius: 20px;
                padding: 0 10px;
              }

              .invoice-header-name-icon {
                width: 100px;
                display: flex;
                align-items: center;
                justify-content: space-around;

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

          .duty-paragraph {
            color: #6f6f70;
            padding: 20px 0;
          }
        }

        .invoice-header-icon {
          width: 100px;
          display: flex;
          align-items: center;
          justify-content: space-around;

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

  .noData {
    position: relative;
    top: 20%;
    // transform: translateY(-50%);
    color: #cccccc;
    text-align: center;

    .noDataImg {
      width: 200px;
      margin-bottom: 20px;
    }
  }
}
.lines {
  border-bottom: 2px solid #ececec;
}
.footer {
  width: 100%;
  background-color: #ffffff;
  position: fixed;
  bottom: 0;
  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);
  // padding-bottom: constant(safe-area-inset-bottom);
  // padding-bottom: env(safe-area-inset-bottom);
  padding-bottom: 20px;

  .push-again-btn {
    margin: 20px 60px;
    color: #ffffff;
    // background-image: linear-gradient(to right, #7d4ea1, #40397c);
    background-color: #064c8a;
    border-radius: 50px;
    text-align: center;
    padding: 20px 0;
  }

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

  .green-push-again-btn {
    .color-background-color('green');
  }
}
</style>
