<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item label="内容归类">
        <el-select v-model="dataForm.dictType" placeholder="请选择内容归类" clearable>
          <el-option v-for="(item,index) in typeList" :key="index" :label="item.dictValue" :value="item.dictType">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="标题">
        <el-input v-model="dataForm.title" placeholder="请输入标题"></el-input>
      </el-form-item> -->
      <el-form-item>
        <el-button @click="pageIndex = 1;getDataList()">查询</el-button>
        <el-button v-if="isAuth('book:shopproduct:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="dataList" border v-loading="dataListLoading" style="width: 100%;">
      <el-table-column prop="title" header-align="center" align="center" label="标题">
      </el-table-column>
      <el-table-column label="内容归类" align="center" prop="type">
        <template slot-scope="scope">
          {{ filterAA(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column label="内容形式" align="center" prop="contentType">
        <template slot-scope="scope">
          {{ filterBB(scope.row.contentType) }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="url" align="center">
        <template slot-scope="scope">
          <a :href="'http://' + scope.row.url" target="_blank">{{ scope.row.url }}</a>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="内容" align="center"  prop="content">
        </el-table-column> -->
      <el-table-column label="排序" align="center" prop="sort" width="50">
        <template slot-scope="scope">
          {{ scope.row.sort }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="100" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="editOrUpdateHandle(scope.row)">修改</el-button>
          <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <el-dialog :visible.sync="addOrUpdateVisible" :close-on-click-modal="false" :append-to-body="true" :title="titlesub"
      width="50%" @close="cancleClose">
      <el-form :inline="true" :model="addForm" ref="addFormRef" :rules="addFormRule">
        <el-row type="flex" justify="center">
          <el-form-item label="标题" prop="title">
            <el-input style="width:500px" v-model="addForm.title"></el-input>
          </el-form-item>
        </el-row>
        <el-row type="flex" justify="center">
          <el-form-item label="内容归类" prop="type">
            <el-select v-model="addForm.type" placeholder="请选择内容归类" style="width: 500px;">
              <el-option v-for="(item,index) in typeList" :key="index" :label="item.dictValue" :value="item.dictType">
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row type="flex" justify="center">
          <el-form-item label="内容形式" prop="contentType">
            <el-select v-model="addForm.contentType" placeholder="请选择形式" style="width: 500px;">
              <el-option v-for="(item,index) in contentTypeList" :key="index" :label="item.dictValue" :value="item.dictType">
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row type="flex" justify="center" v-if="addForm.contentType == 2">
          <el-form-item label="url" prop="url" label-width="48px">
            <el-input style="width:500px" v-model="addForm.url"></el-input>
          </el-form-item>
        </el-row>
        <el-row type="flex" justify="center" v-if="addForm.contentType == 1">
          <el-form-item label="内容" prop="content" label-width="48px">
            <!-- <el-input style="width:500px" v-model="addForm.content" :rows="5" type="textarea"></el-input> -->
            <el-upload class="avatar-uploader" :action="baseUrl + '/oss/fileoss'" accept=".jpeg,.jpg,.gif,.png" :show-file-list="false" :on-success="contentUploadSuccess" >
            </el-upload>
            <quill-editor v-model="addForm.content" ref="myQuillEditor" :options="editorOption"
              @blur="onEditorBlur($event)" @focus="onEditorFocus($event)" 
              @ready="onEditorReady($event)" class="shangpin_editor">
            </quill-editor>
          </el-form-item>
        </el-row>
        <el-row type="flex" justify="center">
          <el-form-item label="排序" label-width="48px">
            <el-input style="width:500px" v-model="addForm.sort"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancleClose">取 消</el-button>
        <el-button type="primary" @click="addOreEditCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList" @showchooseBookf = "showchooseBookf"></add-or-update>
        <choose-book v-if="chooseBookVisible" :bookIds = bookIds ref="chooseBook" :chooseBookVisible = chooseBookVisible @closeBookf = "closeBookf"></choose-book>   -->
  </div>
</template>
<script>
  import {
      quillEditor
    } from 'vue-quill-editor'
  import global from '../../common/common.vue' //引入共用组间

  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'],        // 加粗，斜体，下划线，删除线
    ['blockquote', 'code-block'],                      //引用，代码块
    [{ 'header': 1 }, { 'header': 2 }],               // 几级标题
    [{ 'list': 'ordered' }, { 'list': 'bullet' }],     // 有序列表，无序列表
    [{ 'script': 'sub' }, { 'script': 'super' }],      // 下角标，上角标
    [{ 'indent': '-1' }, { 'indent': '+1' }],          // 缩进
    [{ 'direction': 'rtl' }],                         // 文字输入方向
    [{ 'size': ['small', false, 'large', 'huge'] }],  // 字体大小
    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],// 标题
    [{ 'color': [] }, { 'background': [] }],          // 颜色选择
    [{ 'font': ['SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong', 'Arial'] }],// 字体
    [{ 'align': [] }], // 居中
    ['clean'],                                       // 清除样式,
    ['link', 'image'],  // 上传图片、上传视频
  ]
  // import global from '../../common/common.vue' //引入共用组间
  export default {
    data() {
      return {
        baseUrl: global.baseUrl,
        // cityEntity: [],
        // provinceEntity: [], //省地址
        typeList: [{
          dictType: '1',
          dictValue: '学术思想'
        },{
          dictType: '2',
          dictValue: '学术平台'
        }],
        contentTypeList: [{
          dictType: '1',
          dictValue: '文章'
        },{
          dictType: '2',
          dictValue: '外链'
        }],
        // booknameList: [],
        dataForm: {
          dictType: '', //分类
          // bookName: '', //书名
        },
        // fileList: [],
        addForm: {
          id: '', //新增不传
          title: '', //姓名
          type: '', //分类
          contentType: '', //分类
          url: '',
          content: '',
          sort: 0
        },
        editId: '',
        addFormRule: {
          type: [{
            required: true,
            message: "请选择内容归类"
          }],
          contentType: [{
            required: true,
            message: "请选择内容形式"
          }],
          title: [{
            required: true,
            message: "请输入标题"
          }]
        },
        dataList: [],
        // publishStatus: false,
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        // bookIds: [],
        titlesub: '新增',
        // dialogVisible: false
        // 富文本编辑器配置
        editorOption: {
          modules: {
            history: {
              delay: 1000,
              maxStack: 50,
              userOnly: false
            },
            toolbar: {
              container: toolbarOptions,
              handlers: {
                image: function (value) {
                  if (value) {
                    // 调用element的图片上传组件
                    document.querySelector('.avatar-uploader input').click()
                  } else {
                    this.quill.format('image', false)
                  }
                }
              }
            },
          },
          placeholder: '请输入正文',
          
        },
      }
    },
    components: {
      quillEditor
      // AddOrUpdate,
      // chooseBook
    },
    created() {
      // this.gettypeList()
      // this.getprovinceEntity()
    },
    activated() {
      this.getDataList()
      // this.gettypeList()
      // this.getprovinceEntity()
    },
    methods: {
      // gettypeList() {
      //   this.$http({
      //     url: this.$http.adornUrl('/book/medicaldes/typeList?label=inheritType'),
      //     method: 'post',
      //   }).then(({
      //     data
      //   }) => {
      //     if (data && data.code === 0) {
      //       this.typeList = data.result

      //     } else {
      //       this.typeList = []
      //     }
      //   })
      // },
      contentUploadSuccess(res, file) { 
        // console.log(res)
        let quill = this.$refs.myQuillEditor.quill
        // 如果上传成功
        if (res) {
          // 获取光标所在位置
          let length = quill.getSelection().index;
          // 插入图片，res为服务器返回的图片链接地址
          quill.insertEmbed(length, 'image', res.url)
          // 调整光标到最后
          quill.setSelection(length + 1)
        } else {
          // 提示信息，需引入Message
          this.$message.error('图片插入失败！')
        }

      },
      // 失去焦点事件
      onEditorBlur(quill) {
      //  console.log('editor blur!', quill)       
      },
      // 获得焦点事件
      onEditorFocus(quill) {
        //console.log('editor focus!', quill)
      },
      // 准备富文本编辑器
      onEditorReady(quill) {
       // console.log('editor ready!', quill)
      },
      // 获取数据列表
      getDataList() {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/book/generalArticle/articleByPage'),
          method: 'post',
          data: this.$http.adornData({
            "type": this.dataForm.dictType||'',
            // "name": this.dataForm.bookName,
            "current": this.pageIndex,
            "limit": this.pageSize
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.dataList = data.result.records
            // for (let i = 0; i < this.dataList.length; i++) {
            //   let imgList = []
            //   if (this.dataList[i].img != '') {
            //     let arr = this.dataList[i].img.split(';');
            //     arr.forEach((item, index) => {
            //       imgList.push({
            //         name: index,
            //         url: item
            //       })
            //     })
            //   }
            //   this.dataList[i].imgList = imgList
            // }

            this.totalPage = data.result.total
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // provinceChange() {
      //   this.addForm.cityId = ''
      //   this.cityEntity = []
      //   console.log('addForm.provinceCode', this.addForm.provId);
      //   this.$http({
      //     url: this.$http.adornUrl(`/book/medicaldes/getCityByPro?provId=${this.addForm.provId}`),
      //     method: 'post',
      //   }).then(({
      //     data
      //   }) => {
      //     if (data && data.code === 0) {
      //       this.cityEntity = data.prov
      //       console.log('data67y8ui9', data);
      //     } else {}
      //   })

      // },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      // selectionChangeHandle(val) {
      //   this.dataListSelections = val
      // },
      // 新增 / 修改
      editOrUpdateHandle(row) {
        console.log('rowzz', row.img);
        this.titlesub = '修改'
        this.editId = row.id
        this.addForm.title = row.title
        this.addForm.url = row.url
        this.addForm.content = row.content
        this.addForm.contentType = row.contentType+''
        this.addForm.type = row.type.toString()
        this.addForm.sort = row.sort
        // this.fileList = row.imgList
        // for (var i = 0; i < this.provinceEntity.length; i++) {
        //   for (var j = 0; j < this.provinceEntity[i].cityList.length; j++) {
        //     if (this.provinceEntity[i].cityList[j].cityId == row.cityId) {
        //       this.addForm.provId = this.provinceEntity[i].cityList[j].provId
        //     }
        //   }
        // }
        // this.provinceChange()
        // console.log('this.addForm.provId', this.addForm.provId);

        // this.addForm.cityId = row.cityId
        this.addOrUpdateVisible = true
      },
      addOrUpdateHandle() {
        this.editId = ''
        this.titlesub = '新增'
        this.addOrUpdateVisible = true
      },
      cancleClose() {
        this.addOrUpdateVisible = false
        this.$refs["addFormRef"].resetFields();
        this.addForm = {
          id: '', //新增不传
          title: '', //姓名
          url: '', //分类
          content: '',
          contentType: '',
          type: '',
          sort: 0
        }
        // this.fileList = []
      },
      // getprovinceEntity() {
      //   this.$http({
      //     url: this.$http.adornUrl('/book/medicaldes/getMedicaldesProList'),
      //     method: 'post',
      //   }).then(({
      //     data
      //   }) => {
      //     if (data && data.code === 0) {
      //       this.provinceEntity = data.provinceEntity
      //       console.log('this.provinceEntit', this.provinceEntity);
      //     } else {
      //       this.provinceEntity = []
      //     }
      //   })

      // },
      // 删除
      deleteHandle(id) {
        this.$confirm('请确认是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl(`/book/generalArticle/delArticle?id=${id}`),
            method: 'post',
          }).then(({
            data
          }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1000,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      addOreEditCate() {
        this.$refs["addFormRef"].validate(valid => {
          if (valid) {
            // var imageslist = []
            // var arr = []
            // if (this.fileList.length > 0) {
            //   arr = this.fileList.map(item => {
            //     return item.url
            //   })
            // }
            // imageslist = arr.join(";");

            this.$http({
              url: this.$http.adornUrl('/book/generalArticle/saveOrUpdateArticle'),
              method: 'post',
              data: this.$http.adornData({
                "id": this.editId, //新增不传
                "title": this.addForm.title,
                "url": this.addForm.url,
                // "img": imageslist,
                "content": this.addForm.content,
                "contentType": this.addForm.contentType,
                "type": this.addForm.type,
                // "cityId": this.addForm.cityId,
                "sort": this.addForm.sort
              })
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.$message.success("成功");
                this.addOrUpdateVisible = false
                this.getDataList()
              } else {
                this.$message.error("失败");
              }
            })
            
          }
        })
      },

      // handlePicSuccess(res, file) {
      //   // console.log(res,'res')
      //   if (res.msg == "success") {
      //     this.fileList.push({
      //       name: file.name,
      //       url: res.url
      //     })

      //     this.$message.success("上传成功");
      //   } else {
      //     this.$message.error("上传失败");
      //   }
      // },
      // handleRemove(file, fileList) {

      //   this.fileList = fileList
      //   // this.addForm.noneBtnImg = fileList.length >= this.addForm.limitCountImg;
      // },
      filterAA(val) {
        var aa = this.typeList.filter(obj => obj.dictType == val)
        return aa[0].dictValue
        // return aa
      },
      filterBB(val) {
        var aa = this.contentTypeList.filter(obj => obj.dictType == val)
        return aa[0].dictValue
        // return aa
      },
      // translateaddr(code) {
      //   for (var i = 0; i < this.provinceEntity.length; i++) {
      //     for (var j = 0; j < this.provinceEntity[i].cityList.length; j++) {
      //       if (this.provinceEntity[i].cityList[j].cityId == code) {
      //         return this.provinceEntity[i].provName + ' - ' + this.provinceEntity[i].cityList[j].cityName
      //       }
      //     }
      //   }
      // }
    }
  }
</script>
