<template>
  <div>    
    <el-dialog
      v-model="state.showDialog"
      destroy-on-close
      :title="title"
      draggable
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="500px"
    >
      <el-form ref="formRef" :model="form" size="default" label-width="80px">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="活动名称" prop="name" :rules="[{ required: true, message: '请输入活动名称', trigger: ['blur', 'change'] }]">
              <el-input v-model="form.name" autocomplete="off" placeholder="活动名称"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="跳转方式">
                <el-select v-model="form.skipWay" prop="skipWay" placeholder="跳转方式">                  
                  <el-option label="请选择" value="0"></el-option>
                  <el-option label="文章详情" value="1"></el-option>
                  <el-option label="项目详情" value="2"></el-option>
                </el-select>                
              </el-form-item>
            </el-col>                                          
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="跳转参数" prop="skipContent">
              <el-input v-model="form.skipContent" autocomplete="off" placeholder="文章ID或项目ID(不填写则无跳转)"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                  <el-form-item label="活动图片(690X260)" prop="imgUrl" :rules="[{ required: true, message: '请上传活动图片'}]">
                    <el-upload class="avatar-uploader"                  
                  :data="{ fileDirectory: state.fileDirectory }"
                  :action="ImgAction"  
                  :headers="imgHeaders"
                  :show-file-list="false" 
                  :on-success="onImgSuccess"
              :on-error="onImgError">
                    <img v-if="form.imgUrl" :src="form.imgUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>                                   
                  </el-form-item>
                </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="排序" prop="rank" >
                <el-input v-model="form.rank" autocomplete="off" placeholder="数值越大越靠前"/>
              </el-form-item>
            </el-col>          
                                                    
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="onSure" size="default" :loading="state.sureLoading">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup name="admin/banner/form">

// import { stat } from 'fs'
import { reactive, toRefs, getCurrentInstance, ref, computed } from 'vue'
import { BannerAddInput, BannerUpdateInput } from '/@/api/admin/data-contracts'
import { BannerApi } from '/@/api/admin/Banner'
import eventBus from '/@/utils/mitt'
import { useUserInfo } from '/@/stores/userInfo'
import pinia from '/@/stores/index'
import { AxiosResponse } from 'axios'

const storesUserInfo = useUserInfo(pinia)


defineProps({
  title: {
    type: String,
    default: '',
  },
})

const { proxy } = getCurrentInstance() as any


const formRef = ref()
const state = reactive({
  showDialog: false,
  sureLoading: false,  
  form: {} as BannerAddInput & BannerUpdateInput,   
  token: storesUserInfo.getToken(),
  fileDirectory:'banners',
  imgLoading:false
})
const { form } = toRefs(state)


// 打开对话框
const open = async (row: any = {}) => {  
    
  if (row.id > 0) {
    const res = await new BannerApi().get({ id: row.id }, { loading: true }).catch(() => {
      proxy.$modal.closeLoading()
    })

    if (res?.success) {
      state.form = res.data as BannerAddInput & BannerUpdateInput     
    }
  } else {
    state.form = {} as BannerAddInput & BannerUpdateInput    
  }
  state.showDialog = true
}


// 取消
const onCancel = () => {   
  state.showDialog = false
}

// 确定
const onSure = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return    
    state.sureLoading = true    
    let res = {} as any
    if (state.form.id != undefined && state.form.id > 0) {
      res = await new BannerApi().update(state.form, { showSuccessMessage: true }).catch(() => {
        state.sureLoading = false
      })
    } else {
      res = await new BannerApi().add(state.form, { showSuccessMessage: true }).catch(() => {
        state.sureLoading = false
      })
    }
    state.sureLoading = false

    if (res?.success) {
      eventBus.emit('refreshBanner')
      state.showDialog = false
    }
  })
}
// 上传请求url
const ImgAction = computed(() => {
  return import.meta.env.VITE_API_URL + '/api/admin/file/upload-file'
})
// 上传请求头部
const imgHeaders = computed(() => {
  return { Authorization: 'Bearer ' + state.token }
})
// 上传头像成功
const onImgSuccess = (res: AxiosResponse) => {
  state.imgLoading = false  
  if (!res?.success) {
    if (res.msg) {
      proxy.$modal.msgError(res.msg)
    }
    return
  }
  
  state.form.imgUrl = res?.data?.linkUrl  
}

// 上传头像失败
const onImgError = (error: any) => {
  state.imgLoading = false
  let message = ''
  if (error.message) {
    try {
      message = JSON.parse(error.message)?.msg
    } catch (err) {
      message = error.message || ''
    }
  }
  if (message) proxy.$modal.msgError(message)
}

defineExpose({
  open,
})
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 120px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 300px;
  height: 120px;
  display: block;
}
</style>