<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.title }}</span>
              </div>
            </template>
            <div class="flex flex-col">
              <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="套餐版本">
                <el-radio-group v-model="form.image">
                  <el-radio-button value="1" border>基础版</el-radio-button>
                  <el-radio-button value="2" border>标准版</el-radio-button>
                  <el-radio-button value="3" border>专业版</el-radio-button>
                </el-radio-group>
              </el-form-item>
<!--              <el-form-item label="交付方式" v-if="form.deliveryMethod">-->
<!--                <el-tag v-if="form.deliveryMethod == 1">SaaS交付</el-tag>-->
<!--                <el-tag v-if="form.deliveryMethod == 2">源码交付</el-tag>-->
<!--              </el-form-item>-->
              <el-form-item label="购买时长" v-if="form.chargingMethod && form.chargingMethod > 1">
                <el-radio-group v-model="form.chargingMethod" @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>
<!--              <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.title }}</el-descriptions-item>
            <el-descriptions-item label="产品类型：">{{ form.type == 1 ? '插件' : '完整应用' }}</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-2xl text-red-600">{{ cart.totalPrice }}</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="400"
      :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">
      <el-avatar :size="250" src="https://oss.wsdns.cn/20240409/247a492abda94b08ace33fa5405628ca.jpeg"
                 shape="square"/>
    </div>
    <template #footer>
      <div class="dialog-footer text-center pb-3">
        <el-button type="success" @click="onDone">
          已完成支付
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import {useConfigInfo, useToken, useWebsite} from "~/composables/configState";
import useFormData from '@/utils/use-form-data';
import type {User} from '@/api/system/user/model';
import {ref} from 'vue'
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";
import type {CmsProduct} from "~/api/cms/cmsProduct/model";
import type {CmsProductParameter} from "~/api/cms/cmsProductParameter/model";
import type {CmsProductUrl} from "~/api/cms/cmsProductUrl/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 formRef = ref<FormInstance>()
const config = useConfigInfo();
const token = useToken();
const userInfo = ref<User>();
const cart = useCart();

// 配置信息
const {form, assignFields} = useFormData<CmsProduct>({
  // 自增ID
  productId: undefined,
  // 类型 0软件产品 1实物商品 2虚拟商品
  type: undefined,
  // 产品编码
  code: undefined,
  // 产品标题
  title: undefined,
  // 封面图
  image: undefined,
  // 产品详情
  content: undefined,
  // 父级分类ID
  parentId: undefined,
  // 产品分类ID
  categoryId: undefined,
  // 产品规格 0单规格 1多规格
  specs: undefined,
  // 货架
  position: undefined,
  // 单位名称 (个)
  unitName: undefined,
  // 进货价格
  price: undefined,
  // 销售价格
  salePrice: undefined,
  // 库存计算方式(10下单减库存 20付款减库存)
  deductStockType: undefined,
  // 轮播图
  files: undefined,
  // 销量
  sales: undefined,
  // 库存
  stock: undefined,
  // 安装次数
  install: undefined,
  // 消费赚取积分
  gainIntegral: undefined,
  // 计费方式
  durationMethod: undefined,
  // 推荐
  recommend: undefined,
  // 商户ID
  merchantId: undefined,
  merchantName: undefined,
  merchantAvatar: undefined,
  merchantComments: undefined,
  // 状态（0：未上架，1：上架）
  isShow: undefined,
  // 状态, 0上架 1待上架 2待审核 3审核不通过
  status: undefined,
  // 备注
  comments: undefined,
  // 排序号
  sortNumber: undefined,
  // 用户ID
  userId: undefined,
  // 是否删除, 0否, 1是
  deleted: undefined,
  // 租户id
  tenantId: undefined,
  // 创建时间
  createTime: undefined,
  // 修改时间
  updateTime: undefined,
  // 父级分类名称
  parentName: undefined,
  // 父级分类路径
  parentPath: undefined,
  // 分类名称
  categoryName: undefined,
  // 评分
  rate: undefined,
  // 是否已购买
  isBuy: undefined,
  // 是否已安装插件
  installed: undefined,
  // 产品参数
  parameters: undefined,
  // 产品链接
  links: undefined,
  // 插件入口
  path: undefined,
  // 标签
  tag: undefined,
  // 菜单ID
  menuId: 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 = cart.value.num * cart.value.payPrice * cart.value.month;
  // cart.value.totalPrice = Math.round(cart.value.totalPrice * 100) / 100;
}

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;
  useClientRequest<ApiResult<any>>(`/shop/shop-order/createOrder`, {
    method: 'POST',
    body: cart.value
  }).then(res => {
    if (res.code == 0) {
      ElMessage.success(res.message)
    } else {
      return ElMessage.error(res.message)
    }
  })
}

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;
  }
  const {data: response} = await useServerRequest<ApiResult<CmsProduct>>(`/cms/cms-product/${getIdBySpm(5)}`)
  console.log(response.value?.data,'response')
  if (response.value?.data) {
    assignFields(response.value?.data);
    form.categoryName = '选择套餐';
    if(response.value?.data.price){
      cart.value.payPrice = response.value?.data.price;
      cart.value.comments = `${response.value?.data.title}`;
      if(cart.value.num){
        cart.value.totalPrice = response.value?.data.price * cart.value.num
      }
      let goodsName = '';
      // if(form.type == 0){
      //   goodsName = `【软件】${form.title}`
      // }
      // if(form.type == 1){
      //   goodsName = `【插件】${form.title}`
      // }
      // cart.value.orderProduct?.push({
      //   goodsId: form.productId,
      //   goodsName: goodsName,
      //   image: form.image,
      //   price: response.value?.data.price,
      //   totalPrice: cart.value.totalPrice,
      //   num: cart.value.num,
      //   month: cart.value?.month,
      //   payType: cart.value.payType
      // });
    }
    useHead({
      title: `${form.title}`,
      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 = () => {
  useClientRequest<ApiResult<any>>(`/system/menu/install`, {
    method: 'POST',
    body: {
      productId: 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>
