<template>
  <div class="layout-no-cols">

    <el-toolbar>
      <el-button @click="$router.back()" type="primary" size="medium" round class="shadow-primary">
        <i class="fa fa-chevron-left"></i> 返回上页
      </el-button>
      <span class="button-separator"></span>
      <el-button @click="submitStyleNodeClickHandler" :priv="nodeID === 'new' ? 'SiteStyleManage.AddSubject' : 'SiteStyleManage.EditSubject'" :loading="confirmLoading">
        <i class="fa fa-save"></i>保 存
      </el-button>
    </el-toolbar>
    <div>
      <div class="detail-panel form-panel">
        <el-form :model="tmpStyleNode" :rules="styleNodeRule" ref="addOrEditStyleNodeForm" label-width="128px" v-loading="dialogLoading">
          <el-form-item label="名称：" prop="name" :verify="['NotNull']">
            <el-input v-model="tmpStyleNode.name"></el-input>
          </el-form-item>
          <el-form-item label="起止时间：">
            <el-col :span="11">
              <el-form-item prop="startTime" label-width="0">
                <el-date-picker type="datetime" id="style-node-start-time" :editable="false" placeholder="选择开始时间" v-model="tmpStyleNode.startTime" value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 100%;"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col class="timeTo" :span="2">至</el-col>
            <el-col :span="11">
              <el-form-item prop="endTime" label-width="0">
                <el-date-picker type="datetime" id="style-node-end-time" :editable="false" placeholder="选择结束时间" v-model="tmpStyleNode.endTime" value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 100%;"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="操作：">
            <el-button :plain="false" @click="selectNodeTemplateClickHandler">选择模板</el-button>
            <el-button v-for=" (item,index) in nodeTemplates.imagesURL" :key="item.name" @click="modifyPicClickHandler(item.URL,index)">{{item.name}}</el-button>
            <el-button @click="contentPreview" v-show="tmpStyleNode.content && tmpStyleNode.content.length > 0">预览</el-button>
          </el-form-item>
          <el-form-item label="代码：">
            <el-input v-model="tmpStyleNode.content" type="textarea" :rows="8" placeholder="可单击选择模板按钮选择系统内置代码模板"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!--选择风格节点模板-->
    <style-template-selector :show.sync="nodeTemplates.dlgShow" @callback="selectTemplateCallback"></style-template-selector>
    <resource-dialog :show.sync="resourceDialogModal" :resource-dialog-props="resourceDialogProps" title="图片上传" @callback="resourceDialogCallback"></resource-dialog>

  </div>
</template>
<script>
import util from '@src/common/util.js'
import resouceDialog from '../contentcore/resourceDialog.vue'
import styleTemplateSelector from './styleTemplateSelector.vue'
export default {
  data() {
    var _this = this
    var validateTime = function(rule, value, callback) {
      try {
        if (_this.tmpStyleNode.startTime && _this.tmpStyleNode.startTime >= value) {
          callback(new Error('结束时间应大于开始时间'))
        } else {
          callback()
        }
      } catch (e) {
        callback(new Error('日期格式不正确'))
      }
    }
    return {
      dialogLoading: false,
      confirmLoading: false,
      nodeTemplates: {
        imagesURL: [],
        dlgShow: false
      },
      styleNodeRule: {
        startTime: [{ required: true, message: '请选择日期', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择日期', trigger: 'change' }, { validator: validateTime, trigger: 'change' }]
      },
      resourceDialogProps: {},
      resourceDialogModal: false,
      tmpStyleNode: {}
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      if (!this.nodeID || this.nodeID === 'new') {
      } else {
        this.dialogLoading = true
        this.confirmLoading = false
        try {
          let res = await axios.get(`/ui/stylenodes/${this.nodeID}`)
          this.tmpStyleNode = res.data.data
        } catch (e) {}
        this.getImagesByTemplateContent(this.tmpStyleNode.content)
        this.dialogLoading = false
      }
    },
    // 选择风格模板
    selectNodeTemplateClickHandler() {
      this.nodeTemplates.dlgShow = true
    },
    // 修改图片
    modifyPicClickHandler(imageurl, index) {
      this.resourceDialogProps = {
        resourceType: 'image',
        catalogID: 0,
        inputType: 'radio',
        imageType: 'logo'
      }
      this.resourceDialogFrom = index
      this.resourceDialogModal = true
    },

    resourceDialogCallback(spath, path) {
      let url
      let oldstr = this.nodeTemplates.imagesURL[this.resourceDialogFrom].URL
      if (path.toLowerCase().startsWith('http')) {
        url = `url(${path})`
      } else {
        url =
          'url($' + '{Prefix}' +
          `${path.indexOf('_') > 0 ? path.substring(0, path.lastIndexOf('_')) + path.substring(path.lastIndexOf('.'), path.length) : path})`
      }
      this.nodeTemplates.imagesURL[this.resourceDialogFrom].URL = url
      this.tmpStyleNode.content = this.tmpStyleNode.content.replace(oldstr, url)
    },
    // 根据模板内容获取图片路径
    getImagesByTemplateContent(templateContent) {
      this.nodeTemplates.imagesURL = []
      if (!templateContent) {
        return
      }
      let re = templateContent.match(/url\((URL){0}.*?\)/gi)
      if (re && re.length > 0) {
        for (let i = 0; i < re.length; i++) {
          this.nodeTemplates.imagesURL.push({
            name: '修改图片' + (i + 1),
            URL: re[i]
          })
        }
      }
    },
    // 预览
    contentPreview() {
      let str = this.tmpStyleNode.content
      if (!str || !str.length) {
        this.$alert('请先选择模板或者填写代码！', '提示', { type: 'info' })
        return
      }
      str = str.replace(/\$\{Prefix\}/gi, this.tmpStyleNode.prefix || this.$root.prefix || '')
      let win = window.open()
      win.document.write(str.replace(/\u00a0/g, ' '))
    },

    // 选择风格模板界面单击确定按钮
    async submitStyleNodeClickHandler() {
      try {
        await util.validateForm(this.$refs['addOrEditStyleNodeForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }
      this.confirmLoading = true
      Vue.set(this.tmpStyleNode, 'siteStyleID', this.styleID)
      let res
      if (!this.nodeID || this.nodeID === 'new') {
        res = await axios.post('/ui/stylenodes', this.tmpStyleNode)
      } else {
        res = await axios.put(`/ui/stylenodes/${this.nodeID}`, this.tmpStyleNode)
      }
      util.showResponseMessage(res.data)
      this.confirmLoading = false
      if (res.data.status === 1) {
        this.isShow = false
        this.$emit('callback', this.tmpStyleNode)
      }
    },

    // 选择风格模板界面单击确定按钮
    selectTemplateCallback(data) {
      this.tmpStyleNode.content = data
      this.getImagesByTemplateContent(this.tmpStyleNode.content)
    }
  },
  props: {
    styleID: {
      type: [String, Number],
      default: 0
    },
    nodeID: {
      type: [String, Number],
      default: 0
    }
  },
  components: {
    'resource-dialog': resouceDialog,
    'style-template-selector': styleTemplateSelector
  }
}
</script>
<style>
.style-node-dialog .el-dialog {
  width: 650px;
}

@media (max-width: 480px) {
  .style-node-dialog .el-dialog {
    width: 96%;
  }
}
</style>
<style scoped>
.timeTo {
  text-align: center;
}
</style>
