<template>
  <div class="create">
    <div class="breadcrumb">
      <ul>
        <li v-for="({ name, path }, i) in breadcrumbList" :key="name">
          <span v-if="i !== 0" class="separator">></span>
          <span :class="['breadcrumb-name', { pointer: path }]" @click="path ? $router.push(path) : ''">
            {{ name }}
          </span>
        </li>
      </ul>
    </div>
    <div class="basic-info">
      <div class="basic-info-title">基本信息</div>
      <el-form ref="form" :model="form" :rules="formRules" label-width="80px">
        <el-form-item label="封面" prop="picture_url">
          <el-upload
            class="cover-uploader"
            action="none"
            :show-file-list="false"
            :http-request="uploadCover"
            :before-upload="beforeCoverUpload"
          >
            <img v-if="form.picture_url" :src="form.picture_url" class="cover" />
            <div v-else class="cover-uploader-icon">
              <i class="el-icon-plus"></i>
              <span>点击上传封面</span>
            </div>
          </el-upload>
          <div class="tips">支持jpg、png格式图片，大小不超过5mb。</div>
        </el-form-item>
        <el-form-item label="书籍名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入内容" :maxlength="100" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入内容" :maxlength="20" />
        </el-form-item>
        <el-form-item label="现价" prop="price">
          <el-input v-model="form.price" placeholder="请输入内容" @input="handlePrice($event, 'price')">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="原价" prop="price_old">
          <el-input v-model="form.price_old" placeholder="请输入内容" @input="handlePrice($event, 'price_old')">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="标签" prop="label_name_list">
          <el-select
            v-model="form.label_name_list"
            class="label-select"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请输入标签，回车确认"
          />
        </el-form-item>
        <el-form-item label="分类" prop="type_id">
          <el-select v-model="form.type_id" placeholder="选择分类">
            <el-option v-for="{ id: typeId, name } in type_list" :key="typeId" :label="name" :value="typeId" />
          </el-select>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :autosize="{ minRows: 12 }"
            :maxlength="500"
            show-word-limit
            placeholder="请输入更多内容"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addBook">确定</el-button>
          <el-button @click="$router.push('/')">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { fileUpload } from '@/api/app';
import { GetBook, UpdateBook, AddBook, GetBookTypeList } from '@/api/book';
import { twoDecimal } from '@/utils/validate';

export default {
  name: 'CreateBookPage',
  data() {
    return {
      book_id: this.$route.query.book_id,
      form: {
        picture_url: '',
        picture_id: '',
        name: '',
        author: '',
        price: '',
        price_old: '',
        label_name_list: '',
        type_id: '',
        description: '',
      },
      formRules: {
        picture_url: [{ required: true, message: '请上传封面', trigger: 'blur' }],
        name: [{ required: true, message: '请输入书籍名称', trigger: 'blur' }],
        author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
        price: [{ required: true, message: '请输入现价', trigger: 'blur' }],
        type_id: [{ required: true, message: '请选择分类', trigger: 'blur' }],
        description: [{ required: true, message: '请输入简介', trigger: 'blur' }],
      },
      type_list: [],
      breadcrumbList: [
        { name: '教材管理', path: '/home' },
        { name: '新建教材', path: '' },
        { name: '基本信息', path: '' },
      ],
    };
  },
  created() {
    if (this.book_id) {
      this.getBookDetail();
    }
    GetBookTypeList().then(({ type_list }) => {
      this.type_list = type_list;
    });
  },
  methods: {
    uploadCover(file) {
      fileUpload('Mid', file, { isGlobalprogress: true }).then(({ file_info_list }) => {
        if (file_info_list.length > 0) {
          const { file_url, file_id } = file_info_list[0];
          this.form.picture_url = file_url;
          this.form.picture_id = file_id;
        }
      });
    },
    beforeCoverUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJPG) {
        this.$message.error('上传封面图片只能是 JPG 或 PNG 格式!');
        return false;
      }

      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error('上传封面图片大小不能超过 5MB!');
        return false;
      }
    },
    /**
     * @description 处理价格输入
     * @param {string | number} val 输入的值
     * @param {price | price_old} type 输入的类型
     */
    handlePrice(val, type) {
      this.form[type] = twoDecimal(val);
    },
    addBook() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.book_id) {
            this.updateBook();
          } else {
            AddBook({ ...this.form, sys_version_type: 1 }).then(({ id }) => {
              this.$router.push(`/book/setting/${id}`);
            });
          }
        } else {
          return false;
        }
      });
    },
    getBookDetail() {
      GetBook({ id: this.book_id }).then(
        ({ name, picture_id, picture_url, author, type_id, price, price_old, label_name_list, description }) => {
          this.form = {
            name,
            picture_id,
            picture_url,
            author,
            type_id,
            price,
            price_old,
            label_name_list,
            description,
          };
        },
      );
    },
    updateBook() {
      UpdateBook({ id: this.book_id, ...this.form })
        .then(() => {
          this.$router.push(`/book/setting/${this.book_id}`);
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.create {
  padding: 8px 24px;

  .breadcrumb {
    display: flex;
    align-items: center;

    > ul {
      display: flex;

      li {
        font-size: 14px;
        font-weight: 400;
        color: $font-light-color;

        .separator {
          margin: 0 8px;
          color: #c9cdd4;
        }

        &:nth-last-child(1) {
          font-weight: bold;
          color: $font-color;
        }
      }
    }
  }

  .basic-info {
    width: 1200px;
    padding: 24px;
    margin: 24px auto 16px;
    background-color: #fff;
    border-radius: 4px;

    &-title {
      margin-bottom: 24px;
      font-size: 18px;
      font-weight: bold;
    }

    .el-form {
      .el-input,
      .el-textarea,
      .el-select {
        width: 400px;

        :deep .el-input__inner,
        :deep .el-textarea__inner {
          background-color: #fff;
          border-color: #dcdcdc;
        }
      }

      .cover-uploader {
        :deep img {
          max-width: 228px;
          max-height: 320px;
        }

        :deep .el-upload {
          position: relative;
          overflow: hidden;
          cursor: pointer;
          border: 1px dashed #d9d9d9;
          border-radius: 6px;

          &:hover {
            border-color: #409eff;
          }
        }

        &-icon {
          display: flex;
          flex-direction: column;
          row-gap: 4px;
          align-items: center;
          justify-content: center;
          width: 228px;
          height: 320px;
          font-size: 12px;
          color: #8c939d;
          background-color: #eee;

          .el-icon-plus {
            font-size: 16px;
            font-weight: bold;
            color: #000;
          }
        }

        .avatar {
          display: block;
          width: 178px;
          height: 178px;
        }
      }

      .label-select {
        :deep .el-input__suffix {
          display: none;
        }
      }

      .tips {
        margin-top: -4px;
        font-size: 12px;
        color: #8c8c8c;
      }

      &-item {
        margin-bottom: 24px;
      }
    }
  }
}
</style>

<style lang="scss">
.el-select-dropdown.el-popper.is-multiple {
  display: none;

  .el-select-dropdown__empty {
    display: none;
  }
}
</style>
