<template>

  <!-- Banner -->
  <Banner :layout="layout" />

  <!-- 主体部分 -->
  <div class="clearfix p-5">

    <div class="m-page">
      <div class="sitemp h-[32px] flex justify-between">
        <h2>{{ $t('order.title') }}</h2>
        <Breadcrumb :data="page" :categoryName="page.categoryName" />
      </div>
      <div class="form-box p-5">
        <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="120"
            label-position="left"
            status-icon
        >
          <el-form-item :label="$t('order.title')" prop="title" class="hover:bg-gray-50 p-2">
            <el-input v-model="form.title" :placeholder="$t('order.title')"/>
          </el-form-item>
          <el-form-item :label="$t('order.content')" prop="content" class="hover:bg-gray-50 p-2">
            <el-input type="textarea" :rows="5" cols="80" v-model="form.content" :placeholder="$t('order.content')"/>
          </el-form-item>
          <el-form-item :label="$t('order.realName')" prop="realName" class="hover:bg-gray-50 p-2">
            <el-input v-model="form.realName" :placeholder="$t('order.realName')"/>
          </el-form-item>
          <el-form-item :label="$t('order.phone')" prop="phone" class="hover:bg-gray-50 p-2">
            <el-input v-model="form.phone" :maxlength="11" :placeholder="$t('order.phone')"/>
          </el-form-item>
          <el-form-item :label="$t('order.email')" prop="email" class="hover:bg-gray-50 p-2">
            <el-input v-model="form.email" :placeholder="$t('order.email')"/>
          </el-form-item>
          <el-form-item :label="$t('order.address')" prop="address" class="hover:bg-gray-50 p-2">
            <el-input v-model="form.address" :placeholder="$t('order.address')"/>
          </el-form-item>
          <el-form-item :label="$t('order.code')" prop="code" class="hover:bg-gray-50 p-2">
            <el-space class="flex">
              <el-input size="large" :placeholder="$t('order.imgCode')" maxlength="5" v-model="form.code" />
              <el-image :alt="$t('order.imgCode')" v-if="captcha" :src="captcha" @click="changeCaptcha" />
            </el-space>
          </el-form-item>
          <el-form-item>
            <div class="submitForm ml-2">
              <el-button type="primary" size="large" @click="submitForm(formRef)">
                {{ $t('order.submit') }}
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-dialog v-model="dialogVisible">
      <div class="flex justify-center">
        <el-image w-full :src="dialogImageUrl" alt="查看证件" />
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import {useLayout, usePage} from "~/composables/configState";
import {paramsId} from "~/utils/common";
import {ArrowRight} from '@element-plus/icons-vue'
import type {FormInstance, FormRules} from 'element-plus'
import type {CmsOrder} from "~/api/cms/cmsOrder/model";
import useFormData from "~/utils/use-form-data";
import {addCmsOrder} from "~/api/cms/cmsOrder";
import {getCmsArticle} from "~/api/cms/cmsArticle";
import {getCaptcha} from "~/api/passport/login";

// 引入状态管理
const route = useRoute();
const layout = useLayout();
const page = usePage();
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const dialogImageUrl = ref('')
// 验证码 base64 数据
const captcha = ref('');
const text = ref<string>('');


const {form, resetFields} = useFormData<CmsOrder>({
  // 订单号
  orderId: undefined,
  // 模型名称
  model: 'order',
  // 订单标题
  title: undefined,
  // 订单编号
  orderNo: undefined,
  // 订单类型，0商城 1询价 2留言
  type: undefined,
  // 关联项目ID，配合订单类型使用
  articleId: undefined,
  // 真实姓名
  realName: undefined,
  // 手机号码
  phone: undefined,
  // 电子邮箱
  email: undefined,
  // 收货地址
  address: undefined,
  // 订单内容
  content: undefined,
  // 订单总额
  totalPrice: '0.00',
  // 实际付款
  payPrice: '0.00',
  // 报价询价
  price: '0.00',
  // 购买数量
  totalNum: undefined,
  // 二维码地址，保存订单号，支付成功后才生成
  qrcode: undefined,
  // 下单渠道，0网站 1小程序 2其他
  channel: undefined,
  // 过期时间
  expirationTime: undefined,
  // 订单是否已结算(0未结算 1已结算)
  isSettled: undefined,
  // 用户id
  userId: undefined,
  // 备注
  comments: undefined,
  // 排序号
  sortNumber: undefined,
  // 是否删除, 0否, 1是
  deleted: undefined,
  // 租户id
  tenantId: undefined,
  // 创建时间
  createTime: undefined,
  // 图像验证码
  code: '',
})

const rules = reactive<FormRules<CmsOrder>>({
  title: [
    {required: true, message: '请输入产品名称', trigger: 'blur'},
  ],
  phone: [
    {required: true, message: '请输入手机号码', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'},
  ],
  realName: [
    {required: true, message: '请输入联系人姓名', trigger: 'blur'},
  ],
  content: [
    {required: true, message: '请输入留言内容', trigger: 'blur'},
  ]
})

/* 获取图形验证码 */
const changeCaptcha = async () => {
  getCaptcha().then(captchaData => {
    captcha.value = captchaData.base64;
    text.value = captchaData.text;
  })
};

// 请求数据
const reload = async () => {
  getCmsArticle(paramsId()).then(data => {
    form.articleId = data.articleId;
    layout.value.banner = data.banner;
    form.content = ''
    // seo
    useSeoMeta({
      description: form.comments || form.title,
      keywords: form.title,
      titleTemplate: `${form?.title}` + ' - %s',
    })
    changeCaptcha();
  })
}

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  if(form.code !== text.value){
    await reload();
    ElMessage.error('验证码不正确！');
    return false;
  }
  await formEl.validate((valid) => {
    if (valid) {
      addCmsOrder(form).then(res => {
        if (res.code == 0) {
          ElMessage.success(res.message)
          resetFields();
          reload();
        } else {
          return ElMessage.error(res.message)
        }
      })
    }
  })
}

onMounted(() => {
  // 在这里放置你想要在组件渲染完成后执行的代码
  console.log('组件已挂载');
});

watch(
    () => route.path,
    () => {
      reload();
    },
    { immediate: true }
);
</script>

<style lang="scss">
.content {
  padding-top: 15px;
  overflow: hidden;
  text-indent: 2em;
}
.content p{
  line-height: 2em;
}
.content img{
  padding: 10px;
  max-width: 100%;
}
</style>
