<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible"
    @close="handlereset">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-form-item label="书名" prop="name">
        <el-input v-model="dataForm.name" placeholder="书名"></el-input>
      </el-form-item>
      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="作者姓名" prop="authorId">
          <el-autocomplete
            class="inline-input"
            v-model="author"
            :fetch-suggestions="querySearch"
            placeholder="请输入作者姓名"
            @select="handleSelect"
          ></el-autocomplete>
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-row>
        <el-col :span="12">
          <!-- <el-form-item label="作者" prop="authorId">
        <el-select
          v-model="dataForm.authorId"
          multiple
          filterable
          allow-create
          size="small"
          default-first-option
          placeholder="请输入作者姓名">
          <el-option
            v-for="item in authorList"
            :key="item.value + ''"
            :label="item.value"
            :value="item.id + ''">
          </el-option>
        </el-select>
      </el-form-item> -->
          <el-form-item label="作者" prop="publisherName">
            <el-input v-model="dataForm.publisherName" placeholder="请输入作者"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出版社" prop="publisherId">
            <el-select v-model="dataForm.publisherId" multiple filterable allow-create default-first-option
              placeholder="请输入出版社名称">
              <el-option v-for="item in publisherList" :key="item.value + ''" :label="item.value" :value="item.id + ''">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>


      <!-- <el-input v-model="dataForm.authorId" placeholder="作者姓名" v-show="false"></el-input> -->

      <el-form-item label="序言" prop="title">
        <el-input v-model="dataForm.title" placeholder="序言" :rows="3" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="拆分类型" prop="splits">
        <el-radio-group v-model="dataForm.splits">
          <el-radio v-for="item in splitsTypeList" :key="item.dictType" :label="item.dictType"
            :value="item.dictType">{{item.dictValue}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="目录" prop="content">
        <el-input v-model="dataForm.content" placeholder="目录" :rows="5" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="简介" prop="description">
        <el-input v-model="dataForm.description" placeholder="简介" :rows="5" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="图书分类" prop="bookType">
       <el-radio-group v-model="dataForm.bookType">
         <el-radio :label="0">普通</el-radio>
         <el-radio :label="1">中医经典</el-radio>
         <el-radio :label="2">国学经典</el-radio>

       </el-radio-group>
      </el-form-item>
      <el-row>
        <!-- <el-col :span="12">
          <el-form-item label="原价" prop="price">
            <el-input v-model="dataForm.price" placeholder="价格"></el-input>
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="12">
          <el-form-item label="优惠价格" prop="salePrice">
            <el-input v-model="dataForm.salePrice" placeholder="优惠价格"></el-input>
          </el-form-item> -->
        <!-- </el-col>       -->
        <el-form-item label="图书类型" prop="medicaldesBookType">
          <el-checkbox-group v-model="dataForm.medicaldesBookType">
            <el-checkbox v-for="item in medicaldesBookTypeList" :key="item.dictType" :label="item.dictType"
              :value="item.dictType">{{item.dictValue}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-col :span="12">
          <el-form-item label="是否可听">
            <!-- <el-input v-model="dataForm.salePrice" placeholder="优惠价格"></el-input> -->
            <el-switch style="display: block" v-model="dataForm.canListen" active-color="#13ce66"
              inactive-color="#ff4949" active-text="可听" inactive-text="不可听">
            </el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="是否参与打卡" prop="clockIn" label-width="250">
        <el-radio-group v-model="dataForm.clockIn">
          <!-- <el-radio :label="3">听书</el-radio> -->
          <el-radio :label="1">参与打卡</el-radio>
          <el-radio :label="2">不参与打卡</el-radio>

        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否参与讲书" prop="teachIn" label-width="250">
        <el-radio-group v-model="dataForm.teachIn">
          <!-- <el-radio :label="3">听书</el-radio> -->
          <el-radio :label="1">参与</el-radio>
          <el-radio :label="0">不参与</el-radio>

        </el-radio-group>
      </el-form-item>
      <el-form-item label="付费类型" prop="isVip">
        <el-radio-group v-model="dataForm.isVip">
          <!-- <el-radio :label="3">听书</el-radio> -->
          <el-radio :label="2">付费</el-radio>
          <el-radio :label="1">会免</el-radio>
          <el-radio :label="0">免费</el-radio>

        </el-radio-group>
      </el-form-item>
      <el-form-item label="免费章节数" prop="freeChapterCount" label-width="250">
        <el-input-number v-model="dataForm.freeChapterCount" :min="0" :max="10" label="免费章节数"></el-input-number>
      </el-form-item>
      <!-- <el-form-item label="置顶" prop="istop">
        <el-radio-group v-model="dataForm.istop">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <!-- <el-form-item label="秒杀" prop="istop">
        <el-radio-group v-model="dataForm.isSale">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>       -->
      <!-- <el-form-item label="出版商名称" prop="publisherId">
        <el-input v-model="dataForm.publisherId" placeholder="出版商名称"></el-input>
      </el-form-item> -->
      <el-form-item label="文件上传" prop="novel">
        <el-upload class="upload-demo" :action="baseUrl + '/oss/fileoss'" :on-preview="handlePreview"
          :on-remove="handleRemoveNovel" :before-remove="beforeRemove" :on-success="handleNovelSuccess" multiple
          :limit="3" :on-exceed="handleExceed" :file-list="fileListNovel">
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="插图" prop="images">
        <el-upload :action="baseUrl + '/oss/fileoss'" list-type="picture-card" :on-preview="handlePictureCardPreview"
          :file-list="fileList" :on-success="handlePicSuccess" :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
          <img width="100%" :src="dataForm.images" alt="">
        </el-dialog>
      </el-form-item>
      <!-- <el-form-item label="创建日期" prop="createTime">
      <el-input v-model="dataForm.createTime" placeholder="创建日期"></el-input>
    </el-form-item>
    <el-form-item label="更新日期" prop="updateTime">
      <el-input v-model="dataForm.updateTime" placeholder="更新日期"></el-input>
    </el-form-item> -->
      <el-form-item label="排序" prop="sort">
        <el-input v-model="dataForm.sort" placeholder="排序"></el-input>
      </el-form-item>
      <!-- <el-form-item label="删除标记" prop="delFlag">
      <el-input v-model="dataForm.delFlag" placeholder="删除标记"></el-input>
    </el-form-item> -->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handlereset">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>



<script>
  import global from '../../common/common.vue' //引入共用组间
  export default {
    data() {
      return {
        baseUrl: global.baseUrl,
        visible: false,
        bookList: [{
            dictType: 0,
            dictValue: "普通"
          },
          {
            dictType: 1,
            dictValue: "中医经典"
          },
          {
            dictType: 2,
            dictValue: "国学经典"
          }
        ],
        medicaldesBookTypeList: [{
            dictType: 1,
            dictValue: "中医基础"
          },
          {
            dictType: 2,
            dictValue: "中医经典"
          },
          {
            dictType: 3,
            dictValue: "各家学说"
          },
          {
            dictType: 4,
            dictValue: "中医临床"
          },
          {
            dictType: 5,
            dictValue: "文学"
          },
          {
            dictType: 6,
            dictValue: "哲学"
          },
        ],
        props: {
          dictType: '',
          dictValue: ''
        },
        authorList: [],
        restaurants: [],
        author: '',
        publisherList: [],
        fileList: [],
        fileListNovel: [],
        dialogImageUrl: '',
        dialogVisible: false,
        dataForm: {
          id: 0,
          name: '',
          publisherName: '',
          splits: 0,
          authorId: [],
          description: '',
          title: '',
          bookType: 0,
          content: '',
          type: [],
          medicaldesBookType: [],
          // price: '',
          salePrice: '',
          // istop: '',
          isVip: 0,
          freeChapterCount: 0,
          // isSale: '',
          publisherId: [],
          images: '',
          pid: '',
          level: '',
          createTime: '',
          updateTime: '',
          sort: '',
          delFlag: '',
          novel: '',
          canListen: false,
          clockIn: 2,
          teachIn: 0,
        },
        splitsTypeList: [],
        dataRule: {

          // name: [
          //   { required: true, message: '书名不能为空', trigger: 'blur' }
          // ],
          // authorId: [
          //   { required: true, message: '作者id不能为空', trigger: 'blur' }
          // ],
          // description: [
          //   { required: true, message: '简介不能为空', trigger: 'blur' }
          // ],
          // title: [
          //   { required: true, message: '序言不能为空', trigger: 'blur' }
          // ],
          // content: [
          //   { required: true, message: '内容不能为空', trigger: 'blur' }
          // ],
          // type: [
          //   { required: true, message: '类型不能为空', trigger: 'blur' }
          // ],
          // price: [
          //   { required: true, message: '价格不能为空', trigger: 'blur' }
          // ],
          // istop: [
          //   { required: true, message: '置顶不能为空', trigger: 'blur' }
          // ],
          // publisherId: [
          //   { required: true, message: '出版商id不能为空', trigger: 'blur' }
          // ],
          // images: [
          //   { required: true, message: '插图不能为空', trigger: 'blur' }
          // ],
          // pid: [
          //   { required: true, message: '父id不能为空', trigger: 'blur' }
          // ],
          // level: [
          //   { required: true, message: '层级不能为空', trigger: 'blur' }
          // ],
          // createTime: [
          //   { required: true, message: '创建日期不能为空', trigger: 'blur' }
          // ],
          // updateTime: [
          //   { required: true, message: '更新日期不能为空', trigger: 'blur' }
          // ],
          // sort: [
          //   { required: true, message: '排序不能为空', trigger: 'blur' }
          // ],
          // splits: [
          //    { required: true, message: '拆分类类型不能为空', trigger: 'blur' }
          //  ]
        }
      }
    },
    created() {
      this.getBookList()
      this.loadAll()
    },
    mounted() {
      // this.restaurants = this.loadAll();
    },
    methods: {
      init(id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/book/book/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.dataForm.name = data.book.name
                this.dataForm.publisherName = data.book.dataForm
                // this.dataForm.authorId = data.book.authorId
                this.dataForm.description = data.book.description
                this.dataForm.title = data.book.title
                this.dataForm.bookType = data.book.bookType
                this.dataForm.content = data.book.content
                // this.dataForm.type = data.book.type
                // this.dataForm.price = data.book.price
                // this.dataForm.salePrice = data.book.salePrice
                // this.dataForm.istop = data.book.istop
                this.dataForm.isVip = data.book.isVip
                // this.dataForm.isSale = data.book.isSale
                this.dataForm.freeChapterCount = data.book.freeChapterCount
                this.dataForm.splits = data.book.splits
                // this.dataForm.publisherId = data.book.publisherId
                this.dataForm.images = data.book.images
                this.dataForm.pid = data.book.pid
                this.dataForm.level = data.book.level
                this.dataForm.createTime = data.book.createTime
                this.dataForm.updateTime = data.book.updateTime
                this.dataForm.sort = data.book.sort
                this.dataForm.delFlag = data.book.delFlag
                this.dataForm.novel = data.book.novel
                this.dataForm.clockIn = data.book.clockIn
                this.dataForm.teachIn = data.book.teachIn
                var checklist = data.book.type
                var medicaldeschecklist = data.book.medicaldesBookType
                var authorList = data.book.authorId
                var publisherlish = data.book.publisherId
                if (data.book.authorId != "") {
                  this.dataForm.authorId = authorList.split(',')
                }
                if (data.book.publisherId != "") {
                  this.dataForm.publisherId = publisherlish.split(',')
                }

                this.dataForm.type = checklist.split(',')
                this.dataForm.medicaldesBookType = medicaldeschecklist.split(',')
                for (let i = 0; i < this.dataForm.medicaldesBookType.length; i++) {
                  this.dataForm.medicaldesBookType[i] = parseInt(this.dataForm.medicaldesBookType[i]);
                }
                console.log(this.dataForm.type)
                console.log('2222222222', this.dataForm.medicaldesBookType)
                if (data.book.images != "") {
                  var img = {
                    name: '',
                    url: data.book.images
                  }
                  var attr = []
                  attr.push(img)
                  this.fileList = attr
                }
                if (data.book.novel != "" && data.book.novel != null && data.book.novel != 'undefined') {
                  var novel = {
                    name: '电子书文件',
                    url: data.book.novel
                  }
                  var attr = []
                  attr.push(novel)
                  this.fileListNovel = attr
                }
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit() {
        console.log('11111', this.dataForm.medicaldesBookType)
        // if (this.dataForm.medicaldesBookType.length == 0) {
        //   this.$message.error("请选择图书类型");
        //   return
        // }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/book/book/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'name': this.dataForm.name,
                'authorId': this.dataForm.authorId.join(','),
                'description': this.dataForm.description,
                'title': this.dataForm.title,
                'bookType': this.dataForm.bookType,
                'publisherName': this.dataForm.publisherName,
                'content': this.dataForm.content,
                'type': this.dataForm.type.join(','),
                "medicaldesBookType": this.dataForm.medicaldesBookType.join(','),
                // 'price': this.dataForm.price,
                // 'salePrice': this.dataForm.salePrice,
                // 'istop': this.dataForm.istop,
                'isVip': this.dataForm.isVip,
                // 'isSale': this.dataForm.isSale,
                'freeChapterCount': this.dataForm.freeChapterCount,
                'publisherId': this.dataForm.publisherId.join(','),
                'images': this.dataForm.images,
                'pid': this.dataForm.pid,
                'level': this.dataForm.level,
                'createTime': this.dataForm.createTime,
                'updateTime': this.dataForm.updateTime,
                'sort': this.dataForm.sort,
                'delFlag': this.dataForm.delFlag,
                'novel': this.dataForm.novel,
                'splits': this.dataForm.splits,
                'canListen': this.dataForm.canListen,
                'clockIn': this.dataForm.clockIn,
                'teachIn': this.dataForm.teachIn
              })
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      handlePicSuccess(res, file) {
        if (res.msg == "success") {
          this.dataForm.images = res.url;
          this.$message.success("上传成功");
        } else {
          this.$message.error("上传失败");
        }
      },
      //图书分类
      getBookList() {
        this.$http({
          url: this.$http.adornUrl('/book/sysdictdata/selectByType/book_type'),
          method: 'get',
          // params: this.$http.adornParams({
          //   'type': 'book_type',
          // })
        }).then(({
          data
        }) => {
          console.log(data)
          // this.bookList = data.dataList
        })

        // 获取图书拆分类型
        this.$http({
          url: this.$http.adornUrl('/book/sysdictdata/selectByType/splitsType'),
          method: 'get',
        }).then(({
          data
        }) => {
          this.splitsTypeList = data.dataList
        })
      },
      handleRemove(file) {
        this.dataForm.images = '';
      },
      handlePictureCardPreview(file) {
        this.dataForm.images = file.url;
        this.dialogVisible = true;
      },
      handleDownload(file) {
        console.log(file)
      },
      handlereset() {
        this.fileList = [],
          this.fileListNovel = [],
          this.visible = false
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handleRemoveNovel(file) {
        this.dataForm.novel = '';
      },
      handleNovelSuccess(file) {
        this.dataForm.novel = file.url
      },
      // querySearch(queryString, cb) {
      //     var restaurants = this.restaurants;
      //     var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      //     // 调用 callback 返回建议列表的数据
      //     console.log(results)
      //     cb(results);
      // },
      // createFilter(queryString) {
      //     return (restaurant) => {
      //       return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      //     };
      // },
      loadAll() {
        this.$http({
          url: this.$http.adornUrl('/book/author/bookAuthorList'),
          method: 'get',
        }).then(({
          data
        }) => {
          this.authorList = data.list
        })
        this.$http({
          url: this.$http.adornUrl('/book/publisher/publisherList'),
          method: 'get',
        }).then(({
          data
        }) => {
          this.publisherList = data.list
        })

      },
      // handleSelect(item) {
      //   this.dataForm.authorId = item.id
      //     console.log(item);
      //   }
    }

  }
</script>
