<template>
  <el-dialog
    class="datav-desingn-dialog"
    style="overflow: hidden"
    fullscreen
    destroy-on-close
    ref="datavDesignerDialog"
    v-loading.fullscreen.lock="fullscreenLoading"
    :close-on-click-modal="false"
    :visible.sync="dialogVisible"
  >
    <el-container class="container">
      <el-header ref="header" class="container__header" height="48px">
        <div class="navbar-default box-shadow flex">
          <div class="navbar-default_left">
            <div @click="close(false)" class="back-btn">
              <i class="el-icon-back"></i>
              <span>返回</span>
            </div>
            <template
              v-if="
                layoutObj.id && layoutObj.alias && layoutObj.layoutType != 1
              "
            >
              <el-button
                @click="addToMenu('manage')"
                icon="el-icon-plus"
                class="default_btn"
                :disabled="pubMenuCountManage > 0"
                >添加到后端菜单</el-button
              >
              <el-button
                @click="addToMenu('front')"
                icon="el-icon-plus"
                class="default_btn"
                :disabled="pubMenuCountFront > 0"
                >添加到前端菜单</el-button
              >
            </template>
          </div>
          <div class="navbar-default_middle"><span>大屏展示设计器</span></div>
          <div class="button-group">
            <el-button
              type="default"
              @click="handleSave"
              icon="el-icon-document-checked"
              class="my_primary_btn"
              >{{ $t('eip.common.save') }}</el-button
            >
            <el-button
              type="default"
              @click="handleClear"
              icon="el-icon-delete"
              class="default_btn"
              >清空</el-button
            >
            <el-button
              type="default"
              @click="handlePreview"
              icon="el-icon-search"
              class="default_btn"
              >预览</el-button
            >
          </div>
        </div>
      </el-header>
      <el-container class="container__body">
        <el-aside class="container__body_control" width="50px" v-if="asideShow">
          <DatavFieldPanel
            ref="datavFieldPanel"
            :data.sync="widgetForm"
            :select.sync="widgetFormSelect"
            :selectMap.sync="selectWidgetMap"
            :layoutObj="layoutObj"
          />
        </el-aside>
        <el-main
          class="container__body--widget gridbackground"
          ref="elMain"
          :style="bgStyle"
        >
          <div
            :style="{
              width: widgetPanelStyle.width,
              height: widgetPanelStyle.height,
              position: 'relative',
            }"
          >
            <DatavDesignPanel
              ref="widgetForm"
              :data.sync="widgetForm"
              :select.sync="widgetFormSelect"
              :selectMap.sync="selectWidgetMap"
              :layoutObj="layoutObj"
              :opacity="backgroundOpacity"
              @initItemPosition="initItemPosition"
            />
            <div class="border left-top"></div>
            <div class="border right-top"></div>
            <div class="border left-bottom"></div>
            <div class="border right-bottom"></div>
          </div>
        </el-main>
        <el-aside
          width="320px"
          class="container__body--property"
          v-show="rightAsideShow"
        >
          <DatavConfigPanel
            ref="datavConfigPanel"
            :field.sync="widgetFormSelect"
            :layoutObj.sync="layoutObj"
            :widgetForm.sync="widgetForm"
            :selectWidgetMap="selectWidgetMap"
            :opacity.sync="backgroundOpacity"
            style="heigth: 100%"
          />
        </el-aside>
      </el-container>
    </el-container>
    <datav-add-to-menu
      ref="datavAddToMenu"
      name="datavAddToMenu"
      :alias="layoutObj.alias"
      append-to-body
      @confirmAddToMenu="confirmAddToMenu"
    />
  </el-dialog>
</template>
<script>
import DatavFieldPanel from '@/components/portal/DatavFieldPanel.vue'
import DatavConfigPanel from '@/components/portal/DatavConfigPanel.vue'
import DatavDesignPanel from '@/components/portal/DatavDesignPanel.vue'
const DatavAddToMenu = () => import('@/components/portal/DatavAddToMenu.vue')
import {fullScreenContainer} from '@jiaminghi/data-view'
import html2canvas from 'html2canvas'
import req from '@/request.js'
import portal from '@/api/portal.js'
import {datavToolMap, datavDecorationData} from '@/api/datavConfig.js'
let Base64 = require('js-base64').Base64
export default {
  components: {
    DatavFieldPanel,
    DatavDesignPanel,
    DatavConfigPanel,
    DatavAddToMenu,
  },
  data() {
    return {
      asideShow: true,
      rightAsideShow: true,
      dialogVisible: false,
      widgetForm: {
        list: [],
        config: {
          height: 1080,
          width: 1920,
          widthRatio: 1,
          heightRatio: 1,
          labelWidth: 100,
          backgroundType: 'color',
          backgroundColor: '#000',
          backgroundImage: 'bg1', //datav默认布局背景图片存放路径为assets/img/datav，图片命名前缀datav_，后缀为设置项中的值
          backgroundFile: {id: '', name: ''}, //背景图片附件id
          labelPosition: 'right',
          size: 'small',
        },
      },
      bgStyle: {
        position: 'relative',
        display: 'flex',
        justifyContent: 'center',
        // alignItems:'center',
        width: '100%',
        height: '100%',
        // width:'100%',
        // height:(this.$refs.datavDesignerDialog.$el.offsetHeight-45)+'px',
        overflow: 'hidden',
      },
      widgetPanelStyle: {
        width: '100%',
        height: '100%',
      },
      widhtScale: 1, //宽度比例
      gapHeight: 0, //高度比例差
      backgroundOpacity: 0.9, //背景颜色透明度
      widgetFormSelect: {alias: ''},
      isSubmit: true,
      columnMap: {},
      layoutObj: {},
      datavToolMap: JSON.parse(JSON.stringify(datavToolMap)),
      decorationMap: JSON.parse(JSON.stringify(datavDecorationData)),
      columnToolMap: {}, //图表、datav组件
      decorationToolMap: {}, //装饰组件,
      fullscreenLoading: false,
      uploadUrl: window.context.portal + '/system/file/v1/upload',
      selectWidgetMap: {},
      pubMenuCount: 0,
      pubMenuCountFront: 0,
      pubMenuCountManage: 0,
    }
  },
  methods: {
    showDialog(layoutId, pubMenuCount, pubMenuCountFront, pubMenuCountManage) {
      this.pubMenuCount=pubMenuCount || 0
      this.pubMenuCountFront=pubMenuCountFront || 0
      this.pubMenuCountManage=pubMenuCountManage || 0
      this.selectWidgetMap = {}
      this.dialogVisible = true
      this.widgetForm = {
        list: [],
        config: {
          height: 1080, //1080,
          width: 1920, //1920,
          labelWidth: 100,
          backgroundType: 'color',
          backgroundColor: '#000',
          backgroundImage: 'bg1',
          backgroundFile: {id: '', name: ''},
          labelPosition: 'right',
          size: 'small',
        },
      }
      if (layoutId) {
        this.loadData(layoutId, 0)
      } else {
        let _this = this
        setTimeout(function () {
          _this.initWidgetPanel()
        }, 100)
      }
    },
    showNewDialog(config) {
      this.selectWidgetMap = {}
      this.dialogVisible = true
      this.layoutObj = {
        name: config.data.name,
        alias: config.data.alias,
        layoutType: config.data.layoutType,
        memo: config.data.memo,
        enable: 1,
      }
      this.widgetForm = {
        list: [],
        config: {
          height: config.data.height, //1080,
          width: config.data.width, //1920,
          labelWidth: 100,
          backgroundType: 'color',
          backgroundColor: '#000',
          backgroundImage: 'bg1',
          backgroundFile: {id: '', name: ''},
          labelPosition: 'right',
          size: 'small',
        },
      }
      if (config.type == 'new') {
        this.layoutObj.type = 'datav'
      } else if (config.type == 'template') {
        this.layoutObj.type = 'template'
      } else if (config.type == 'copyTemplate') {
        this.layoutObj.type = 'datav'
        if (config.config) {
          this.widgetForm = config.config
        }
      } else if (config.type == 'unit') {
        this.layoutObj.type = 'unit'
      }
      let _this = this
      setTimeout(function () {
        _this.initWidgetPanel()
      }, 100)
    },
    loadData(layoutId) {
      let _this = this
      portal.getLayoutManageDesignData(layoutId, 0).then((response) => {
        this.columnMap = response.columnMap
        if (!response.sysIndexLayout) {
          //如果为空，说明现在新建
          this.layoutObj = {}
          this.layoutObj.layoutType = 0
        } else {
          _this.layoutObj = response.sysIndexLayout
          let json = JSON.parse(Base64.decode(this.layoutObj.designHtml))
          _this.$set(_this, 'widgetForm', json)
          _this.$set(
            _this,
            'backgroundOpacity',
            json.config ? json.config.backgroundOpacity : 0.9
          )
          if (json.list.length > 0) {
            _this.widgetFormSelect = json.list[0]
          }
        }
        _this.initWidgetPanel()
      })
    },
    initWidgetPanel() {
      const elHeight = this.$refs.elMain.$el.offsetHeight
      let scaleHeight = elHeight
      let scaleWidth = this.$refs.elMain.$el.offsetWidth
      let reverse = this.widgetForm.config.width < this.widgetForm.config.height
      if (!reverse) {
        const width = this.$refs.elMain.$el.offsetWidth
        const scale = this.widgetForm.config.width / width
        this.widhtScale = scale
        scaleHeight = this.widgetForm.config.height / scale
        try {
          this.gapHeight = (elHeight - scaleHeight) / 2
        } catch (error) {}
        this.$set(this.widgetPanelStyle, 'height', scaleHeight + 'px')
      } else {
        const scale = this.widgetForm.config.height / elHeight
        this.widhtScale = scale
        scaleWidth = this.widgetForm.config.width / scale
        this.$set(this.widgetPanelStyle, 'height', scaleHeight + 'px')
      }
      this.$refs.widgetForm.recordCanvasSize(
        elHeight,
        scaleHeight,
        scaleWidth,
        reverse,
        this.widgetForm.config.width,
        this.widgetForm.config.height
      )
    },
    handleGenerateJson() {
      this.jsonTemplate = this.widgetForm
      this.$message(JSON.stringify(this.widgetForm))
    },
    handleSave() {
      this.$refs.datavConfigPanel.valiateData().then((flag) => {
        if (!flag.status) {
          this.$message.warning(
            `${flag.message}有${flag.errorItem.length}个字段未通过校验，请正确填写表单内容`
          )
        } else {
          this.widgetForm.config.backgroundOpacity = this.backgroundOpacity
          this.layoutObj.designHtml = Base64.encode(
            JSON.stringify(this.widgetForm)
          )
          this.fullscreenLoading = true
          let captureData = this.$refs.widgetForm.savePic()
          const oldFileId = this.layoutObj.screenCaptureId
          let _this = this
          html2canvas(captureData.content, captureData.opts).then(function (
            canvas
          ) {
            context.mozImageSmoothingEnabled = false
            context.webkitImageSmoothingEnabled = false
            context.msImageSmoothingEnabled = false
            context.imageSmoothingEnabled = false
            canvas.toBlob(function (filedata) {
              var formdata = new FormData()
              formdata.append('image', filedata, _this.layoutObj.name + '.jpg')
              req
                .post(_this.uploadUrl, formdata)
                .then((response) => {
                  const result = response.data
                  if (result.success) {
                    _this.$set(
                      _this.layoutObj,
                      'screenCaptureId',
                      result.fileId
                    )
                    //如果之前截图文件已存在，则需要删除
                    if (oldFileId) {
                      req
                        .post(
                          window.context.portal + '/system/file/v1/remove',
                          oldFileId
                        )
                        .then((r) => {})
                    }
                  }
                  req
                    .post(
                      window.context.portal +
                        '/portal/sysIndexLayoutManage/sysIndexLayoutManage/v1/saveLayout',
                      _this.layoutObj
                    )
                    .then((response) => {
                      _this.fullscreenLoading = false
                      if (response.data.state) {
                        _this.$message.success(response.data.message)
                        _this.afterSaveData()
                        _this.layoutObj.id = response.data.value
                      } else {
                        _this.$message.error(response.data.message)
                      }
                    })
                    .finally(() => {
                      _this.fullscreenLoading = false
                      _this.$emit('refresh')
                    })
                })
                .finally(() => {
                  _this.fullscreenLoading = false
                  _this.$emit('refresh')
                })
            })
          })
        }
      })
    },
    afterSaveData() {
      // this.close(true)
      // this.$emit('close', null)
    },
    close(isConfirm) {
      if (!isConfirm) {
        this.$confirm(
          '您确认离开当前编辑页面？',
          '现在离开，内容不会自动保存',
          {
            cancelButtonText: '取消',
            confirmButtonText: '确定',
            type: 'warning',
            closeOnClickModal: false,
          }
        ).then(() => {
          this.selectWidgetMap = {}
          this.dialogVisible = false
          this.$refs.datavDesignerDialog.close()
        })
      } else {
        this.selectWidgetMap = {}
        this.dialogVisible = false
        this.$refs.datavDesignerDialog.close()
      }
    },
    initItemPosition(index, x, y) {
      try {
        let item = this.widgetForm.list[index]
        item.x = parseInt(
          (x - this.$refs.datavFieldPanel.$el.offsetWidth) * this.widhtScale
        )
        item.y = parseInt(y - this.gapHeight)
        this.$set(this.widgetForm.list, index, item)
      } catch (error) {}
    },
    //清空面板
    handleClear() {
      this.widgetFormSelect = {alias: ''}
      this.$set(this.widgetForm, 'list', [])
      this.$set(this.widgetForm, 'list', [])
    },
    //预览
    handlePreview() {
      if (this.widgetForm.list && this.widgetForm.list.length > 0) {
        let previewKey =
          Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999)
        sessionStorage.setItem(previewKey, JSON.stringify(this.widgetForm))
        let routeData = this.$router.resolve({
          name: 'datavPreview',
          query: {key: previewKey},
        })
        window.open(routeData.href, '_blank')
      } else {
        this.$message.warning('大屏元素不能为空，请先设计大屏元素。')
      }
    },
    addToMenu(type) {
      this.$refs.datavAddToMenu.showDialog(
        type,
        this.layoutObj.alias,
        '',
        this.layoutObj.id
      )
    },
    confirmAddToMenu(isFront){
      this.pubMenuCount+=1
      if(isFront){
        this.pubMenuCountFront = 1
      } else {
        this.pubMenuCountManage = 1
      }
      this.$emit('refresh')
    },
  },
  mounted() {
    let _this = this
    for (const key in this.datavToolMap) {
      if (Object.hasOwnProperty.call(this.datavToolMap, key)) {
        const obj = this.datavToolMap[key]
        if (obj.items && obj.items.length > 0) {
          _this.columnToolMap[key] = {desc: obj.desc, items: []}
          obj.items.forEach((item) => {
            _this.columnToolMap[key].items.push({
              type: item.type,
              name: item.name,
              alias: item.alias,
              icon: item.icon,
              template: item.template,
              zIndex: item.zIndex,
            })
          })
        }
      }
    }
    for (const key in this.decorationMap) {
      if (Object.hasOwnProperty.call(this.decorationMap, key)) {
        const obj = this.decorationMap[key]
        if (obj.items && obj.items.length > 0) {
          _this.decorationToolMap[key] = {desc: obj.desc, items: []}
          obj.items.forEach((item) => {
            _this.decorationToolMap[key].items.push({
              name: item.name,
              alias: item.alias,
              icon: item.icon,
              zIndex: item.zIndex,
            })
          })
        }
      }
    }
  },
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/element-variables.scss';

>>> .el-dialog.is-fullscreen {
  overflow: hidden;
  background-image: url('../../assets/img/design_bg.png');
}

.header {
  padding: 0;
  background: #fff;
  z-index: 7;
}

.controler-container {
  padding: 3px 5px;
  box-shadow: 2px 0 5px #ededed;
  overflow: hidden;
}

.property-container {
  margin-left: 3px;
  box-shadow: -2px 0 5px #ededed;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.widget-form-container {
  position: relative;
  padding: 0;
  margin-top: 0;
  margin-bottom: 15px;
  height: calc(100vh - 50px);
  /* height: calc(100vh - 80px); */
}

.footer-container {
  border-top: 1px solid #ededed;
}
.datav-desingn-dialog {
  overflow: hidden;
}
.datav-desingn-dialog >>> .el-dialog__header {
  display: none;
}

.datav-desingn-dialog >>> .el-dialog__body {
  padding: 0;
  height: 100%;
}
.button-group {
  height: 100%;
  line-height: 42px;
}
.bg {
  padding: 0.2rem 0.2rem 0 0.2rem;
  background-size: cover;
  background-position: center center;
  overflow: hidden;
  width: 100%;
  height: 100%;
}

.container {
  height: 100%;
  .container__header {
    // background: $--color-white;
    z-index: 7;
    position: relative;
    background-image: url('../../assets/img/design_bg.png');
    .navbar-default {
      height: 49px;
      background-image: none;
      border-radius: 0px;
      box-shadow: 0px 2px 5px rgba(86, 96, 117, 0.15);
      justify-content: space-between;
      background: rgba(34, 37, 40, 0.7);
      padding: 0 20px;

      .navbar-default_left {
        display: flex;
        align-items: center;
        .back-btn {
          color: #409eff;
          font-size: 12px;
          cursor: pointer;
          margin-right: 10px;
        }
      }
      .navbar-default_middle {
        position: absolute;
        left: 50%;
        margin-left: -206px;
        width: 411px;
        height: 100%;
        background: url('../../assets/img/design_header_bg.png');
        background-size: 100% 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        > span {
          color: #74b8ff;
          font-size: 20px;
          font-weight: bold;
          position: relative;
          top: -5px;
        }
      }
    }
  }
  .container__body {
    // height: calc(100% - 80px);
    padding-top: 10px;
    overflow: hidden;
    background-image: url('../../assets/img/design_bg.png');
    .container__body_control {
      overflow: visible;
    }
  }
  .container__footer {
    background: $--background-color-secondary;
    border-top: 1px solid $--border-color-base;
  }
  .container__body--widget {
    background: $--background-color-base;
    position: relative;
    padding: 0 5px;
    margin-top: 1px;
    padding-left: 0;
    // margin-left: -8px;
    // margin-right: -8px;
    .border {
      position: absolute;
      width: 40px;
      height: 40px;
      &.left-top {
        left: -3px;
        top: -3px;
        border-top: 3px solid #409eff;
        border-left: 3px solid #409eff;
      }
      &.right-top {
        right: -3px;
        top: -3px;
        border-top: 3px solid #409eff;
        border-right: 3px solid #409eff;
      }
      &.left-bottom {
        left: -3px;
        bottom: -3px;
        border-bottom: 3px solid #409eff;
        border-left: 3px solid #409eff;
      }
      &.right-bottom {
        right: -3px;
        bottom: -3px;
        border-bottom: 3px solid #409eff;
        border-right: 3px solid #409eff;
      }
    }
  }
  .container__body--property {
    background: rgba(27, 29, 32, 0.6);
    box-shadow: 0px 0px 9px 1px rgba(111, 112, 113, 0.08);
  }
  .el-header {
    padding: 0px 0px;
  }
  .gridbackground {
    /*网格背景*/
    /*90度直线，100灰度，0.1透明度，5%宽度，0透明度背景*/
    // background: linear-gradient(90deg, rgba(100, 100, 100, 0.1) 5%, transparent 0),
    /*0度直线，100灰度，0.1透明度，5%宽度，0透明度背景*/
    // linear-gradient(rgba(100, 100, 100, 0.1) 5%, transparent 0);
    /*横纵向宽距*/
    // background-size: 15px 15px;

    background: transparent;
    // box-shadow: 0px 0px 11px 1px rgba(8, 13, 39, 0.7);
    padding: 20px;
  }
  .default_btn {
    color: #409eff;
    border: 1px solid #409eff;
    background: linear-gradient(-90deg, #25272b 0%, #1a3857 50%, #25272b 96%);
    border-radius: 3px;
    font-size: 12px;
  }
  .my_primary_btn {
    border: 1px solid #409eff;
    // border-image: linear-gradient(-53deg, #58C8EF, #8EAEF5, #7CE5F5, #7BB2F6) 10 10;
    background: linear-gradient(140deg, #3e97f2 27%, #4171f9 73%);
    border-radius: 3px;
    color: #fff;
    font-size: 12px;
  }
}
</style>
