<template>
  <div class="AddBuildingBox">
    <PageHeader></PageHeader>
    <div class="AddBuildingBody">
      <div class="title">基本信息</div>
      <div class="addBuildingFormBody">
        <el-form class="formBody" label-position="right" ref="formRef" :model="form" :rules="rules" label-width="130px">
          <el-form-item label="Banner名称" prop="name">
            <el-input v-model.trim="form.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="Banner图" prop="url">
            <el-upload
              class="avatar-uploader"
              ref="uploadRef"
              accept=".png, .jpg"
              :action="uploadUrl"
              name="file"
              :headers="headerToken()"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              v-on:error="handleAvatarError"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.url" :src="form.url" class="avatar" alt="" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">支持jpg, png等格式文件上传，文件大小不超过10MB.</div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item label="跳转链接" prop="link">
            <el-input v-model.trim="form.link" placeholder="请输入跳转链接" />
          </el-form-item>
          <el-form-item label="排序号" prop="byOrder">
            <el-input-number v-model.trim="form.byOrder" placeholder="请输入" />
          </el-form-item>
          <el-form-item style="margin-top: 30px">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="cancelForm">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import PageHeader from '@/components/Pageheader/index.vue';
import { addBanner, getBanner, updateBanner } from '@/api/system/Banner';
import { useUserStore } from '@/store/modules/user';
import { UploadProps, UploadRawFile } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/car/uploadImage';

const router = useRouter();
const route = useRoute();

function headerToken() {
  const useStore = useUserStore();
  return {
    Authorization: 'Bearer ' + useStore.token
  };
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: UploadRawFile) => {
  const type = rawFile.type.split('/').pop();
  if (['png', 'jpg', 'jpeg'].includes(type)) {
    if (rawFile.size / 1024 / 1024 <= 10) {
      return true;
    } else {
      ElMessage.warning('图片大小超过10M,请重新上传');
      return false;
    }
  } else {
    ElMessage.warning('图片格式不是 png/jpg 格式, 请重新上传');
    return false;
  }
};
const handleAvatarSuccess: UploadProps['onSuccess'] = (response: any) => {
  if (response.code === 500) {
    form.value.url = '';
  } else if (response.code === 200) {
    form.value.url = response.data.url;
  }
};

const handleAvatarError: UploadProps['onError'] = (respones) => {};

const formRef = ref();
const form = ref({
  id: null,
  name: '', // 分类id、
  url: '', // 设备名称
  link: '', // 编号
  status: '1',
  byOrder: 1 // 区域
});
const rules = ref({
  name: [{ required: true, message: '请输入Banner图名称', trigger: 'blur' }],
  url: [{ required: true, message: '请上传图片', trigger: 'blur' }]
});
const userid = ref(null);

function init() {
  if (route.query.id) {
    userid.value = route.query.id;
    getBanner(userid.value).then((res) => {
      form.value = {
        id: res.data.id,
        name: res.data.name, // 分类id、
        url: res.data.url, // 设备名称
        status: res.data.status ?? '0',
        link: res.data.link, // 编号
        byOrder: res.data.byOrder // 区域
      };
    });
  }
}
init();

// !== 提交 =============================================================================
// 提交
const submitForm = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (userid.value) {
        updateBanner(form.value).then(() => {
          ElMessage.success('编辑成功');
          cancelForm();
        });
      } else {
        addBanner(form.value).then(() => {
          ElMessage.success('添加成功');
          cancelForm();
        });
      }
    }
  });
};
// 推出
const cancelForm = () => {
  router.back();
};
</script>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
:deep(.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);
}
:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 1.1rem;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.AddBuildingBox {
  padding: 15px;
  height: 100%;
  width: 100%;
}
.AddBuildingBody {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background-color: white;
  padding: 15px;
  .title {
    height: 40px;
    line-height: 40px;
    padding-left: 20px;
    background-color: rgba(255, 255, 255, 1);
    color: rgba(16, 16, 16, 1);
    border-bottom: 1px solid #bbbbbb;
    margin-bottom: 60px;
  }

  .formBody {
    width: 650px;
    margin: 0 auto;

    .checkoutuserbox {
      margin: 5px;
      border: 1px solid #ccc;
      padding: 5px 10px;
      border-radius: 5px;
      &.add {
        cursor: pointer;
        border-style: dashed;
        &:hover {
          color: #409eff;
          border-color: #409eff;
        }
      }
      & > div {
        cursor: pointer;
        margin-left: 10px;
        &:hover {
          color: red;
        }
      }
    }
    &:deep(.el-form-item__content, .el-select, .el-input) {
      width: 350px !important;
      margin-right: 10px;
      .el-cascader {
        width: 100%;
      }
    }
    .el-form-item {
      margin-bottom: 20px;
      align-items: center;
    }
    .el-button {
      width: 80px;
      height: 35px;
      margin-right: 20px;
    }
  }
}
</style>
