<template>
  <uv-navbar :fixed="false" title="申请开具发票" left-arrow @leftClick="$onClickLeft" />
  <view class="container">
    <view class="invoice-form">
      <!-- 订单信息展示 -->
      <view class="form-item">
        <text class="label">订单编号<text class="required"> *</text></text>
        <input type="text" :value="orderId" class="input-field" disabled />
      </view>
      <view class="form-item">
        <text class="label">开票金额<text class="required"> *</text></text>
        <input type="text" :value="'￥' + amount" class="input-field" disabled />
      </view>

      <!-- 发票类型选择 -->
      <view class="invoice-type">
        <text class="label">发票类型</text>
        <view class="radio-group">
          <view class="radio-item" @click="invoiceType = 'company'">
            <radio :checked="invoiceType === 'company'" color="#52ac41" />
            <text>企业单位</text>
          </view>
          <view class="radio-item" @click="invoiceType = 'personal'">
            <radio :checked="invoiceType === 'personal'" color="#52ac41" />
            <text>个人/非企业单位</text>
          </view>
        </view>
      </view>

      <!-- 企业单位表单 -->
      <block v-if="invoiceType === 'company'">
        <view class="form-item">
          <text class="label">公司抬头<text class="required"> *</text></text>
          <input type="text" placeholder="公司抬头(必填)" placeholderClass="placeholder" class="input-field"
            v-model="companyForm.invoiceTitle" />
        </view>

        <view class="form-item">
          <text class="label">公司税号<text class="required"> *</text></text>
          <input type="text" placeholder="公司税号(必填)" placeholderClass="placeholder" class="input-field"
            v-model="companyForm.taxNumber" />
        </view>

        <view class="form-item">
          <text class="label">公司地址</text>
          <input type="text" placeholder="公司地址(选填)" placeholderClass="placeholder" class="input-field"
            v-model="companyForm.companyAddress" />
        </view>

        <view class="form-item">
          <text class="label">公司电话</text>
          <input type="text" placeholder="公司电话(选填)" placeholderClass="placeholder" class="input-field"
            v-model="companyForm.companyPhone" />
        </view>

        <view class="form-item">
          <text class="label">开户银行</text>
          <input type="text" placeholder="开户银行(选填)" placeholderClass="placeholder" class="input-field"
            v-model="companyForm.bankName" />
        </view>

        <view class="form-item">
          <text class="label">开户账号</text>
          <input type="text" placeholder="开户账号(选填)" placeholderClass="placeholder" class="input-field"
            v-model="companyForm.bankAccount" />
        </view>
      </block>

      <!-- 个人/非企业单位表单 -->
      <block v-else>
        <view class="form-item">
          <text class="label">抬头名称<text class="required"> *</text></text>
          <input type="text" placeholder="抬头名称(必填)" placeholderClass="placeholder" class="input-field"
            v-model="personalForm.invoiceTitle" />
        </view>

        <!-- <view class="form-item">
					<text class="label">税号</text>
					<input 
						type="text" 
						placeholder="请输入个人税号(选填)" 
						placeholderClass="placeholder"
						class="input-field"
						v-model="personalForm.taxNumber"
					/>
				</view> -->
      </block>

      <!-- 提交按钮 -->
      <view class="submit-btn-wrapper">
        <button class="submit-btn" @tap="handleSubmit">提交申请</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { applyInvoice } from "@/api/order";
import { useMainStore } from "@/store/store";
import { storeToRefs } from "pinia";

const main = useMainStore();
const { member, isLogin } = storeToRefs(main);

const orderId = ref('')
const amount = ref('')
const userId = ref('')

// 初始化订单信息
onLoad((query) => {
  if (!isLogin.value) {
    uni.navigateTo({ url: "/pages/components/pages/login/login" });
  }
  orderId.value = query.orderId
  amount.value = query.amount
})

// 表单提交处理
const invoiceType = ref('company')

// 企业单位表单数据
const companyForm = reactive({
  userId: '',
  invoiceTitle: '',  // 发票抬头
  taxNumber: '',    // 纳税人识别号
  companyAddress: '', // 单位地址
  companyPhone: '',  // 公司电话
  bankName: '',     // 开户银行
  bankAccount: ''   // 银行账户
})

// 个人/非企业单位表单数据
const personalForm = reactive({
  userId: '',
  invoiceTitle: '', // 个人发票抬头
  // taxNumber: ''    // 个人税号（可能为空）
})

const handleSubmit = async () => {

  try {
    if (invoiceType.value === 'company') {
      // 验证企业表单
      if (!companyForm.invoiceTitle) {
        uni.showToast({
          title: '请输入发票抬头',
          icon: 'none'
        })
        return
      }
      if (!companyForm.taxNumber) {
        uni.showToast({
          title: '请输入纳税人识别号',
          icon: 'none'
        })
        return
      }

      // 构建提交数据
      const params = {
        userId: member.value.id,
        invoiceType: 'enterprise',
        invoiceTitle: companyForm.invoiceTitle,
        taxNumber: companyForm.taxNumber,
        companyAddress: companyForm.companyAddress,
        companyPhone: companyForm.companyPhone,
        bankName: companyForm.bankName,
        bankAccount: companyForm.bankAccount
      }

      // 提交企业发票信息
      uni.showLoading({
        title: '提交中...'
      })

      // 调用接口提交数据
      const data = await applyInvoice(orderId.value, amount.value, params);

      uni.hideLoading()

      if (data) {
        uni.showToast({
          title: '提交成功',
          icon: 'success'
        })
        // 返回上一页
        setTimeout(() => {
          uni.setStorageSync('setNeedRefreshOrder', true);
          uni.navigateBack()
        }, 1500)
      } else {
        uni.showToast({
          title: '提交失败，请重试',
          icon: 'none'
        })
      }
    } else {
      // 验证个人表单
      if (!personalForm.invoiceTitle) {
        uni.showToast({
          title: '请输入发票抬头',
          icon: 'none'
        })
        return
      }

      // 构建提交数据
      const params = {
        userId: member.value.id,
        invoiceType: 'individual',
        invoiceTitle: personalForm.invoiceTitle,
        // taxNumber: personalForm.taxNumber || ''
      }

      // 提交个人发票信息
      uni.showLoading({
        title: '提交中...'
      })

      // 调用接口提交数据
      const data = await applyInvoice(orderId.value, amount.value, params);

      uni.hideLoading()

      if (data) {
        uni.showToast({
          title: '提交成功',
          icon: 'success'
        })
        // 返回上一页
        setTimeout(() => {
          uni.setStorageSync('setNeedRefreshOrder', true);
          uni.navigateBack()
        }, 1500)
      } else {
        uni.showToast({
          title: '提交失败，请重试',
          icon: 'none'
        })
      }
    }
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: '网络请求失败，请重试',
      icon: 'none'
    })
    console.error('提交发票信息错误:', error)
  }
}
</script>

<style lang="scss" scoped>
.order-info {
  padding: 30rpx;
  background: #fff;
  margin-bottom: 20rpx;

  .info-item {
    display: flex;
    justify-content: space-between;
    padding: 20rpx 0;

    .label {
      font-size: 28rpx;
      color: #666;
    }

    .value {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }
  }
}

.container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 0;
}

.invoice-form {
  background-color: #ffffff;
  padding: 0 30rpx;
}

.invoice-type {
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.label {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: inline-block;
}

.radio-group {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  margin-right: 60rpx;
}

.radio-item text {
  font-size: 28rpx;
  margin-left: 8rpx;
}

.form-item {
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.input-field {
  height: 60rpx;
  font-size: 28rpx;
  margin-top: 10rpx;
  width: 100%;
}

.placeholder {
  color: #cccccc;
  font-size: 28rpx;
}

.section-title {
  font-size: 30rpx;
  color: #333;
  padding: 30rpx 0;
  background-color: #f5f5f5;
  padding-left: 20rpx;
  margin: 0 -30rpx;
}

.required {
  color: #ff4d4f;
  margin-left: 5rpx;
}

.submit-btn-wrapper {
  padding: 50rpx 30rpx;
  box-sizing: border-box;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background-color: #52ac41;
  border-radius: 44rpx;
  color: white;
  font-size: 32rpx;
  border: none;
}
</style>