<template>
  <div>
    <!--编辑block标签弹窗  -->
    <el-dialog title="编辑标签<cms:block>" class="dialog block-dialog" :visible="isShowModal" @update:visible="closeHandler">
      <!--工具栏  -->
      <el-toolbar>
        <el-button @click="saveClickHandler">
          <i class="fa fa-floppy-o" aria-hidden="true"></i>保存
        </el-button>
        <el-button @click="publishClickHandler">
          <i class="fa fa-file-text-o" aria-hidden="true"></i>发布
        </el-button>
        <el-button>
          <i class="fa fa-search" aria-hidden="true"></i>预览
        </el-button>
        <el-button @click="versionVisble = true">
          <i class="fa fa-book" aria-hidden="true"></i>版本
        </el-button>
      </el-toolbar>

      <div class="dialog-con">
        <!-- 基本信息 -->
        <div class="base-info-box">
          <div class="base-info">基本信息
            <span style="float: right" @click="toggleInfo()">
              <i v-if="toggleShow" class="fa fa-chevron-circle-up" aria-hidden="true"></i>
              <i v-show="upDown" class="fa fa-chevron-circle-down" aria-hidden="true"></i>
            </span>
          </div>
          <el-form v-show="toggleShow" :model="form" :rules="rules" ref="form" :label-position="labelPosition" label-width="120px">
            <el-form-item label="类型：">
              <el-radio-group v-model="form.blockType">
                <el-radio label="自动列表" disabled></el-radio>
                <el-radio label="HTML代码" disabled></el-radio>
                <el-radio label="手工选择" disabled></el-radio>
                <el-radio label="模板生成" disabled></el-radio>
                <el-radio label="页面部件" disabled></el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="名称：" class="block-input" prop="name">
              <el-input v-model="form.blockTagName"></el-input>
            </el-form-item>

            <el-form-item label="代码：" class="block-input" prop="code">
              <el-input v-model="form.blockTagCode"></el-input>
            </el-form-item>

            <el-form-item label="宽度：" class="block-width">
              <el-input v-model="form.blockWidth"></el-input>px
            </el-form-item>

            <el-form-item label="路径：" class="block-input" prop="path">
              <el-input v-model="form.blockTagPath"></el-input>
              <el-button class="select-document" @click="blockSelectVisible = true">浏览..</el-button>
              <el-tooltip effect="dark" content="可直接编辑自定义区块文件名字" placement="right" style="cursor: help">
                <i class="fa fa-info-circle" aria-hidden="true"></i>
              </el-tooltip>
            </el-form-item>

            <el-form-item label="权重范围：">
              <el-input-number v-model="form.minWeightRange" :min="0"></el-input-number>&nbsp;~
              <el-input-number v-model="form.maxWeightRange" :min="0"></el-input-number>
            </el-form-item>

            <el-form-item label="接受推荐：">
              <el-select v-model="form.recommend">
                <el-option label="作为待选稿" value="draft"></el-option>
                <el-option label="作为列表项" value="listItems"></el-option>
              </el-select>
            </el-form-item>

          </el-form>
        </div>

        <el-tabs type="border-card" class="con-table-box">
          <!-- 内容 -->
          <el-tab-pane label="内容">
            <el-button icon="edit" @click="recordClickHandler">选择内容记录</el-button>
            <el-button icon="delete2" @click="clearClickHandler">清空</el-button>
            <el-button icon="plus" @click="addRow($index, blockTagData)">添加</el-button>

            <el-table v-loading="dataLoading" :data="blockTagData" class="table-con">
              <el-table-column prop="title" label="标题" class="title-box">
                <template slot-scope="props">
                  <div class="row-item" draggable="true" @dragstart="dragStart($event, props.$index)" @dragover="allowDrop" @drop="drop($event, props.$index)">
                    <el-form label-position="left" inline class="con-form">
                      <el-form-item>
                        <span class="circle">
                          <i class="fa fa-plus icon-plus" aria-hidden="true" @click="addDocument()"></i>
                        </span>
                        <span class="con-box" v-for="con in props.row.content" :key="con.title">
                          <span class="con con-item" @click.native.prevent="deleteRow(scope.$index, blockTagData)">
                            {{ con.title }}
                            <span class="icon-box">
                              <i class="fa fa-plus-square-o icon icon-add" aria-hidden="true"></i>
                              <i class="fa fa-pencil icon icon-edit" aria-hidden="true" @click="handleEdit(scope.$index, scope.row)"></i>
                              <i class="fa fa-remove icon icon-remove" aria-hidden="true" @click.native.prevent="deleteRow(scope.$index, blockTagData)"></i>
                            </span>
                          </span>
                        </span>
                      </el-form-item>
                    </el-form>
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="操作" fixed="right" width="80">
                <template slot-scope="scope">
                  <el-button @click.native.prevent="addRow(scope.$index, blockTagData)" type="text">
                    <i class="fa fa-plus icon-plus" aria-hidden="true"></i>
                  </el-button>
                  <el-button @click.native.prevent="deleteRow(scope.$index, blockTagData)" type="text">
                    <i class="fa fa-minus icon-minus" aria-hidden="true"></i>
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!-- 内置模板 -->
          <el-tab-pane label="内置模板">
            <div>
              <prev>

                &lt;cms:blockrow&gt; &lt;z:list&gt; &lt;li&gt; &lt;a&gt;[最新]&lt;/a&gt; &lt;cms:blockitem&gt; &lt;z:list&gt; &lt;a title="${blockitem.title}" target="_blank" href="${blockitem.URL}" style="${blockitem.titleStyle}"&gt;${blockitem.title}&lt;/a&gt; &lt;z:if condition="${i&gt;total}"&gt; &lt;/z:if&gt; &lt;/z:list&gt; &lt;/cms:blockitem&gt; &lt;/li&gt; &lt;/z:list&gt; &lt;/cms:blockrow&gt;

              </prev>
            </div>
          </el-tab-pane>
        </el-tabs>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="confirmClickHandler">确 定</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 选择区块生成路径弹窗 -->
    <blockDoc-dialog :isShowModal="blockSelectVisible" @close=" val => blockSelectVisible = val"></blockDoc-dialog>

    <!--添加文档弹窗  -->
    <el-dialog title="添加文档" class="dialog add-doc-dialog" :visible.sync="blockAddDocVisible">
      <el-form :model="form" :label-position="labelPosition" label-width="120px">
        <el-form-item label="标题：">
          <el-input v-model="form.docTitle" style="width: 60%"></el-input>
          <el-color-picker v-model="titleColor" v-on:change="headleChangeColor"></el-color-picker>
          <el-button type="primary" @click="docSelect">选择文档</el-button>
        </el-form-item>
        <el-form-item label="地址：">
          <el-input v-model="form.docAddress"></el-input>
        </el-form-item>
        <el-form-item label="摘要：">
          <el-input type="textarea" v-model="form.docAbstract"></el-input>
        </el-form-item>

        <el-form-item label="图片：">
          <i class="fa fa-picture-o fa-5x icon-img" aria-hidden="true" @click="uploadImg"></i>
          <span classs="operate">
            <i class="fa fa-pencil icon icon-edit" aria-hidden="true"></i>
            <i class="fa fa-remove icon icon-remove" aria-hidden="true"></i>
            <i class="fa fa-crop icon icon-crop" aria-hidden="true"></i>
          </span>
        </el-form-item>

        <el-form-item label="日期：">
          <el-col :span="11">
            <el-date-picker type="date" placeholder="选择日期" :picker-options="pickerOptions" v-model="docDate" style="width: 100%;"></el-date-picker>
          </el-col>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmClickHandler">确 定</el-button>
      </div>
    </el-dialog>

    <!--上传图片弹窗  -->
    <el-dialog title="上传图片" class="dialog add-doc-dialog" :visible.sync="blockUploadImgVisible">
      <el-form :model="form" :label-position="labelPosition" label-width="120px">

        <el-form-item label="图片：">
            <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="docImageUrl" :src="docImageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmClickHandler">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import BlockDocDialog from './BlockDocDialog.vue'

export default {
  components: {
    'blockDoc-dialog': BlockDocDialog
  },
  data() {
    return {
      dataLoading: true, // 数据加载
      labelPosition: 'right', // 表单标签右对齐

      // <cms:block>
      form: {
        blockType: '手工选择', // 类型
        blockTagName: '首页区块', // 名称
        blockTagCode: 'index_top', // 代码
        blockWidth: 400, // 宽度
        blockTagPath: 'include/', // 路径
        minWeightRange: 0, // 最小权重
        maxWeightRange: 100, // 最大权重
        recommend: 'draft' // 接受推荐
      },
      editBlockTagVisble: false, // 编辑block标签弹窗
      versionVisble: false, // 版本弹窗
      toggleShow: true, // 基本信息显示
      upDown: false, // 基本信息隐藏
      blockTagData: [], // block标签内容数据
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        code: [{ required: true, message: '代码不能为空', trigger: 'blur' }],
        path: [{ required: true, message: '生成文件不能为空', trigger: 'blur' }]
      },
      searchForm: {
        name: '', // 搜索名字
        URL: '' // 文件路径
      },

      // 选择内容记录
      recordVisible: true, // 选择内容记录
      recordContentData: [], // 数据列表
      allMenuTreeData: this.menuTreeData,
      defaultProps: { children: 'children', label: 'name' }, // 左边栏目打开项

      // 选择区块生成路径
      blockSelectVisible: false, // 区块生成路径弹窗
      blockUrlData: [], // 选择区块生成路径数据
      selectedRows: [], // 已选择项数组
      docUrl: '', // 区块生成路径文件名路径
      currentPath: ['/'], // 当前文件路径

      // 重命名
      renameVisible: false, // 重命名弹窗
      lastCatalog: '', // 上级目录
      catalogName: '', // 目录名
      disabled: 1, // 重命名禁用上级目录

      // 新建目录
      addVisible: false, // 新建目录弹窗
      newCatalogName: '', // 新建目录名称
      newBlockUrlData: {}, // 新建目录数据

      // 添加文档
      blockAddDocVisible: false, // 添加文档弹窗
      docTitle: '内容', // 添加文档标题
      docAddress: '', // 添加文档地址
      docAbstract: '', // 添加文档摘要
      docDate: '', // 添加文档日期
      docImageUrl: '', // 添加文件图片
      titleColor: '#333', // 颜色选择器
      blockUploadImgVisible: false, // 上传图片弹窗
      // 日期快捷键
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      }
    }
  },
  methods: {
    // 清空
    clearClickHandler() {
      this.blockTagData = ''
    },
    // 选择内容记录
    recordClickHandler() {
      this.recordVisible = true
    },
    // 左边栏目添加icon
    renderContent(createElement, { node, data, store }) {
      return createElement('span', [
        createElement('i', { attrs: { class: 'fa fa-folder-open-o', style: 'font-size: 14px;' } }),
        createElement('span', {}, node.label)
      ])
    },

    // 生成路径确定按钮
    tempClickHandler(val) {
      this.form.blockTagPath = this.currentPath.concat(this.docUrl)
      this.blockSelectVisible = false // 隐藏选择区块生成路径弹窗
    },
    // 重命名
    async renameClickHandler() {
      try {
        await this.$confirm('重命名可能会影响到网站页面显示, 确定要重命名吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      this.renameVisible = true
      this.lastCatalog = this.currentPath
      this.catalogName = this.docUrl
    },

    // 双击进入子目录
    docUrlClickHandler(row, event) {
      this.currentPath.push(row.name)
      this.blockPathTableData()
    },

    // 跳转至指定路径
    returnClickHandler(index) {
      this.currentPath = this.currentPath.slice(0, index + 1)
      this.blockPathTableData()
    },

    // 返回上级目录
    returnLastCatalog() {
      if (this.currentPath !== '/') {
        this.currentPath.pop()
        this.blockPathTableData()
      }
    },

    // 刷新
    refreshClickHandler() {
      this.blockPathTableData()
    },

    // 新建目录
    addCatalog(index, rows) {
      this.addVisible = true
      this.lastCatalog = this.currentPath
    },

    // 新建目录确定按钮
    async addDialogHandler(index, rows) {
      this.addVisible = false
      // console.log(rows);
      // rows.push({});
      this.blockUrlData.unshift(this.newBlockUrlData)
      this.newBlockUrlData = {
        name: this.$refs.input.value,
        size: '',
        type: '目录',
        lastmodifytime: new Date('2016-08-13 13:25:50').getTime()
      }

      let res = await axios.put(`/ui/blockUrl`).catch(e => console.log(e))
      return res.data
    },

    inputVal(val) {
      this.$emit()
    },

    // 搜索
    searchTagClickHandler() {
      this.blockPathTableData()
    },

    // 生成路径选中文件
    handleSelectionChange(val) {
      this.selectedRows = val

      let size = val.length
      if (size === 1) {
        this.docUrl = val[0].name
      }
      if (size > 1) {
        this.$refs.multipleTable.clearSelection()
        this.$refs.multipleTable.toggleRowSelection(val[size - 1])
        this.docUrl = val[size - 1].name
      }
    },

    // 拖拽表格
    // 取消默认行为
    allowDrop(e) {
      e.preventDefault()
    },
    // 开始拖动
    dragStart(e, index) {
      let tar = e.target
      e.dataTransfer.setData('Text', index)
      // console.log(index)
      if (tar.tagName.toLowerCase() === 'tr') {
        // console.log('drag start')
        // console.log('drag Index: ' + index)
      }
    },
    // 放置
    drop(e, index) {
      this.allowDrop(e)
      // console.log('drop index: ' + index);
      // 使用一个新数组重新排序后赋给原变量
      let arr = this.blockTagData.concat([])

      let dragIndex = e.dataTransfer.getData('Text')

      let temp = arr.splice(dragIndex, 1)
      arr.splice(index, 0, temp[0])
      // console.log('sort');
      this.blockTagData = arr
    },

    // 基本信息显示
    toggleInfo() {
      this.toggleShow = !this.toggleShow
      this.upDown = !this.upDown
    },
    handleEdit(index, rows) {
      alert('Qwe')
    },
    // 选择文档
    docSelect() {},
    inputTextHandler(val) {
    // console.log(val)
    },
    headleChangeColor(titleColor) {
    // console.log(titleColor)
      return titleColor
    },
    // 上传图片
    uploadImg() {
      this.blockUploadImgVisible = true
    },

    // 添加文档图片上传
    handleAvatarSuccess(res, file) {
      this.docImageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    // 添加文档
    addDocument() {
      this.blockAddDocVisible = true
    },

    // 添加行数据
    addRow(index, rows) {
      rows.push({})
    },

    // 删除行数据
    deleteRow(index, rows) {
      rows.splice(index, 1)
    // console.log(index)
    },

    // 发布
    publishClickHandler() {
      this.update()
    },
    // 保存
    saveClickHandler() {
      this.update()
    },

    // 关闭弹窗
    closeHandler(val) {
      this.$emit('close', val)
    },

    // 编辑block标签确认按钮
    confirmClickHandler() {
      this.isShowModal = false // 隐藏弹窗
      this.update()
    },

    // 初始化批量添加内容表格数据
    async blockTableData() {
      let res = await axios.get(`/ui/blockTag`).catch(e => console.log(e))
      let data = res.data
      this.blockTagData = data.data
      this.dataLoading = false
    },
    // 初始化批量添加生成路径表格数据
    async blockPathTableData() {
      let res = axios.get(`/ui/blockUrl`, {params: {SearchFormName: this.searchForm.name}}).catch(e => console.log(e))
      let data = res.data
      this.blockUrlData = data.data
      this.dataLoading = false
    },

    // 初始化批量添加选择内容数据
    async recordContentListData() {
      let res = await axios.get(`/ui/workspace/recordContent`).catch(e => console.log(e))
      let data = res.data
      this.recordContentData = data.data
      this.dataLoading = false
    },

    // 数据更新
    async update() {
      let ids = []
      this.selectedRows.forEach(function(row) {
        ids.push(row.id)
      })
      let res = await axios.put(`/ui/templates/${ids}`).catch(e => console.log(e))
      // console.log(ids)

      this.$notify({
        title: '成功',
        message: `操作成功`,
        type: 'success',
        duration: 2000
      })

      return res.data
    }
  },
  props: {
    isShowModal: {
      type: Boolean,
      required: true
    },
    menuTreeData: {
      type: Array,
      default: _ => {
        return []
      }
    }
  },
  //    mounted() {
  //      let w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  //      let h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

  //     this.$refs.nana.style.height = h +'px';
  //   // console.log(this.$refs.nana.style.height);
  //    }
  async created() {
    this.blockTableData()
    this.blockPathTableData()
    this.recordContentListData()

    let res = await axios.get(`/ui/workspace/pages`).catch(e => console.log(e))
    let data = res.data
    this.allMenuTreeData = data.data
    this.dataLoading = false
  }
}
</script>

<style>
/* 选择区块生成路径 */
/* 搜索框 */
.blockDocDialog .el-dialog__body {
  padding: 0;
}
.blockDocDialog .el-form--inline {
  margin: 10px;
  text-align: left;
}
.blockDocDialog .el-form-item {
  margin-bottom: 0;
}
.blockDocDialog .el-form--inline .el-form-item__content {
  width: 100%;
}
.blockDocDialog .formBox {
  padding: 0 10px;
  border-radius: 4px;
  width: 60%;
  border: 1px solid #bfcbd9;
}
.blockDocDialog .formBox:hover {
  border: 1px solid #8391a5;
}
.blockDocDialog .formBox a {
  color: #495060;
}
.blockDocDialog .formBox .subUrl {
  padding: 0 5px;
}
.blockDocDialog .formBox .subUrl:first-child {
  padding: 0;
}
.rootUrl i {
  padding: 0;
}
.blockDocDialog .formNameBox {
  width: 25%;
}
.blockDocDialog .formNameBox .el-form-item__content {
  width: 65%;
}
/* 重命名 */
.rename-dialog .el-dialog .line {
  padding: 0 5px;
}
/* block标签 */
.block-dialog .el-form--inline {
  text-align: left;
}
.block-dialog .dialog-footer {
  float: right;
  margin: 20px 0;
}
.base-info-box,
.con-table-box {
  margin-left: -20px;
  margin-right: -20px;
}
.base-info {
  margin-bottom: 10px;
  padding: 0 20px;
  height: 50px;
  line-height: 50px;
  background: #eef1f6;
}
.block-dialog i {
  cursor: pointer;
}
.table-con {
  margin-top: 20px;
  width: 100%;
}
.table-con {
  overflow: auto;
}
.title-box {
  min-width: 100px;
  overflow: auto;
}
.con-form {
  text-align: left;
  white-space: nowrap;
}
.con {
  margin: 5px;
  padding: 0 40px 0 10px;
  position: relative;
  display: inline-block;
  border-radius: 4px;
  border: 1px solid #eee;
  line-height: 20px;
}
/* icon */
.circle {
  padding-left: 4px;
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 4px;
  border: 1px solid #eee;
  background: transparent;
  line-height: 19px;
}
.icon-box {
  position: absolute;
  right: 0;
}
.row-item .fa {
  display: none;
}
.row-item:hover .icon-add,
.row-item:hover .icon-plus {
  display: inline-block;
}
.con-item:hover .icon-edit,
.con-item:hover .icon-remove {
  display: inline-block;
}
.icon-l-add {
  float: left;
  line-height: 35px;
}
.icon-add {
  position: absolute;
  right: -15px;
  top: -5px;
  color: #637283;
}
.icon-edit {
  color: #637283;
}
.icon-remove {
  color: #d6a87b;
}
.icon-plus {
  color: #9facad;
}
.icon-minus {
  color: #ff6966;
}
/* 图片上传 */
.icon-img {
  color: #ccc;
}
.icon-crop {
  color: #637283;
}
/* .avatar-uploader {
    display: inline-block;
  }
  .avatar-uploader .avatar-uploader-icon {
    border: 1px dashed #eee;
    border-radius: 4px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .avatar-uploader-icon:hover {
    border-color: #20a0ff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
  }
  .add-doc-dialog {
    vertical-align: top;
  }
  .operate {
    margin-left: 10px;
    display: inline-block;
    height: 178px;
    line-height: 178px;
    vertical-align: top;
  }
  .operate i{
    line-height: 178px;
  } */
</style>
