<template>
  <div>
    <!--    编辑-->
    <xy-dialog :is-show.sync="isShow" title="图书编辑" type="form" :form="detail" :rules="rules" @submit="editor"
      ref="addActivity">

      <template v-slot:name>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>图书名称
          </div>
          <div class="xy-table-item-content">
            <el-input clearable placeholder="请填写图书名称" v-model="detail.name" style="width: 300px;" />
          </div>
        </div>
      </template>

      <template v-slot:isbn>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>ISBN
          </div>
          <div class="xy-table-item-content">
            <el-input clearable autofocus placeholder="请填写ISBN" @change="getBookInfo" ref="inputisbn"
              v-model="detail.isbn" style="width: 300px;">

              <el-button slot="append" icon="el-icon-search"></el-button>

            </el-input>
          </div>
        </div>
      </template>



      <template v-slot:type_id>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>图书类目
          </div>
          <div class="xy-table-item-content">
            <treeselect v-model="detail.type_id" :normalizer="normalizer" :multiple="false" clearable
              style="width: 300px;" :show-count="true" placeholder="选择图书类目" :options="typeOptions" />
          </div>
        </div>
      </template>


      <template v-slot:small_cover_id>
        <div class="xy-table-item">
          <div class="xy-table-item-label">封面
          </div>
          <div class="xy-table-item-content">

            <div v-if="detail.small_cover" style="position: relative;">
              <img :src="detail.small_cover" class="avatar" style="width:120px;height:120px">
              <Button shape="circle" icon="md-close" type="error" size="small" class="img__delete"
                @click="detail.small_cover = '',detail.small_cover=''"></Button>
            </div>
            <el-upload v-else accept="picture" :limit="1" class="avatar-uploader" list-type="picture-card"
              :action="action" :show-file-list="true" :on-error="uploadFail" :on-success="uploadSuccess"
              :before-upload="uploadBefore">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            尺寸要求：120*120
          </div>

        </div>
      </template>


      <template v-slot:big_cover_id>
        <div class="xy-table-item">
          <div class="xy-table-item-label">大封面
          </div>
          <div class="xy-table-item-content">

            <div v-if="detail.big_cover" style="position: relative;">
              <img :src="detail.big_cover" class="avatar" style="width:280px;height:280px">
              <Button shape="circle" icon="md-close" type="error" size="small" class="img__delete"
                @click="detail.big_cover = '',detail.big_cover_id=''"></Button>
            </div>
            <el-upload v-else accept="picture" :limit="1" class="avatar-uploader" list-type="picture-card"
              :action="action" :show-file-list="true" :on-error="uploadFailLogo" :on-success="uploadSuccessLogo"
              :before-upload="uploadBeforeLogo">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            尺寸要求：480*480
          </div>

        </div>
      </template>



      <template v-slot:bind_way>
        <div class="xy-table-item">
          <div class="xy-table-item-label">装帧方式
          </div>
          <div class="xy-table-item-content">
            <el-input clearable placeholder="请填写装帧方式" v-model="detail.bind_way" style="width: 150px;" />
          </div>
        </div>
      </template>


      <template v-slot:publish_date>
        <div class="xy-table-item">
          <div class="xy-table-item-label">出版日期
          </div>
          <div class="xy-table-item-content">
            <el-input clearable placeholder="请填写出版日期" v-model="detail.publish_date" style="width: 150px;" />
          </div>
        </div>
      </template>


      <template v-slot:author>
        <div class="xy-table-item">
          <div class="xy-table-item-label">图书作者
          </div>
          <div class="xy-table-item-content">
            <el-input clearable placeholder="请填写图书作者" v-model="detail.author" style="width: 150px;" />
          </div>
        </div>
      </template>

      <template v-slot:publish_house>
        <div class="xy-table-item">
          <div class="xy-table-item-label">出版社
          </div>
          <div class="xy-table-item-content">
            <el-input clearable placeholder="请填写出版社" v-model="detail.publish_house" style="width: 150px;" />
          </div>
        </div>
      </template>


      <template v-slot:font_total>
        <div class="xy-table-item">
          <div class="xy-table-item-label">图书页数
          </div>
          <div class="xy-table-item-content">
            <el-input clearable placeholder="请填写图书页数" v-model="detail.font_total" style="width: 150px;" />
          </div>
        </div>
      </template>



      <template v-slot:content>
        <div class="xy-table-item">
          <div class="xy-table-item-label">图书介绍
          </div>
          <div class="xy-table-item-content">
            <el-input clearable placeholder="请填写图书介绍" type="textarea" rows="4" v-model="detail.content"
              style="width: 300px;" />
          </div>
        </div>
      </template>

      <template v-slot:stockNum v-if="this.id==''">
        <div class="xy-table-item">
          <div class="xy-table-item-label">入库数量
          </div>
          <div class="xy-table-item-content">
            <el-input clearable placeholder="请填写入库数量" v-model="detail.stockNum" style="width: 150px;" />
          </div>
        </div>
      </template>

    </xy-dialog>

  </div>
</template>

<script>
  import {
    save,
    show,
    isbn,
    isbnCheck
  } from "@/api/bookStore/bookIndex";
  import {
    list as bookTypeIndex
  } from "@/api/bookStore/bookType";

  import {
    get_isbn
  } from "@/api/bookStore/interface";

  import {
    uploadFile,
    uploadFileByUrl
  } from "@/api/common";

  // import the component
  import Treeselect from '@riophae/vue-treeselect'
  // import the styles
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

  export default {
    // register the component
    components: {
      Treeselect
    },
    data() {

      return {
        typeOptions: [],
        isShow: false,
        id: "",
        type: "add",
        action: `${process.env.VUE_APP_BASE_API}/api/admin/upload-file`,
        detail: {
          id: "",
          isbn: "",
          name: "",
          sub_title: "",
          author: "",
          bind_way: "",
          type_id: "",
          publish_date: "",
          publish_house: "",
          font_total: "",
          content: "",
          small_cover_id: "",
          small_cover: "",
          big_cover: "",
          big_cover_id: "",
          stockNum: 1,
          details: [],
        },
        normalizer(node) {
          return {
            id: node.id,
            label: node.name,
            children: node.children,
          }
        },
        rules: {
          name: [{
            required: true,
            message: "项目名称必填"
          }],
          type_id: [{
            required: true,
            message: "请选择图书类目",
            trigger: 'change'
          }]
        }

      }
    },
    watch: {
      isShow(newVal) {
        if (newVal) {
          if (this.type === 'editor') {
            this.getDetail()
          }
        } else {
          this.id = ''
          this.type = ''
          this.$refs['addActivity'].reset();

          this.detail.id = "";
          this.detail.small_cover = "";
          this.detail.big_cover = "";
        }
        let that = this;
        this.$nextTick(function() {
          console.log(that.$refs.inputisbn)
          that.$refs.inputisbn.focus();
        })
      }
    },
    methods: {
      downloadByBlob(url, name, id) {
        uploadFileByUrl({
          url: url
        }).then(r => {
          let fileFormData = new FormData();
          fileFormData.append('file', r, "name.jpg"); //filename是键，file是值，就是要传的文件，test.zip是要传的文件名
          uploadFile(fileFormData).then(res => {
            console.log("res", res)
            this.detail[name] = res.url;
            this.detail[id] = res.id;
          })
        })

      },
      getBookInfo(e) {
        console.log(e);
        let that = this;
        if (e == "" || e.length < 10) {
          this.$Message.error("请正确输入ISBN");
          return false;
        }

        isbnCheck({
          isbn: e
        }).then(r => {

          console.log("r", r)
          this.getISBN(e);
        })
      },
      getISBN(isbnNo) {
        let that = this;
        isbn({
          isbn: isbnNo
        }).then(res => {
          console.log("res", res)

          console.log("res.msg", res.msg);
          var json = JSON.parse(res.msg);
          console.log("json", json);
          if (json.error_code != 0) {
            that.$Message.error("存在错误" + res.error_code);
          } else {
            let book = json.result.data;
            that.detail.name = book.title;
            that.detail.sub_title = book.subtitle;
            that.detail.author = book.author;
            that.detail.bind_way = book.paper;
            that.detail.publish_date = book.pubDate;
            that.detail.publish_house = book.publisher;
            that.detail.font_total = book.wordNum;
            that.detail.content = book.gist;

            if (book.smallImg && book.smallImg != '') {
              that.downloadByBlob(book.smallImg, "small_cover", "small_cover_id");

            }
            if (book.img && book.img != '') {
              that.downloadByBlob(book.img, "big_cover", "big_cover_id");
            }

          }
        })
      },
      loadbookTypeIndex() {
        bookTypeIndex({
          is_tree: 1
        }).then(res => {
          this.typeOptions = res;
        })
      },
      //上传
      uploadFailLogo(err) {
        console.log(err)
      },
      uploadSuccessLogo(response) {
        this.detail.big_cover = response.url
        this.detail.big_cover_id = response.id
      },
      uploadBeforeLogo(file) {
        if ((file.size / 1000) > 2024) {
          Message({
            type: 'warning',
            message: '上传图片大小超过2M！'
          })
          return false
        }
      },
      //上传
      uploadFail(err) {
        console.log(err)
      },
      uploadSuccess(response) {
        this.detail.small_cover = response.url
        this.detail.small_cover_id = response.id
      },
      uploadBefore(file) {
        if ((file.size / 1000) > 2024) {
          Message({
            type: 'warning',
            message: '上传图片大小超过2M！'
          })
          return false
        }
      },
      querySearch(queryString, cb) {
        listuser().then(response => {
          var data = response.data;
          for (var m of data) {
            m.value = m.name;
          }
          cb(data)
        }).catch(error => {
          //reject(error)
        })
      },
      handleSelectUser(item) {
        this.detail.admin_id = item.id;
        this.detail.admin_name = item.value;

      },
      async getDetail() {
        let res = await show({
          id: this.id
        })
        Object.assign(this.detail, res);
        this.detail.small_cover = res.small_cover.url;
        this.detail.big_cover = res.big_cover.url;
      },
      editor() {

        if (this.detail.id == "") {
          let _arr = [];
          console.log(this.detail.stockNum)
          for (var i = 0; i < this.detail.stockNum; i++) {
            _arr.push({
              enter_date: this.$moment().format("YYYY-MM-DD"),
              remark: "",
              status: 0,
            })
          }
          console.log(this.detail.id)
          this.detail.details = _arr;
        }

        save(this.detail).then(res => {
          this.isShow = false
          this.$Message.success("操作成功");
          this.$emit('refresh')
        })
      },

    },
    computed: {

    },
    created() {
      let that = this;
      that.loadbookTypeIndex();
      that.$nextTick(function() {
        console.log(that.$refs.inputisbn)
        that.$refs.inputisbn.focus();
      })
    },
    mounted() {
      let that = this;
      that.$nextTick(function() {
        console.log(that.$refs.inputisbn)
        that.$refs.inputisbn.focus();
      })
    }
  }
</script>

<style scoped lang="scss">
  .contract-add-plan {
    min-height: 30px;
    border: 1px solid #dcdee2;
    border-radius: 4px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    align-content: center;

    padding: 0 8px;

    &-no-plan {
      height: 30px;
      line-height: 30px;
      color: #CDD0D5;
    }
  }

  .xy-table-item-label {
    width: 140px;
  }

  .xy-table-item-price {
    position: relative;

    &::after {
      z-index: 1;
      position: absolute;
      right: 0;
      top: 0;
      content: '（元）'
    }

    ::v-deep .el-input__clear {
      position: relative;
      right: 30px;
      z-index: 2;
    }
  }

  .xy-table-item-price-wan {
    position: relative;

    &::after {
      position: absolute;
      right: 0;
      top: 0;
      content: '（万元）'
    }

    ::v-deep .el-input__clear {
      position: relative;
      right: 46px;
      z-index: 2;
    }
  }
</style>
