<template>
  <div>
    <scroll-view class="scroll-Y" scroll-y>
      <div class="part top">
        <div class="invoice-header">
          <div class="part-item header-type lines">
            <span class="part-item-key">抬头类型</span>
            <van-radio-group
              v-model="condition.invoiceTitleType"
              direction="horizontal"
              class="part-item-value"
              @change="radioChange"
            >
              <van-radio
                v-for="item in items"
                :key="item.name + item.value"
                checked-color="#064C8A"
                :name="item.value"
              >
                {{ item.name }}
              </van-radio>
            </van-radio-group>
          </div>
          <div class="part-item lines">
            <span class="part-item-key">抬头名称</span>
            <div class="part-item-value">
              <!-- <input
              type="text"
              placeholder="请输入抬头名称"
              v-model="condition.invoiceTitleName"
            /> -->
              <van-field
                v-model="condition.invoiceTitleName"
                right-icon="arrow"
                input-align="right"
                placeholder="请输入抬头名称"
              />
            </div>
          </div>
          <div class="part-item lines" v-if="isCompany">
            <span class="part-item-key">公司税号</span>
            <div class="part-item-value">
              <!-- <input
              type="text"
              placeholder="请输入公司税号"
              v-model="condition.corporationTax"
            /> -->
              <van-field
                v-model="condition.corporationTax"
                right-icon="arrow"
                input-align="right"
                placeholder="请输入公司税号"
              />
            </div>
          </div>
          <div class="part-item lines">
            <span class="part-item-key">设为默认</span>
            <div class="part-item-value">
              <van-switch
                active-color="#064C8A"
                v-model="isDefault"
                @change="switch1Change"
              />
            </div>
          </div>
        </div>
        <div class="invoice-more" v-if="isCompany">
          <div class="tab-title">更多信息(以下为选填内容)</div>
          <div class="company-box">
            <div class="part-item lines">
              <span class="part-item-key">公司地址</span>
              <div class="part-item-value">
                <van-field
                  v-model="condition.companyAddress"
                  right-icon="arrow"
                  input-align="right"
                  placeholder="请输入公司地址"
                />
              </div>
            </div>
            <div class="part-item lines">
              <span class="part-item-key">公司电话</span>
              <div class="part-item-value">
                <van-field
                  v-model="condition.companyTel"
                  right-icon="arrow"
                  input-align="right"
                  placeholder="请输入公司电话"
                />
              </div>
            </div>
            <div class="part-item lines">
              <span class="part-item-key">开户银行</span>
              <div class="part-item-value">
                <van-field
                  v-model="condition.depositBank"
                  right-icon="arrow"
                  input-align="right"
                  placeholder="请输入开户银行"
                />
              </div>
            </div>
            <div class="part-item lines" style="border: none">
              <span class="part-item-key">开户账户</span>
              <div class="part-item-value">
                <van-field
                  v-model="condition.accountNumber"
                  right-icon="arrow"
                  input-align="right"
                  placeholder="请输入开户账户"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </scroll-view>
    <div class="part footer">
      <div
        :class="{
          'push-again-btn': true,
          'blue-push-again-btn': custTypeId === 1,
          'green-push-again-btn': custTypeId === 2,
        }"
        @click="submit"
      >
        保存
      </div>
    </div>
  </div>
</template>

<script>
// const app = getApp()
const app = {};
import { mapState } from 'vuex';
import MemberCacheTool from '@/utils/member-cache-tool.js';
import uni from '@/utils/uniHooks';

export default {
  data() {
    return {
      picUrl: this.$picUrl,
      type: 'add',
      id: '',
      globalData: app.globalData,
      items: [
        { value: 0, name: '单位' },
        { value: 1, name: '个人/非企业单位' },
      ],
      isDefault: true, // 记录
      condition: {
        id: '', // |Long|否|抬头id
        invoiceTitleType: 0, // |int|是|抬头类型（ 0：单位，1:个人/非企业单位）
        invoiceTitleName: '', // |String|是|抬头名称
        corporationTax: '', // |String|是|公司税号|
        setDefault: '', // |int|是|设为默认(0：不默认，1：默认)
        depositBank: '', // |String|否|开户银行
        accountNumber: '', // |String|否|开户账号
        companyAddress: '', // |String|否|公司地址
        companyTel: '', // |String|否|公司电话
        createUser: '', // |String|是|创建人
        creator: '', // |Long|是|创建者id
        updateUser: this.member?.nickname, // |String|是|更新人
        // updater: this.member?.id, // |Long|是|更新人id
        // mobile: this.member?.mobile, // |String|是|手机号
        // vipcode: this.member?.vipcode, // |String|是|会员号
        // openid: MemberCacheTool.getOpenId(app), // |String|是|openid
      },
      preUrl: '',
    };
  },
  computed: {
    isCompany: function () {
      return this.condition.invoiceTitleType == 0;
    },
    ...mapState({
      custTypeId: (state) => state.custTypeId,
      member: (state) => state.member,
      openid: (state) => state.openid, // |String|是|openid
    }),
  },
  created() {
    const options = this.$route.query;
    console.log(this.globalData);
    if (options.type) this.type = options.type;
    if (options.id) (this.id = options.id), this.getInvoiceTitleById();
    // 埋点本地化
    this.preUrl = uni.getStorageSync('previousUrl');
    uni.setStorageSync(
      'previousUrl',
      '/pages/parkingFee/parkingReceipt/parkingChangeHeader.vue'
    );
  },
  mounted() {
    setTimeout(() => {
      uni.setNavigationBarTitle({
        title: '发票抬头',
      });
    }, 300);
  },
  methods: {
    radioChange: function (e) {
      for (let i = 0; i < this.items.length; i++) {
        if (this.items[i].value === e.detail.value) {
          this.condition.invoiceTitleType = i;
          break;
        }
      }
    },
    switch1Change: function (e) {
      console.log('switch1 发生 change 事件，携带值为', e.target.value);
      this.isDefault = e.target.value;
    },
    // 根据抬头ID获取抬头详情信息  api/1.0/invoiceTitle/{id}
    getInvoiceTitleById() {
      const self = this;
      const params = {
        id: this.id,
      };
      self.$md(params);
      uni.request({
        url: self.$baseURL + 'api/1.0/invoiceTitle/' + this.id,
        method: 'GET',
        data: params,
        header: JSON.parse(uni.getStorageSync('handleUser')),
        success: (res) => {
          console.log('获取抬头详情信息', res.data);
          if (res.data.code === 0) {
            self.condition = res.data.data;
            // 单独对默认选项进行赋值
            self.isDefault = res.data.data.setDefault === 1 ? true : false;
          } else {
            uni.showToast({
              title: res.data.msg,
              duration: 2000,
              icon: 'none',
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '服务器开小差了呢，请您稍后再试',
            icon: 'none',
          });
        },
      });
    },
    // 添加、编辑抬头信息
    submit() {
      const self = this;
      const url =
        self.type === 'add' ? 'api/1.0/invoiceTitle' : 'api/1.0/invoiceTitle';
      const methodType = self.type === 'add' ? 'POST' : 'PUT';
      if (self.type === 'add') {
        self.condition.createUser = self.$store.state.userInfo.nickname;
        self.condition.creator = self.$store.state.userInfo.id;
      }
      self.condition.setDefault = self.isDefault ? 1 : 0;
      const params = {
        ...self.condition,
        updater: this.member?.id, // |Long|是|更新人id
        mobile: this.member?.mobile, // |String|是|手机号
        vipcode: this.member?.vipcode, // |String|是|会员号
      };
      console.log('提交信息', params);
      self.$md(params);
      uni.request({
        url: self.$baseURL + url,
        method: methodType,
        data: params,
        header: JSON.parse(uni.getStorageSync('handleUser')),
        success: (res) => {
          console.log(271, res.data);
          if (res.data.code === 0) {
            // 保存结果埋点
            // self.sensorsClick('$ClickSubmitHeader',{
            //   redirect_url: '',
            //   type_header:
            //     params.invoiceTitleType == 0
            //       ? 'SelectCompany'
            //       : 'SelectPersonal',
            //   default_header:
            //     params.setDefault == 0
            //       ? 'SetAsDefaultClose'
            //       : 'SetAsDefaultOpen',
            // })
            this.$router.back();
            // uni.navigateBack({delta: 1})
          } else {
            uni.showToast({
              title: res.data.msg,
              duration: 2000,
              icon: 'none',
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '服务器开小差了呢，请您稍后再试',
            icon: 'none',
          });
        },
      });
    },
    // 埋点方法
    sensorsClick(eventName, params) {
      let optionsQuery = uni.getStorageSync('options_query');
      let fixedParams = {
          cta_itemno: '',
          cta_name: '',
          previous_url: 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);
    },
  },
};
</script>

<style lang="less" scoped>
// @import '../../../styles/common.less';
.scroll-Y {
  width: 100%;
  display: flex;
  flex-direction: column;
  height: 100vh;
  // background: #f2f2f2;
  background: #f4f7ff;
  //padding: 30px 30px 30px 30px;

  .part {
    // background-color: #FAFBFF;
    width: calc(100% - 60px);

    .part-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      // padding: 32px 0;
      font-size: 28px;
      width: 91.4%;
      height: 87px;
      margin: 0 auto;

      .part-item-key {
        color: #999;
      }

      .part-item-value {
        color: #999;
        text-align: right;

        > label {
          margin-left: 20px;
        }

        .van-cell {
          background-color: transparent;
          font-size: 30px;
          padding-right: 0;
        }
      }
    }

    .tab-title {
      color: #676767;
      padding-top: 36px;
      padding-bottom: 20px;
      // padding: 30px 35px;
      // background-color: #f1f1f1;
      font-size: 30px;
      font-weight: 400;
      color: #333333;
      line-height: 42px;
    }

    .company-box {
      background: #fafbff;
      border-radius: 4px;
      border: 1px solid #d8dae0;
    }

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

    .invoice-more {
      padding-bottom: 8px;
    }

    .invoice-header {
      background: #fafbff;
      border-radius: 4px;
      border: 1px solid #d8dae0;
    }
  }

  .top {
    margin-top: 30px;
    margin-left: 30px;
  }

  .middle {
    margin: 20px 0;

    .purple {
      color: #a668b1;
    }
  }

  
}
.footer {
    width: 100%;
    height: 150px;
    position: fixed;
    bottom: 0px;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    //padding-bottom: 20px;
    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-top: 20px;
    .invoive-img {
      text-align: center;

      > img {
        width: 100%;
      }

      .download {
        margin-top: 20px;
        margin-bottom: 20px;
        display: flex;
        justify-content: center;
        align-items: center;

        > img {
          width: 32px;
        }

        > span {
          margin-left: 10px;
          color: #808080;
        }
      }
    }

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

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

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