<template>
  <el-dialog
    :visible="visible"
    width="500px"
    title="申请上架（填写教材信息）"
    :close-on-click-modal="false"
    @close="dialogClose"
  >
    <el-form ref="form" label-width="200px" :model="book_info">
      <el-form-item label="名称">
        <el-input v-model="book_info.name" />
      </el-form-item>
      <el-form-item label="版本">
        <el-input v-model="book_info.version" />
      </el-form-item>
      <el-form-item label="英文名称">
        <el-input v-model="book_info.name_english" />
      </el-form-item>
      <el-form-item label="所属丛书">
        <el-input v-model="book_info.series_name" />
      </el-form-item>
      <el-form-item label="国际标准图书编号（ISBN）">
        <el-input v-model="book_info.isbn" />
      </el-form-item>
      <el-form-item label="作者">
        <el-input v-model="book_info.author" />
      </el-form-item>
      <el-form-item label="价格">
        <el-input v-model="book_info.price" type="number" step="0.01" @input="onPriceInput" />
      </el-form-item>
    </el-form>

    <div slot="footer">
      <el-button type="primary" @click="confirm">申请上架教材</el-button>
      <el-button @click="dialogClose">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { GetBookBaseInfo } from '@/api/book';

export default {
  name: 'RequestBook',
  props: {
    projectId: {
      type: String,
      required: true,
    },
    visible: {
      type: Boolean,
      required: true,
    },
  },
  data() {
    return {
      book_info: {
        name: '',
        version: '',
        name_english: '',
        series_name: '',
        isbn: '',
        author: '',
        price: '',
      },
    };
  },
  created() {
    this.getBookBaseInfo();
  },
  methods: {
    getBookBaseInfo() {
      GetBookBaseInfo({ id: this.projectId }).then(({ book_info }) => {
        this.book_info = book_info;
      });
    },
    onPriceInput(value) {
      const regex = /^\d+(\.\d{0,2})?$/;
      if (!regex.test(value)) {
        this.book_info.price = value.slice(0, -1);
      }
    },
    dialogClose() {
      this.$emit('update:visible', false);
    },
    confirm() {
      this.$emit('confirm', {
        project_id: this.projectId,
        book_info: {
          name: this.book_info.name,
          version: this.book_info.version,
          name_english: this.book_info.name_english,
          series_name: this.book_info.series_name,
          isbn: this.book_info.isbn,
          author: this.book_info.author,
          price: this.book_info.price,
        },
      });
    },
  },
};
</script>
