<template>
  <PageBanner :form="form" :active="active"/>
  <div class="page-main md:w-screen-xl m-auto p-3">
    <el-row :gutter="24">
      <el-col :span="16" :xs="24">
        <el-form :model="form" label-width="auto" label-position="left" class="w-full">
          <el-card shadow="hover" class="mb-4">
            <template #header>
              <div class="card-header font-bold">
                <span v-if="form.type === 0">【产品】</span>
                <span v-if="form.type === 1">【插件】</span>
                <span>{{ form.shortName }}</span>
              </div>
            </template>
            <div class="flex flex-col">
              <el-form-item label="套餐版本">
                <el-radio-group v-model="form.image">
                  <el-radio-button value="1" border>基础版</el-radio-button>
                  <el-radio-button value="2" border disabled>专业版</el-radio-button>
                  <el-radio-button value="3" border disabled>定制版</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="项目名称">
                <el-input v-model="cart.appName" style="width: 360px" placeholder="花味官网"></el-input>
              </el-form-item>
              <el-form-item label="二级域名">
                <el-input
                    v-model="cart.domain"
                    style="width: 360px"
                    placeholder="huawei"
                >
                  <template #prepend>Https://</template>
                  <template #append>.wsdns.cn</template>
                </el-input>
              </el-form-item>
<!--              <el-form-item label="类型">-->
<!--                  <el-radio-button v-if="form.type == 0" border>完整应用</el-radio-button>-->
<!--                  <el-radio-button v-if="form.type == 1" border>插件</el-radio-button>-->
<!--              </el-form-item>-->
<!--              <el-form-item label="交付方式" v-if="form.deliveryMethod">-->
<!--                <el-radio-button v-if="form.deliveryMethod == 1" border>SaaS交付</el-radio-button>-->
<!--                <el-radio-button v-if="form.deliveryMethod == 2" border>源码交付</el-radio-button>-->
<!--              </el-form-item>-->
              <el-form-item label="购买时长" v-if="form.chargingMethod && form.chargingMethod > 1">
                <el-radio-group v-model="cart.month" @change="handleChargingMethod">
                  <el-radio-button :value="1" border>1个月</el-radio-button>
                  <el-radio-button :value="12" border>1年</el-radio-button>
                  <el-radio-button :value="24" border>2年</el-radio-button>
                  <el-radio-button :value="36" border>3年</el-radio-button>
                  <el-radio-button :value="60" border>5年</el-radio-button>
                </el-radio-group>
              </el-form-item>

<!--              单价 {{ form.price }} x 购买时长 {{ cart.month }} x 数量 {{ cart.num }} x 折扣 0.1= {{ cart.totalPrice }}-->
<!--              <el-form-item label="购买数量">-->
<!--                <el-input-number v-model="cart.num" :min="1" :max="form.canBuyNumber" @change="handleChange"/>-->
<!--              </el-form-item>-->
            </div>
          </el-card>
          <el-card shadow="hover" class="mb-4">
            <template #header>
              <div class="card-header font-bold">
                <span>服务协议</span>
              </div>
            </template>
            <div class="flex items-center">
              <el-checkbox v-model="isAgree" @change="changeIsAgree"></el-checkbox>
              <span class="ml-1">我已阅读并同意</span>
              <span class="text-blue-400 hover:text-blue-500 cursor-pointer"
                    @click="openSpmUrl(`/detail`, {}, 357, true)">《用户协议》</span>
              <span class="text-blue-400 hover:text-blue-500 cursor-pointer"
                    @click="openSpmUrl(`/detail`, {}, 69, true)">《隐私协议》</span>
              <span class="text-blue-400 hover:text-blue-500 cursor-pointer"
                    @click="openSpmUrl(`/detail`, {}, 69, true)">《产品购买协议》</span>
            </div>
          </el-card>
        </el-form>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-card shadow="hover" class="mb-4">
          <template #header>
            <div class="card-header font-bold">
              <span>订单详情</span>
            </div>
          </template>
          <el-descriptions :title="`订购产品`" :column="1" class="mb-4">
            <el-descriptions-item label="产品名称：">{{ form.shortName }}</el-descriptions-item>
            <el-descriptions-item label="产品类型：">{{ form.type == 1 ? '插件' : '完整应用' }}</el-descriptions-item>
            <el-descriptions-item label="交付方式：">{{ form.deliveryMethod == 1 ? 'SaaS交付' : '源码交付' }}</el-descriptions-item>
            <el-descriptions-item label="应用名称：">{{ cart.appName }}</el-descriptions-item>
<!--            <el-descriptions-item label="套餐版本：">标准版</el-descriptions-item>-->
            <el-descriptions-item label="购买数量：">{{ cart.num }} 套</el-descriptions-item>
            <el-descriptions-item label="购买时长：">{{ cart.month }} 个月</el-descriptions-item>
<!--            <el-descriptions-item label="到期时间：">2025-10-06</el-descriptions-item>-->
          </el-descriptions>
          <el-descriptions title="合计：" :column="1" class="mb-4">
            <el-descriptions-item label="订单金额："><span class="line-through">￥</span><span
                class="text-xl line-through">{{ cart.totalPrice }}</span></el-descriptions-item>
            <el-descriptions-item label="实付金额："><span class="text-red-600">￥</span><span
                class="font-bold text-xl text-red-600">{{ cart.payPrice }}</span></el-descriptions-item>
          </el-descriptions>
          <el-form-item>
            <el-button type="danger" class="w-full" :disabled="!isAgree" size="large" @click="onPay">去支付</el-button>
          </el-form-item>
        </el-card>
      </el-col>
    </el-row>
  </div>
  <el-dialog
      v-model="visible"
      title="订单确认"
      align-center
      width="450"
      :before-close="() => visible = false"
  >
    <div class="flex justify-center pt-3">
      <el-radio-group v-model="cart.payType" @change="handlePayType">
        <el-radio-button :value="102" border>微信支付</el-radio-button>
<!--        <el-radio-button :value="3" border>支付宝</el-radio-button>-->
        <el-radio-button :value="0" border>余额支付</el-radio-button>
      </el-radio-group>
    </div>
    <div class="flex justify-center py-4" v-if="cart.payType == 102">
      <el-avatar :size="250" :src="wxPayQrCode"
                 shape="square"/>
    </div>
    <template #footer>
      <div class="dialog-footer text-center pb-3" v-if="cart.payType != 0">
        <el-tag type="success" size="large">
          使用微信扫码完成支付
        </el-tag>
      </div>
      <div class="flex flex-col justify-center w-1/2 m-auto pb-12" v-if="cart.payType === 0">
        <span class="py-2 text-center">可用余额：￥{{ userInfo?.balance || 0.00 }}</span>
        <div class="flex flex-col">
          <el-input type="password" class="py-2" size="large" v-model="payPassword" maxlength="6" show-password placeholder="请输入支付密码" />
          <el-button type="danger" class="py-2 my-3" size="large" @click="onDone">
            确定支付
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import {useConfigInfo, useToken, useUser, useWebsite} from "~/composables/configState";
import useFormData from '@/utils/use-form-data';
import type {User} from '@/api/system/user/model';
import {ref} from 'vue'
import QRCode from 'qrcode';
import {useServerRequest} from "~/composables/useServerRequest";
import type {ApiResult} from "~/api";
import PageBanner from './components/PageBanner.vue';
import type {FormInstance} from "element-plus";
import {useClientRequest} from "~/composables/useClientRequest";
import type {Company} from "~/api/system/company/model";

// 配置信息
const runtimeConfig = useRuntimeConfig();
const route = useRoute();
const activeIndex = ref('');
const website = useWebsite()
const isAgree = ref<boolean>(true);
const active = ref<number>(1);
const visible = ref<boolean>(false);
const wxPayQrCode = ref<string>()
const payPassword = ref<string>()
const formRef = ref<FormInstance>()
const config = useConfigInfo();
const token = useToken();
const userInfo = useUser();
const cart = useCart();
const qrOptions = ref({
  width: 200, // 二维码宽度
  margin: 10, // 二维码边距
  color: { dark: '#000', light: '#fff' }, // 二维码颜色
});

// 配置信息
const {form, assignFields} = useFormData<Company>({
  companyId: undefined,
  menuId: undefined,
  type: undefined,
  appName: undefined,
  shortName: undefined,
  companyName: undefined,
  companyType: undefined,
  companyTypeMultiple: undefined,
  appType: undefined,
  companyLogo: undefined,
  image: undefined,
  companyCode: undefined,
  domain: undefined,
  phone: undefined,
  tel: undefined,
  email: undefined,
  InvoiceHeader: undefined,
  startTime: undefined,
  expirationTime: undefined,
  version: undefined,
  versionName: undefined,
  versionCode: undefined,
  members: undefined,
  storage: undefined,
  storageMax: undefined,
  buys: undefined,
  clicks: undefined,
  users: undefined,
  departments: undefined,
  industryParent: undefined,
  industryChild: undefined,
  country: undefined,
  province: undefined,
  city: undefined,
  region: undefined,
  address: undefined,
  latitude: undefined,
  longitude: undefined,
  businessEntity: undefined,
  comments: undefined,
  authentication: undefined,
  industryId: undefined,
  industryName: undefined,
  status: undefined,
  userId: undefined,
  official: undefined,
  deliveryMethod: undefined,
  chargingMethod: undefined,
  price: undefined,
  planId: undefined,
  sortNumber: undefined,
  authoritative: undefined,
  merchantId: undefined,
  tenantId: undefined,
  tenantName: undefined,
  tenantCode: undefined,
  modules: undefined,
  requestUrl: undefined,
  socketUrl: undefined,
  serverUrl: undefined,
  modulesUrl: undefined,
  merchantUrl: undefined,
  websiteUrl: undefined,
  mpWeixinCode: undefined,
  mpAlipayCode: undefined,
  h5Code: undefined,
  androidUrl: undefined,
  iosUrl: undefined,
  avatar: undefined,
  nickname: undefined,
  code: undefined,
  createTime: undefined,
  updateTime: undefined,
  password: undefined,
  password2: undefined,
  collection: undefined,
  recommend: undefined,
  title: undefined,
  parentName: undefined,
  categoryName: undefined,
});

const handleChange = (index:any): void => {
  cart.value.num = index;
  computeTotalPrice();
}

const handleChargingMethod = (index: any): void => {
  cart.value.month = index;
  computeTotalPrice();
}

const computeTotalPrice = () => {
  // 计算公式 = (商品价格 * 数量 * 月份) / 折扣率
  cart.value.totalPrice = Math.round(Number(form.price)*Number(cart.value.num)*Number(cart.value.month));
  cart.value.payPrice = Math.round(Number(cart.value.totalPrice) * Number(0.1));
}

const changeIsAgree = (index: any) => {
  if (index) {
    active.value = 2;
  }
}

const handlePayType = (index: any) => {
  cart.value.payType = index;
  onPay();
}

// 统一下单
const onPay = () => {
  visible.value = true;
  active.value = 3;
  // 余额支付
  if(cart.value.payType == 0){
    return;
  }
  // 微信支付
  if(cart.value.payType == 102){
    useClientRequest<ApiResult<any>>(`/system/wx-native-pay/codeUrl`, {
      method: 'POST',
      body: cart.value
    }).then(async res => {
      if (res.code == 0) {
        console.log(res.data)
        try {
          // 生成二维码图像数据URL
          wxPayQrCode.value = await QRCode.toDataURL(res.data);
        } catch (error) {
          console.error('Error generating QR code:', error);
        }
      } else {
        return ElMessage.error(res.message)
      }
    })
  }
  // 支付宝支付
  if(cart.value.payType == 3){
    return;
  }
}

const onSubmit = async () => {
  const {data: modify} = await useServerRequest<ApiResult<User>>('/auth/user', {
    baseURL: runtimeConfig.public.apiServer,
    method: 'put',
    body: form
  })
  if (modify.value?.code == 0) {
    ElMessage.success('修改成功')
  }
}

const reload = async () => {
  // 要求登录
  if (!token.value || token.value == '') {
    navigateTo(`/passport/login`)
    return false;
  }
  // useClientRequest(`/auth/user`, {}).then(res => {
  //   if(res?.data?.balance){
  //     cart.value.balance = res?.data?.balance;
  //   }
  // })
  const {data: response} = await useServerRequest<ApiResult<Company>>(`/system/company/${getIdBySpm(5)}`, {baseURL: runtimeConfig.public.apiServer})
  if (response.value?.data) {
    assignFields(response.value?.data);
    form.categoryName = '选择套餐';
    cart.value.comments = `购买${response.value?.data.shortName}`;
    if(response.value?.data.price){
      cart.value.payPrice = response.value?.data.price;
      computeTotalPrice();
    }
    useHead({
      title: `${form.shortName}`,
      meta: [{name: website.value.keywords, content: website.value.comments}]
    });
  }
}

// 扫码支付
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  ElMessage.error('还没有评分哦!')
  // if (form.rate === 0) {
  //   ElMessage.error('还没有评分哦!')
  //   return false;
  // }
  // form.productId = props.productId;
  // useClientRequest<ApiResult<any>>(`/cms/cms-product-comment/`, {
  //   method: 'POST',
  //   body: form
  // }).then(res => {
  //   if (res.code == 0) {
  //     ElMessage.success(res.message)
  //     visible.value = false
  //     resetFields();
  //     emit('done',1)
  //   } else {
  //     return ElMessage.error(res.message)
  //   }
  // })
}

// 余额支付
const onDone = () => {
  cart.value.type = 1;
  cart.value.list = [];
  cart.value.list?.push(form);
  useClientRequest<ApiResult<any>>(`/system/order/createOrder`, {
    method: 'POST',
    body: cart.value
  }).then(res => {
    if(res.code == 0){
      ElMessage.success('购买成功');
      visible.value = !visible.value;
      setTimeout(() => {
        openSpmUrl(`https://console.websoft.top/cost-center/order`)
      },500)
    }
    if(res.code == 1){
      ElMessage.error(res.message);
    }

  }).catch(res => {

  })

  // useClientRequest<ApiResult<any>>(`/system/menu/install`, {
  //   method: 'POST',
  //   body: {
  //     companyId: getIdBySpm(5)
  //   }
  // }).then(res => {
  //   if (res.code == 0) {
  //     ElMessage.success(res.message)
  //   } else {
  //     return ElMessage.error(res.message)
  //   }
  // })
}

watch(
    () => route.path,
    (path) => {
      activeIndex.value = path;
      console.log(path, '=>Path')
      reload();
    },
    {immediate: true}
);
</script>

<style lang="scss">
.text-a123 {
  color: #f0f2f5;
}
</style>
