<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="120px">
          <el-form-item label="巡检类型" prop="inspectionType">
            <el-select v-model="dataForm.inspectionType" placeholder="巡检类型">
              <el-option :label="item.dictLabel" :value="item.dictValue" v-for="item in state.getDictByKey('inspectionType')"></el-option>
          </el-select>
      </el-form-item>
          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker
            v-model="dataForm.startDate"
            type="datetime"        
            placeholder="选择开始日期"
            value-format="YYYY-MM-DD HH:mm:ss" 
            style="width: 100%;"
          ></el-date-picker>
      </el-form-item>
          <el-form-item label="结束日期" prop="endDate">
            <el-date-picker
            v-model="dataForm.endDate"
            type="datetime"        
            placeholder="选择结束日期"
            value-format="YYYY-MM-DD HH:mm:ss" 
            style="width: 100%;"
          ></el-date-picker>
      </el-form-item>
          <el-form-item label="巡检照片" prop="filePath">
            <el-upload
              class="avatar-uploader"
              :action="action"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
      </el-form-item>
          <el-form-item label="审阅状态" prop="status">
            <el-select v-model="dataForm.status" placeholder="审阅状态">
            <el-option :label="item.dictLabel" :value="item.dictValue" v-for="item in state.getDictByKey('inspectionReviewStatus')"></el-option>
          </el-select>
      </el-form-item>
                  <el-form-item label="备注" prop="remark">
        <el-input v-model="dataForm.remark" placeholder="备注"></el-input>
      </el-form-item>
      </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import app from "@/constants/app";
import { getToken } from "@/utils/cache";
import { parseTime } from '@/utils/ruoyi'
import { reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus";
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
const emit = defineEmits(["refreshDataList"]);
import useView from "@/hooks/useView";
const state = reactive({ ...useView({}) });

const action = `${app.api}/sys/oss/upload`;
const headers = {token:  getToken() }
const imageUrl = ref('');
const visible = ref(false);
const dataFormRef = ref();

const dataForm = reactive({
  id: '',  inspectionType: '',  startDate: '',  endDate: '',  filePath: '',  status: '',  creator: '',  createDate: '',  updater: '',  updateDate: '',  remark: ''});

const rules = ref({
          inspectionType: [
      { required: true, message: '必填项不能为空', trigger: 'blur' }
    ],
          startDate: [
      { required: true, message: '必填项不能为空', trigger: 'blur' }
    ],
          endDate: [
      { required: true, message: '必填项不能为空', trigger: 'blur' }
    ],
          status: [
      { required: true, message: '必填项不能为空', trigger: 'blur' }
    ]
  });

const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
    imageUrl.value = '';
  }

  if (id) {
    getInfo(id);
  }
};

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  if(response.code!==0) return ElMessage.error(response.msg);
  imageUrl.value = response?.data?.src;
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!['image/jpeg','image/png','image/jpp'].includes(rawFile.type)) {
    ElMessage.error('请上传jpg/png格式的图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('图片大小不能超过10MB!')
    return false
  }
  return true
}

// 获取信息
const getInfo = (id: number) => {
  baseService.get("/emergency/inspection/" + id).then((res) => {
    Object.assign(dataForm, res.data);
    dataForm.inspectionType = dataForm.inspectionType + '';
    dataForm.status = dataForm.status + '';
    imageUrl.value = dataForm.filePath;
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    if(!imageUrl.value) return ElMessage.error('请上传图片');
    dataForm.startDate = dataForm.startDate ? parseTime(new Date(dataForm.startDate), '{yy}-{mm}-{dd} {hh}:{ii}:{ss}') : null;
    dataForm.endDate = dataForm.endDate ? parseTime(new Date(dataForm.endDate), '{yy}-{mm}-{dd} {hh}:{ii}:{ss}') : null;
    dataForm.filePath = imageUrl.value;
    (!dataForm.id ? baseService.post : baseService.put)("/emergency/inspection", dataForm).then((res) => {
      ElMessage.success({
        message: '成功',
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

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