<template>
  <div class="detail-content-box scroll">
    <content-info :content.sync="mContent" @catalog-change="catalogChange" :site-config="siteConfig" :catalog-id="catalogId">
      <div slot="editorList">
        <el-list-view ref="multipleTable" :data="images" v-show="images.length>0">
          <template slot-scope="row">
            <div class="panel-fieldset">
              <el-row>
                <el-col :span="6">
                  <img :src="row.isExternalURL==='Y' ? row.externalSource: (prefix + row.path + row.fileName + '?' + randomNumber)" onerror="this.src='assets/images/picture404-'+((row.ID||row.$index) % 4)+'.png';" class="list-img">
                </el-col>
                <el-col :span="18">
                  <el-row>
                    <el-col :span="3" style="line-height:36px;">
                      标题:
                    </el-col>
                    <el-col :span="21">
                      <el-input type="text" v-model="row.name" />
                    </el-col>
                  </el-row>
                  <br/>
                  <el-row>
                    <el-col :span="3" style="line-height:36px;">
                      摘要:
                    </el-col>
                    <el-col :span="21">
                      <el-input type="textarea" v-model="row.info" />
                    </el-col>
                  </el-row>
                  <br/>
                  <el-row>
                    <el-col :span="3" style="line-height:36px;">链接地址：</el-col>
                    <el-col :span="10">
                      <el-input v-if="showInputFlags(row.$index)" :disabled="!isInputUrl[row.$index]" v-model="row.linkURL"></el-input>
                      <el-input v-else :disabled="true" v-model="row.linkText"></el-input>

                    </el-col>
                    <el-col :span="11" align="right">
                      <el-button type="primary" @click="selectContent(row.$index)">链接到内容</el-button>
                      <el-button type="primary" @click="selectCatalog(row.$index)">链接到栏目</el-button>
                      <el-button type="primary" @click="inputUrl(row.$index)">外部地址</el-button>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
              <el-row class="list-card-buttons">
                <el-col :span="14">
                  <div>原名称:<em>{{row.oldFileName}}</em> </div>
                  <div><span v-show="row.isExternalURL!=='Y'">大小:<em>{{row.fileSize || '0'}}</em> &nbsp;</span>类型:<em>{{row.isExternalURL==='Y' ? '网络图片' : row.suffix}}</em> &nbsp;宽:<em>{{row.width}}</em> &nbsp;高:<em>{{row.height}}</em></div>
                </el-col>
                <el-col :span="10" class="imgBtn-class">
                  <br/>
                  <el-button class="el-button-extends" @click.stop="imageSort(row.$index,'up')" v-if="row.$index > 0 && row.ID">
                    <i class="fa fa-arrow-up" aria-hidden="true" title="上移"></i></el-button>
                  <el-button class="el-button-extends" @click.stop="imageSort(row.$index,'down')" v-if="row.$index < images.length-1 && row.ID && images[images.length-1].ID">
                    <i class="fa fa-arrow-down" aria-hidden="true" title="下移"></i></el-button>
                  <el-button @click="prevImg(row)"  class="el-button-extends"> <i class="fa fa-search-plus" aria-hidden="true" title="预览"></i></el-button>
                  <el-button @click="uploadImg(row.ID,row.isExternalURL==='Y')" :disabled="row.isExternalURL==='Y'" class="el-button-extends"><i class="fa fa-pencil-square-o" aria-hidden="true" title="编辑"></i></el-button>
                  <el-button @click="setLogo(row.ID, row.path + row.fileName)" :disabled="row.isExternalURL==='Y'" class="el-button-extends"><i class="fa fa-picture-o" aria-hidden="true" title="设置为封面"></i></el-button>
                  <el-button @click="cutImg(row)" :disabled="row.isExternalURL==='Y'" class="el-button-extends"><i class="fa fa-scissors" aria-hidden="true" title="裁剪"></i></el-button>
                  <el-button @click="delImg((row.ID))"  class="el-button-extends"><i class="fa fa-times" aria-hidden="true" title="删除"></i></el-button>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-list-view>

        <el-toolbar v-show="mContent.ID>0">
          <image-zip-upload-button :content="mContent" @refresh-content="refreshImages"></image-zip-upload-button>
          <el-button :priv="'com.zving.cms.Catalog.Content.Edit.'+mContent.catalogID" @click="interImageModal = true"><i class="fa fa-plus"></i>添加网络图片</el-button>
          <el-button :priv="'com.zving.cms.Catalog.Content.Edit.'+mContent.catalogID" @click="imageSelectModal = true"><i class="fa fa-plus"></i>添加资源库图片</el-button>
        </el-toolbar>
      </div>
    </content-info>

    <image-upload-dialog :visible.sync="imgUpload.uploadFlag"  :contentId="content.ID" :catalogId="content.catalogID" :id="imgUpload.id" @refreshlist="refreshImages"></image-upload-dialog>

    <image-cutting-dialog :show.sync="cutLogo.cuttingFlag" :siteID="content.siteID" :imagePath="cutLogo.imgPath" @callback="cuttingCallback"></image-cutting-dialog>

    <el-dialog :visible.sync="imgViewFlag" :append-to-body="true" :show-close="false" width="90%" top="0" custom-class="imgViewDialog">
      <div slot="title">
        <el-toolbar align="right">
          <el-button @click="isOriginaChange(true)" type="text" v-show="images[imgViewIndex] && images[imgViewIndex].isExternalURL!=='Y'" :disabled="isOriginal" style="backgroud:white;">
             <span>原图</span>
           </el-button>
           <el-button @click="isOriginaChange(false)" type="text" v-show="images[imgViewIndex] && images[imgViewIndex].isExternalURL!=='Y'" :disabled="!isOriginal" style="backgroud:white;">
             <span>缩略图</span>
           </el-button>
          <el-button @click="delViewImg()" type="text" style="backgroud:white">
             <span>删除</span>
           </el-button>
           <el-button @click="gotoImg(imgViewIndex-1)" style="backgroud:white" :disabled="imgViewIndex==0" type="text">
             <span> 上一张</span>
           </el-button>
           <el-button @click="gotoImg(imgViewIndex+1)" :disabled="imgViewIndex==images.length-1" type="text" style="backgroud:white">
             <span>下一张</span>
           </el-button>
           <el-button @click="imgViewFlag=!1" type="text" style="backgroud:white">
             <span> 返回列表</span>
           </el-button>
       </el-toolbar>
      </div>
        <div>
          <div >
              <img :src="(images[imgViewIndex] && images[imgViewIndex].isExternalURL==='Y')? images[imgViewIndex].externalSource : prefix + currentImgUrl"/>
          </div>
        </div>
    </el-dialog>
    <el-dialog title="添加网络图片" :visible.sync="interImageModal" @open="confirmLoading = false,interAddress=''" class="inter-image-dialog">
      <el-form label-width="150px" style="margin-top:20px;">
        <el-form-item label="网络图片地址：">
          <el-input v-model="interAddress" placeholder="使用回车键区分多个图片" type="textarea" :rows="3" style="width:90%;" ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="interImageModal = false">取 消</el-button>
        <el-button type="primary" @click="interImageConfirm" :loading="confirmLoading">确 定</el-button>
      </div>
    </el-dialog>
    <image-select-dialog :visible.sync="imageSelectModal" :content="content" @refreshlist="refreshImages"></image-select-dialog>
    <content-selector :show.sync="contentSelectorDialogModal" title="浏览内容" @callback="contentSelectCallback"></content-selector>
    <catalog-selector :show.sync="catalogSelectorDialogModal" inputType="radio" title="选择栏目" @callback="catalogSelectorCallback"></catalog-selector>
  </div>
</template>
<script>
import util from '@src/common/util.js'
import '../../contentcore/js/contentScript.js'
import imageCutting from '../../contentcore/commonImageCuttingDialog.vue'
import imageUpload from '../../contentcore/components/ImageUpload.vue'
import ContentInfo from '../../contentcore/components/ContentInfo.vue'
import emitter from '@src/mixins/emitter.js'
import imageZipUploadButton from '../../contentcore/components/ImageZipUploadButton.vue'
import imageSelectDialog from '../../contentcore/components/ImageSelectDialog.vue'
import catalogSelector from '../../contentcore/components/CatalogSelector.vue'
import ContentSelector from '@src/components/contentComponent/ContentSelector.vue'
export default {
  mixins: [emitter],
  components: {
    'image-upload-dialog': imageUpload,
    'image-cutting-dialog': imageCutting,
    'content-info': ContentInfo,
    imageZipUploadButton,
    imageSelectDialog,
    'catalog-selector': catalogSelector,
    'content-selector': ContentSelector
  },
  props: {
    content: {
      type: Object,
      default: function() {
        return {
          titleStyle: { color: '' },
          shortTitleStyle: { color: '' },
          detailTemplate: {},
          templateFlag: 'N'
        }
      }
    },
    prefix: {
      type: String,
      default: function() {
        return window.app ? window.app.prefix : window.opener && window.opener.app ? window.opener.app.prefix : ''
      }
    },
    siteConfig: {
      type: Object
    },
    contentId: {
      type: [String, Number]
    },
    catalogId: {
      type: [String, Number]
    }
  },
  computed: {
    mContent: {
      set(val) {
        this.$emit('update:content', val)
      },
      get() {
        return this.content
      }
    },
    images: {
      set(val) {
        this.mContent = Object.assign({}, this.mContent, { images: val })
      },
      get() {
        // TODO: 在vue的规则里get方法里不能赋值，请调整下面的代码
        // if (this.content.images) {
        //   this.content.images = this.content.images.filter(function(image, index) {
        //     return image.ID > 0
        //   })
        // }
        return this.content.images || []
      }
    },
    currentImgUrl() {
      if (this.images && this.images.length > 0) {
        if (this.isOriginal) {
          return this.images[this.imgViewIndex].path + this.images[this.imgViewIndex].fileName
        } else {
          var filename = this.images[this.imgViewIndex].fileName
          filename = filename.substring(0, filename.lastIndexOf('.')) + '_120x120' + filename.substring(filename.lastIndexOf('.'))
          return this.images[this.imgViewIndex].path + filename
        }
      }
      return ''
    }
  },
  data() {
    return {
      isInputUrl: [],
      contentSelectorDialogModal: false,
      catalogSelectorDialogModal: false,
      imageSelectModal: false,
      interImageModal: false,
      interAddress: '',
      confirmLoading: false,
      randomNumber: 1,
      imgViewFlag: false,
      imgViewIndex: 0,
      isOriginal: true,
      cutLogo: {
        currentImg: {},
        imgPath: '',
        cuttingFlag: false
      },
      imgUpload: {
        id: '',
        uploadFlag: false
      },
      resourceDialogProps: {
        selectorURL: 'imageResources',
        resourceType: 'image',
        allowType: '.jpg,.jpeg,.png,gif,.bmp',
        height: 200,
        width: 200,
        imageWidth: 260,
        imageHeight: 260,
        url: ''
      }
    }
  },
  async created() {
    this.initContent()
  },
  methods: {
    selectContent(index) {
      this.isInputUrl[index] = false
      this.imgViewIndex = index
      this.contentSelectorDialogModal = true
    },
    contentSelectCallback(row) {
      this.images[this.imgViewIndex].linkText = '内容：' + row.title
      this.images[this.imgViewIndex].linkURL = row.link
      this.images = this.images.concat()
    },
    selectCatalog(index) {
      this.isInputUrl[index] = false
      this.imgViewIndex = index
      this.catalogSelectorDialogModal = true
    },
    inputUrl(index) {
      this.imgViewIndex = index
      this.isInputUrl[index] = true
      if (!(this.images[index].linkURL && this.images[0].linkURL.startsWith('http://'))) {
        this.images[index].linkText = null
        this.images[index].linkURL = 'http://'
      }
      this.isInputUrl = this.isInputUrl.concat()
    },
    catalogSelectorCallback(row) {
      this.images[this.imgViewIndex].linkText = '栏目：' + row.name
      this.images[this.imgViewIndex].linkURL = row.link
      this.images = this.images.concat()
    },
    uploadImg(imgID, flag) {
      if (flag) {
        return
      }
      this.imgUpload = Object.assign({}, this.imgUpload, { id: imgID, uploadFlag: true })
    },
    async interImageConfirm() {
      this.confirmLoading = true
      if (this.interAddress.indexOf('-splitchar-') > -1) {
        this.$alert("图片链接中不能出现'-splitchar-'字符串", '提示', { type: 'warning' })
        return
      }
      let images = this.interAddress.split('\n')
      let res = await axios.post(`/ui/contentcore/contents/${this.mContent.ID}/images/interimg`, {
        data: images.join('-splitchar-'),
        catalogID: this.mContent.catalogID,
        groupID: this.mContent.ID
      })
      util.showResponseMessage(res.data)
      this.confirmLoading = false
      if (res.data.status === 1) {
        this.interImageModal = false
        this.refreshImages()
      }
    },
    async imageSort(index, type) {
      let newData = [
        ...this.images.filter((val, i) => (type === 'up' ? i < index - 1 : i < index)),
        ...this.images.filter((val, i) => (type === 'up' ? i === index : i === index + 1)),
        ...this.images.filter((val, i) => (type === 'up' ? i === index - 1 : i === index)),
        ...this.images.filter((val, i) => (type === 'up' ? i > index : i > index + 1))
      ]
      this.images = newData.concat()
      let res = await axios.put(`/ui/contentcore/contents/${this.mContent.ID}`, Object.assign({}, this.mContent, { images: newData }))
      util.showResponseMessage(res.data)
      if (res.data.status !== 1) {
        this.$emit('refreshlist', true)
      }
    },
    async setLogo(imgId, logoFile) {
      let resp = await axios.put(`/ui/contentcore/contents/${this.content.ID}/images/setlogo/${imgId}`, { catalogID: this.content.catalogID })
      util.showResponseMessage(resp.data)
      if (resp.data.status === 1) {
        logoFile = logoFile + (logoFile.indexOf('?') > 0 ? '&' : '?') + 'r=' + +(new Date())
        this.mContent = Object.assign({}, this.mContent, { logoFile: logoFile })
      }
    },
    async initContent() {
      this.editGroupFlag = this.mContent.ID > 0
      this.resourceDialogProps = Object.assign({}, this.resourceDialogProps, { catalogID: this.content.catalogID })
    },
    prevImg(row) {
      this.imgViewFlag = true
      this.imgViewIndex = this.images.indexOf(row)
    },
    cutImg(row) {
      this.cutLogo = Object.assign({}, this.cutLogo, { currentImg: row, imgPath: row.path + row.fileName, cuttingFlag: true })
    },
    cuttingCallback(sPath, path) {
      this.randomNumber = parseInt(Math.random() * 1000000)
    },
    async delImg(val) {
      try {
        await this.$confirm('确认删除该图片吗，删除后无法恢复！', '提示', { type: 'warning' })
      } catch (e) {
        return
      }
      let resp = await axios.delete(`/ui/contentcore/contents/${this.content.ID}/images/${val}`, {
        data: { catalogID: this.mContent.catalogID }
      })
      util.showResponseMessage(resp.data)
      if (resp.data.status === 1) {
        this.refreshImages()
      }
    },
    gotoImg(index) {
      if (index === this.imgViewIndex || index < 0 || index >= this.images.length) {
        return
      }
      this.imgViewIndex = index
    },
    async delViewImg() {
      if (this.imgViewIndex === 0 && this.images.length === 1) {
        this.imgViewFlag = false
        await this.delImg(this.images[0].ID)
        return
      }
      if (this.imgViewIndex === this.images.length - 1) {
        this.imgViewIndex--
        await this.delImg(this.images[this.imgViewIndex + 1].ID)
      } else {
        await this.delImg(this.images[this.imgViewIndex].ID)
      }
    },
    isOriginaChange(flag) {
      this.isOriginal = flag
    },
    refreshImages() {
      this.$emit('refreshlist', true)
      this.randomNumber = parseInt(Math.random() * 1000000)
    },
    catalogChange(catalog) {
      this.$emit('catalog-change', catalog)
    },
    showInputFlags(index) {
      if (this.isInputUrl[index]) {
        return true
      }
      if (typeof this.images[index].linkText === 'string' && this.images[index].linkText.length > 0) {
        return false
      } else {
        return true
      }
    }
  }
}
</script>
<style scoped>
.el-button-extends {
  padding: 0px;
  border: none;
}
.imgBtn-class {
  text-align: right;
}
.list-img {
  text-align: center;
  max-width: 200px;
  max-height: 178px;
}
.save-btn {
  text-align: right;
}
</style>
<style>
.editor-style-title .el-input__inner {
  color: inherit;
}
.el-dialog.imgViewDialog {
  height: 100vh;
  padding-bottom: 20px;
  margin-bottom: 0;
}
.el-dialog.imgViewDialog .el-dialog__body {
  max-height: calc(100vh - 20px);
  min-height: calc(100vh - 20px);
  margin-top: -85px;
  padding-top: 85px;
  margin-bottom: 0;
}
.el-dialog.imgViewDialog .el-dialog__body > div > div {
  height: calc(100vh - 115px);
  width: calc(90vw - 40px);
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
.el-dialog.imgViewDialog .el-dialog__body > div {
  height: calc(100vh - 115px);
  text-align: center;
}
.el-dialog.imgViewDialog .el-dialog__body img {
  max-width: 100%;
}
.el-dialog.imgViewDialog .el-toolbar .el-button {
  background: white;
}

.inter-image-dialog .el-dialog {
  width: 600px;
}
@media (max-width: 480px) {
  .inter-image-dialog .el-dialog {
    width: 96%;
  }
}
</style>
