<template>

  <!-- 主体部分 -->
  <div class="clearfix p-5" style="border-top: #f9f9f9 16px solid;">

    <div class="m-page">
      <div class="sitemp h-[32px] flex justify-between">
        <h2>矛盾纠纷收集与处理</h2>
      </div>
      <div class="form-box p-5">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120"
          label-position="top"
          status-icon
        >
          <el-form-item :label="`您的姓名`" prop="realName" class=" p-2 text-left">
            <el-input v-model="form.realName" class="text-left" :placeholder="`您的姓名`"/>
          </el-form-item>
          <el-form-item :label="`手机号码`" prop="phone" class=" p-2">
            <el-input v-model="form.phone" :maxlength="11" :placeholder="`手机号码`"/>
          </el-form-item>
          <el-form-item :label="`您的住址`" prop="address" class="p-2 text-left">
            <el-cascader v-model="value" class="w-full" :options="options" placeholder="所在城区" @change="handleChange" />
            <el-input class="mt-2" v-model="form.address" :placeholder="`您的住址`"/>
          </el-form-item>
          <el-form-item :label="`纠纷描述`" prop="content" class=" p-2">
            <el-input type="textarea" :rows="5" cols="80" v-model="form.content"
                      :placeholder="`您要反映的矛盾纠纷内容`"/>
          </el-form-item>
          <el-form-item :label="`附件上传`" prop="files" class=" p-2">
            <el-upload
              v-model:file-list="files"
              action="https://server.gxwebosoft.com/api/oss/upload"
              :headers="{
                          Authorization: token,
                          TenantId: 5,
                        }"
              :limit="8"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="filesRemove"
              :on-success="filesSuccess"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
<!--          <el-form-item :label="`验证码`" prop="code" class=" 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="ml-2 w-full">
              <el-button type="primary" size="large" class="block w-full" @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 {ArrowRight, Plus} from '@element-plus/icons-vue'
import type {UploadProps, UploadUserFile} from 'element-plus'
import type {FormInstance, FormRules} from 'element-plus'
import RegionsData from '~/api/json/regions-data.json'
import type {CmsOrder} from "~/api/cms/cmsOrder/model";
import useFormData from "~/utils/use-form-data";
import {addCmsOrder} from "~/api/cms/cmsOrder";
import {getCaptcha} from "~/api/passport/login";

// 引入状态管理
const route = useRoute();
const token = useToken();
const files = ref<UploadUserFile[]>([])

const srcList = ref<string[]>([])
const address = ref<string>()
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: 1,
  // 关联项目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,
  // 图像验证码内容
  files: 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'},
  ],
  address: [
    {required: true, message: '请填写您的住址', trigger: 'blur'},
  ],
  realName: [
    {required: true, message: '请输入联系人姓名', trigger: 'blur'},
  ],
  content: [
    {required: true, message: '请输入纠纷内容', trigger: 'blur'},
  ]
})

const value = ref([])
const options = ref<any>([])
const props = {
  expandTrigger: 'hover' as const,
}

const handleChange = (value:any) => {
  address.value = ''
  console.log(value)
  const province = RegionsData.find(item => item.value == value[0]);
  if(province){
    address.value = `${province?.label}`
    const city = province.children?.find(item => item.value == value[1]);
    if(city){
      address.value = `${province?.label}${city.label}`
      const region = city.children?.find(item => item.value == value[2]);
      if(region){
        address.value = `${province?.label}${city.label}${region.label}`
      }
    }
  }
}

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

// 请求数据
const reload = async () => {
  form.content = ''
  // seo
  useSeoMeta({
    description: form.comments || form.title,
    keywords: form.title,
    titleTemplate: `${form?.title || '矛盾纠纷收集平台'}` + ' - %s',
  })
  const gx = RegionsData.find(item => item.value == '450000')
  options.value = gx?.children
  changeCaptcha();
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const filesRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  form.files = JSON.stringify('');
}

const filesSuccess = (e: any) => {
  srcList.value.push(e.data.downloadUrl)
}

// 提交表单
const submitForm = (formEl: FormInstance | undefined) => {
  if (process.client) {
    addCmsOrder({
      ...form,
      files: JSON.stringify(srcList.value) || undefined,
      address: `${address.value} ${form.address}`
    }).then(res => {
      if (res.code == 0) {
        resetFields();
        files.value = []
        ElMessage.success(res.message)
      } else {
        return ElMessage.error(res.message)
      }
    })
  }
}

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

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

<style lang="scss">
</style>
