// const app = getApp()
const app = {};
import { mapState } from 'vuex';
import MemberCacheTool from '@/utils/member-cache-tool.js';
import uni from '@/utils/uniHooks';
import { invoicesEdittitles, invoicesNewtitles } from '@/api/parking';

export default {
  data() {
    return {
      picUrl: this.$picUrl,
      type: 'add',
      id: '',
      globalData: app.globalData,
      items: [
        { value: 'COMPANY', name: '单位' },
        { value: 'INDIVIDUAL', name: '个人/非企业单位' },
      ],
      isDefault: true, // 记录
      condition: {
        companyAddress: "",
        companyTel: "",
        defaultOrNot: true,
        depositAccount: "",
        depositBank: "",
        id: '',
        invoiceTitleType: "COMPANY",
        taxNo: "",
        titleName: "",
        // 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 == 'COMPANY';
    },
    ...mapState({
      custTypeId: (state) => state.custTypeId,
      member: (state) => state.member,
      openid: (state) => state.openid, // |String|是|openid
    }),
  },
  created() {
    const options = this.$route.query;
    if (options.type == 'edit') {
      this.condition = JSON.parse(this.$route.query.item)
    }
    console.log('this.condition::::', this.condition, this.globalData, this.$route.query.id);
    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);
    setTimeout(() => {
      window?.toWXSendMsg({
        type: 'uni_func',
        funcName: 'setNavigationBarColor',
        options: {
          frontColor: '#000000',
          backgroundColor: '#FBFCFF',
        },
      });
    }, 500)
  },
  methods: {
    radioChange: function (value) {
      console.log(71, value);
      for (let i = 0; i < this.items.length; i++) {
        if (this.items[i].value === value) {
          this.condition.invoiceTitleType = value;
          break;
        }
      }
    },
    switch1Change: function (value) {
      console.log('switch1 发生 change 事件，携带值为', value);
      this.isDefault = value;
    },
    // 根据抬头ID获取抬头详情信息  api/1.0/invoiceTitle/{id}
    getInvoiceTitleById: async function() {
      const self = this;
      // const params = {
      //   id: this.id,
      // };
        try {
          const res = await invoicesEdittitles(this.$route.query.id)
          if (res.content.length > 0 ) {
            console.log('res:::', res)
            self.condition = res.data.data;
            // 单独对默认选项进行赋值
            self.isDefault = res.data.data.setDefault === 1 ? true : false;
          } else {
            Toast({
              message: '服务器开小差了呢，请您稍后再试',
            });
          }
        } catch {
          uni.showToast({
            title: '服务器开小差了呢，请您稍后再试',
            icon: 'none',
          });
        }
      // 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: async function () {
      let res = null
      if (!this.condition.titleName)  return uni.showToast({
        title: '请填写抬头名称',
        icon: 'none',
      });
      if (!this.condition.taxNo && this.condition.invoiceTitleType === 'COMPANY') return uni.showToast({
          title: '请填写公司税号',
          icon: 'none',
        });
      try {
        if ( this.isCompany ) {
          if ( !this.condition?.titleName ) {
            uni.showToast({
              title: '请输入公司名称',
              icon: 'none',
            });
            return
          }
          if ( !this.condition?.taxNo ) {
            uni.showToast({
              title: '请输入公司税号',
              icon: 'none',
            });
            return
          }
        }
        if (this.type === 'add') {
          
          res = await invoicesNewtitles(this.condition)
          if (res) {
            this.$router.back();
          }
  
        } else if (this.type === 'edit') {
          res = await invoicesEdittitles(this.condition, this.$route.query.id)
          if (res) {
            this.$router.back();
          }
        }
      } catch {
        uni.showToast({
          title: '服务器开小差了呢，请您稍后再试',
          icon: 'none',
        });
      }
      

      // 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) {
      //       this.$router.back();
      //     } else {
      //       uni.showToast({
      //         title: res.data.msg,
      //         duration: 2000,
      //         icon: 'none',
      //       });
      //     }
      //   },
      //   fail: () => {
      //     uni.showToast({
      //       title: '服务器开小差了呢，请您稍后再试',
      //       icon: 'none',
      //     });
      //   },
      // });
    },
  },
};
