<template>
  <div class="main-content">
    <BaseTable
      ref="tableRef"
      :tableHeader="tableHeader"
      :tableData="tableData"
      :searchParams="searchParams"
      @searchFn="searchFn"
      @resetFn="resetFn"
      :moreOperation="false"
      @addFn="addFn"
    >
      <template #search>
        <el-form-item label="手机号">
          <el-input v-model.trim="searchParams.name" />
        </el-form-item>
        <el-form-item label="内容关键字">
          <el-input v-model.trim="searchParams.description" />
        </el-form-item>
      </template>
    </BaseTable>

    <el-dialog width="900px" :title="formDialog.title" v-model="formDialog.visible" :close-on-click-modal="false">
      <el-form ref="formRef" size="small" label-width="120px" :model="formDialog.formData" :rules="formDialog.formRules">
        <el-row>
          <el-form-item label="许愿树名称" prop="name">
            <el-input v-model.trim="formDialog.formData.name" />
          </el-form-item>
          <el-form-item label="经度" prop="longitude">
            <el-input v-model.trim="formDialog.formData.longitude" />
          </el-form-item>
          <el-form-item label="纬度" prop="latitude">
            <el-input v-model.trim="formDialog.formData.latitude" />
          </el-form-item>
          <el-form-item label="可许愿半径" prop="radius">
            <el-input type="number" v-model.number="formDialog.formData.radius" />
          </el-form-item>
          <el-form-item label="封面图片" prop="coverImage">
            <el-input style="display: none" v-model.trim="formDialog.formData.coverImage" />
            <el-upload
              class="avatar-uploader"
              :action="upload.action"
              :headers="upload.headers"
              :show-file-list="false"
              :on-success="handleSuccess"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="许愿树描述" prop="description">
            <el-input type="textarea" v-model.trim="formDialog.formData.description" :rows="4" />
          </el-form-item>
        </el-row>
      </el-form>
      <template #footer>
        <el-button type="primary" :loading="formDialog.loading" @click="submitFn">确定</el-button>
        <el-button @click="cancelFn">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { creatTree, queryTreePage } from '@/api/wishing/tree'
import { isNumber, isInteger } from '@/utils/validate'
import { useUserStore } from '@/stores/user'
import type { FormInstance, FormRules } from 'element-plus'

const userStore = useUserStore()
const tableRef = ref()
const formRef = ref<FormInstance>()
const imageUrl = ref('')

const defaultSearch = {
  current: 1,
  size: 10,
  total: 0
}

const searchParams = reactive({ ...defaultSearch, name: '', description: '' })

const upload = computed(() => ({
  headers: { Authorization: `Bearer ${userStore.accessToken}` },
  action: '/dgapi/upms/attachment/upload-file'
}))

const tableHeader = [
  { label: '许愿树名称', prop: 'name', align: 'center' as const },
  { label: '经度', prop: 'longitude', align: 'center' as const },
  { label: '纬度', prop: 'latitude', align: 'center' as const },
  { label: '地址', prop: 'address', align: 'center' as const },
  { label: '封面图片', prop: 'coverImage', align: 'center' as const },
  { label: '是否启动', prop: 'isActive', align: 'center' as const },
  { label: '可许愿半径', prop: 'radius', align: 'center' as const },
  {
    label: '许愿次数', prop: 'totalWishes', align: 'center' as const, type: 'render',
    render: (_h: any, params: any) => params.row.totalWishes || 0
  },
  { label: '创建时间', prop: 'createdAt', align: 'center' as const }
]

const tableData = ref<any[]>([])

const formDialog = reactive({
  title: '',
  visible: false,
  loading: false,
  isAdd: false,
  formData: {
    id: 0,
    address: '',
    coverImage: '',
    description: '',
    latitude: null as number | null,
    longitude: null as number | null,
    name: '',
    radius: 100,
    totalWishes: 0
  },
  formRules: {
    name: [{ required: true, message: '请输入许愿树名称', trigger: 'blur' }],
    latitude: [
      { required: true, message: '请输入纬度', trigger: 'blur' },
      { validator: (_r: any, v: any, cb: any) => isNumber(v) ? cb() : cb(new Error('纬度只能是数字')), trigger: 'blur' }
    ],
    longitude: [
      { required: true, message: '请输入经度', trigger: 'blur' },
      { validator: (_r: any, v: any, cb: any) => isNumber(v) ? cb() : cb(new Error('经度只能是数字')), trigger: 'blur' }
    ],
    radius: [
      { validator: (_r: any, v: any, cb: any) => isInteger(v) ? cb() : cb(new Error('半径只能是整数')), trigger: 'blur' }
    ]
  } as FormRules
})

function searchFn(isReset = false) {
  if (isReset) {
    Object.assign(searchParams, defaultSearch)
  }
  queryTreePage(searchParams).then(
    (res: any) => {
      tableData.value = res.data.records
      searchParams.total = res.data.total
    },
    (error: any) => {
      ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
    }
  )
}

function resetFn() {
  Object.assign(searchParams, defaultSearch, { name: '', description: '' })
  searchFn()
}

function addFn() {
  formDialog.title = '新增'
  formDialog.visible = true
  formDialog.loading = false
  formDialog.isAdd = true
  formDialog.formData = {
    id: 0, address: '', coverImage: '', description: '',
    latitude: null, longitude: null, name: '', radius: 100, totalWishes: 0
  }
  imageUrl.value = ''
}

function cancelFn() {
  formDialog.visible = false
  formDialog.loading = false
  formRef.value?.resetFields()
}

function submitFn() {
  if (!formRef.value) return
  formDialog.loading = true
  if (!formDialog.formData.coverImage) {
    ElMessage.error('请上传封面图片')
    formDialog.loading = false
    return
  }
  formRef.value.validate((valid) => {
    if (!valid) {
      formDialog.loading = false
      return
    }
    creatTree(formDialog.formData as any).then(
      () => {
        ElMessage.success('新增成功')
        formDialog.visible = false
        formDialog.loading = false
        searchFn(true)
      },
      (error: any) => {
        ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
        formDialog.loading = false
      }
    )
  })
}

function handleSuccess(res: any) {
  if (res.code === 200) {
    imageUrl.value = res.data.url
    formDialog.formData.coverImage = res.data.url
  } else {
    ElMessage.error(res.msg)
  }
}

searchFn()
</script>

<style scoped lang="less">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 2px dashed #d9d9d9;
}
</style>
