<template>
  <view class="page">
    <!-- 已选订单摘要 -->
    <view class="summary-bar flex-align-center pl-30 pr-30 pt-20 pb-20">
      <view class="fs-28 color-666">已选 {{ checkedCount }} 个订单</view>
    </view>

    <!-- 已保存抬头选择 -->
    <view class="block mt-20" v-if="titleList.length">
      <view class="fs-30 fw-600 color-333 mb-20">选择已有抬头</view>
      <scroll-view scroll-x class="title-scroll">
        <view class="title-cards flex">
          <view
            v-for="item in titleList"
            :key="item.id"
            class="title-card br-12 p-20 mr-20"
            :class="{ active: selectedTitleId === item.id }"
            @click="selectTitle(item)"
          >
            <view class="fs-28 fw-500 color-333 ellipsis">{{ item.invoiceTitle }}</view>
            <view class="fs-22 color-999 mt-8">{{ item.invoiceType === 'ORGANIZATION' ? '企业' : '个人' }}</view>
            <view class="fs-20 color-theme mt-4" v-if="item.isDefault">默认</view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 发票抬头表单 -->
    <view class="block mt-20">
      <view class="flex-align-center flex-between mb-28">
        <view class="fs-30 fw-600 color-333">填写发票信息</view>
        <view class="import-btn flex-center br-20 fs-24 color-theme py-8 px-16" @click="importWechatTitle">
          同步微信抬头
        </view>
      </view>

      <!-- 接收邮箱 -->
      <view class="form-item">
        <view class="fs-28 color-333 mb-12">接收邮箱<text class="color-primary">*</text></view>
        <input class="input br-8 fs-28 p-20" v-model="form.email" placeholder="电子发票将发送至此邮箱" />
      </view>

      <!-- 发票类型 -->
      <view class="form-item">
        <view class="fs-28 color-333 mb-12">发票类型</view>
        <view class="type-selector flex">
          <view
            class="type-option flex-center br-8 fs-28 py-12 px-24 mr-20"
            :class="{ active: form.invoiceType === 'ORGANIZATION' }"
            @click="form.invoiceType = 'ORGANIZATION'"
          >企业</view>
          <view
            class="type-option flex-center br-8 fs-28 py-12 px-24"
            :class="{ active: form.invoiceType === 'INDIVIDUAL' }"
            @click="form.invoiceType = 'INDIVIDUAL'"
          >个人</view>
        </view>
      </view>

      <!-- 抬头名称 -->
      <view class="form-item">
        <view class="fs-28 color-333 mb-12">
          {{ form.invoiceType === 'ORGANIZATION' ? '公司名称' : '姓名' }}
          <text class="color-primary">*</text>
        </view>
        <input
          class="input br-8 fs-28 p-20"
          v-model="form.invoiceTitle"
          :placeholder="form.invoiceType === 'ORGANIZATION' ? '请输入公司全称' : '请输入姓名'"
        />
      </view>

      <!-- 企业专有字段 -->
      <template v-if="form.invoiceType === 'ORGANIZATION'">
        <view class="form-item">
          <view class="fs-28 color-333 mb-12">公司税号<text class="color-primary">*</text></view>
          <input class="input br-8 fs-28 p-20" v-model="form.taxId" placeholder="请输入纳税人识别号" />
        </view>
        <view class="form-item">
          <view class="fs-28 color-333 mb-12">公司地址</view>
          <input class="input br-8 fs-28 p-20" v-model="form.address" placeholder="请输入注册地址" />
        </view>
        <view class="form-item">
          <view class="fs-28 color-333 mb-12">公司电话</view>
          <input class="input br-8 fs-28 p-20" v-model="form.telephone" placeholder="请输入公司电话" />
        </view>
        <view class="form-item">
          <view class="fs-28 color-333 mb-12">开户银行</view>
          <input class="input br-8 fs-28 p-20" v-model="form.bankName" placeholder="请输入开户银行" />
        </view>
        <view class="form-item">
          <view class="fs-28 color-333 mb-12">银行账号</view>
          <input class="input br-8 fs-28 p-20" v-model="form.bankAccount" placeholder="请输入银行账号" />
        </view>
      </template>

      <view class="form-item">
        <view class="fs-28 color-333 mb-12">备注</view>
        <input class="input br-8 fs-28 p-20" v-model="form.remark" placeholder="可选备注信息" />
      </view>

      <!-- 保存此抬头 -->
      <view class="form-item flex-align-center mt-10">
        <view class="fs-28 color-333 mr-16">保存此抬头</view>
        <view class="switch-container" @click="saveTitleCheck = !saveTitleCheck">
          <view class="switch br-24" :class="{ on: saveTitleCheck }">
            <view class="switch-dot"></view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部提交 -->
    <view class="foot-placeholder"></view>
    <view class="foot-bar flex-center bg-fff">
      <view class="submit-btn br-40 bg-theme color-fff fs-32 fw-500 flex-center" @click="submit">
        提交开票
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onLoad } from "@dcloudio/uni-app";
import { ref, reactive } from "vue";
import { applyInvoice, fetchTitleList } from "@/api";
import { back } from "@/utils/navigate";

const checkedCount = ref(0);
const startChargeSeqs = ref<string[]>([]);
const titleList = ref<any[]>([]);
const selectedTitleId = ref(0);
const saveTitleCheck = ref(true);

const form = reactive({
  invoiceType: "ORGANIZATION",
  invoiceTitle: "",
  taxId: "",
  address: "",
  telephone: "",
  bankName: "",
  bankAccount: "",
  email: "",
  remark: "",
});

onLoad((options: any) => {
  if (options.startChargeSeqs) {
    startChargeSeqs.value = options.startChargeSeqs.split(",");
    checkedCount.value = startChargeSeqs.value.length;
  }

  // 加载已保存的抬头
  fetchTitleList()
    .then((res: any) => {
      titleList.value = res || [];
    })
    .catch(() => {});
});

const importWechatTitle = () => {
  // #ifdef MP-WEIXIN
  wx.chooseInvoiceTitle({
    success: (res: any) => {
      form.invoiceType = res.type === '0' ? 'ORGANIZATION' : 'INDIVIDUAL';
      form.invoiceTitle = res.title || '';
      form.taxId = res.taxNumber || '';
      form.address = res.companyAddress || '';
      form.telephone = res.telephone || '';
      form.bankName = res.bankName || '';
      form.bankAccount = res.bankAccount || '';
    },
    fail: (err: any) => {
      const msg = err && err.errMsg ? err.errMsg : '';
      if (/cancel/.test(msg)) return;
      if (/auth deny/.test(msg)) {
        uni.showModal({
          title: "需要授权",
          content: "请在设置中开启「发票抬头」权限",
          confirmText: "去设置",
          success: (res: any) => {
            if (res.confirm) wx.openSetting({});
          }
        });
        return;
      }
      uni.showToast({ title: "同步失败，请重试", icon: "none" });
    }
  });
  // #endif
};

const selectTitle = (item: any) => {
  selectedTitleId.value = item.id;
  form.invoiceType = item.invoiceType || "ORGANIZATION";
  form.invoiceTitle = item.invoiceTitle || "";
  form.taxId = item.taxId || "";
  form.address = item.address || "";
  form.telephone = item.phone || item.telephone || "";
  form.bankName = item.bankName || "";
  form.bankAccount = item.bankAccount || "";
  form.email = item.email || "";
};

const emailRegex = /^[\w.%+-]+@[\w.-]+\.[a-zA-Z]{2,}$/;

const submit = () => {
  if (!form.email.trim()) {
    uni.showToast({ title: "请填写接收发票的邮箱地址", icon: "none" });
    return;
  }
  if (!emailRegex.test(form.email.trim())) {
    uni.showToast({ title: "邮箱格式不正确", icon: "none" });
    return;
  }
  if (!form.invoiceTitle.trim()) {
    uni.showToast({ title: "请填写抬头名称", icon: "none" });
    return;
  }
  if (form.invoiceType === "ORGANIZATION" && !form.taxId.trim()) {
    uni.showToast({ title: "请填写公司税号", icon: "none" });
    return;
  }

  uni.showLoading({ title: "提交中" });

  const params: any = {
    startChargeSeqs: startChargeSeqs.value,
    invoiceType: form.invoiceType,
    invoiceTitle: form.invoiceTitle.trim(),
    email: form.email.trim(),
    remark: form.remark.trim(),
  };

  if (form.invoiceType === "ORGANIZATION") {
    params.taxId = form.taxId.trim();
    params.address = form.address.trim();
    params.phone = form.telephone.trim();
    params.bankName = form.bankName.trim();
    params.bankAccount = form.bankAccount.trim();
  }

  applyInvoice(params)
    .then(() => {
      uni.hideLoading();
      back();
    })
    .catch((err) => {
      uni.hideLoading();
      uni.showModal({ content: err.errMsg || "提交失败，请重试" });
    });
};
</script>

<style lang="scss">
.page {
  min-height: 100vh;
  background-color: #f6f7fa;
  padding-bottom: 120rpx;
}

.summary-bar {
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;
}

.block {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin: 0 20rpx;
}

.form-item {
  margin-bottom: 28rpx;
}

.input {
  width: 100%;
  background: #f6f7fa;
  border: 1rpx solid #eee;
  box-sizing: border-box;
  height: 80rpx;
  line-height: 80rpx;
}

.flex-between { justify-content: space-between; }

.import-btn {
  border: 2rpx solid #419D95;
  background: rgba(65, 157, 149, 0.06);
}

.type-selector {
  .type-option {
    border: 2rpx solid #e0e0e0;
    color: #666;
    transition: all 0.2s;

    &.active {
      border-color: #419D95;
      background: rgba(65, 157, 149, 0.08);
      color: #419D95;
    }
  }
}

.title-scroll {
  white-space: nowrap;
}

.title-cards {
  .title-card {
    display: inline-block;
    width: 240rpx;
    border: 2rpx solid #eee;
    flex-shrink: 0;

    &.active {
      border-color: #419D95;
      background: rgba(65, 157, 149, 0.06);
    }
  }
}

.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.switch {
  width: 80rpx;
  height: 44rpx;
  background: #ddd;
  position: relative;
  transition: background 0.2s;

  &.on {
    background: #419D95;
  }
}

.switch-dot {
  width: 36rpx;
  height: 36rpx;
  background: #fff;
  border-radius: 50%;
  position: absolute;
  top: 4rpx;
  left: 4rpx;
  transition: transform 0.2s;

  .switch.on & {
    transform: translateX(36rpx);
  }
}

.foot-placeholder {
  height: 140rpx;
}

.foot-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  padding-bottom: env(safe-area-inset-bottom);
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.submit-btn {
  width: 600rpx;
  height: 80rpx;
}

.br-8 { border-radius: 8rpx; }
.br-12 { border-radius: 12rpx; }
.br-20 { border-radius: 20rpx; }
.br-24 { border-radius: 24rpx; }
.br-40 { border-radius: 40rpx; }
.p-20 { padding: 20rpx; }
.pl-30 { padding-left: 30rpx; }
.pr-30 { padding-right: 30rpx; }
.pt-20 { padding-top: 20rpx; }
.pb-20 { padding-bottom: 20rpx; }
.mt-10 { margin-top: 10rpx; }
.mt-20 { margin-top: 20rpx; }
.mt-8 { margin-top: 8rpx; }
.mt-4 { margin-top: 4rpx; }
.mb-12 { margin-bottom: 12rpx; }
.mb-20 { margin-bottom: 20rpx; }
.mb-28 { margin-bottom: 28rpx; }
.mr-16 { margin-right: 16rpx; }
.mr-20 { margin-right: 20rpx; }
.fs-20 { font-size: 20rpx; }
.fs-22 { font-size: 22rpx; }
.fs-24 { font-size: 24rpx; }
.fs-28 { font-size: 28rpx; }
.fs-30 { font-size: 30rpx; }
.fs-32 { font-size: 32rpx; }
.fw-500 { font-weight: 500; }
.fw-600 { font-weight: 600; }
.color-333 { color: #333; }
.color-666 { color: #666; }
.color-999 { color: #999; }
.color-primary { color: #e74c3c; }
.color-theme { color: #419D95; }
.color-fff { color: #fff; }
.bg-fff { background-color: #fff; }
.bg-theme { background-color: #419D95; }
.flex { display: flex; }
.flex-center { display: flex; align-items: center; justify-content: center; }
.flex-align-center { display: flex; align-items: center; }
.py-12 { padding-top: 12rpx; padding-bottom: 12rpx; }
.px-24 { padding-left: 24rpx; padding-right: 24rpx; }
</style>
