<template>
  <div class="es-template">
    <el-tabs v-if="controlProps.pageStyle === 'tabs'" v-model="current" :before-leave="beforeLeave"
             class="es-template--tabs"
             v-bind="controlProps" @tab-click="tabsChange">
      <el-tab-pane v-for="(oneModule, indexOne) in modules" :id="oneModule.id" :key="indexOne"
                   :label="oneModule.moduleName">
        <!-- View -->
        <TemplateComp :ref="oneModule.id" :bizParams="bizParams" :errorMessage="errorMessage[oneModule.id]"
                      :modules="oneModule.twoModules"
                      :oneModuleId="oneModule.id"
                      :formData="formData"
                      :oneModuleName="oneModule.moduleName" :saveData="saveData[oneModule.id]"
                      class="es-template__content" @callInterface="callInterface"></TemplateComp>

        <!-- Action -->
        <div v-if="showSubmit && !readOnly" :id="'btn_'+oneModule.id" class="es-template__footer">
          <el-button v-if="getModuleProp(oneModule, 'isDownloadPdf')" :disabled="loading" :loading="pdfLoading"
                     icon="el-icon-download" plain type="primary"
                     @click="exportPdf(oneModule)">导出PDF
          </el-button>
          <el-button v-if="getModuleProp(oneModule, 'isSubmit')" :disabled="loading" :loading="loading || btnLoading"
                     plain
                     type="danger" @click="submitForm(oneModule)">提交
          </el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!---->
    <div v-if="controlProps.pageStyle === 'steps'"
         :class="{'es-steps--isVertical' : isVertical}" class="es-template--steps">
      <el-steps :active="current"
                :direction="controlProps.direction"
                :style="{height: 'auto'}"
                align-center>
        <el-step v-for="(oneModule, indexOne) in modules" :key="indexOne" :title="oneModule.moduleName"></el-step>
      </el-steps>

      <div ref="stepsMain" class="es-template--steps__main">
        <div v-for="(oneModule, indexOne) in modules" v-show="current === indexOne" :key="indexOne">
          <TemplateComp :ref="oneModule.id" :bizParams="bizParams"
                        :errorMessage="errorMessage[oneModule.id]"
                        :modules="oneModule.twoModules"
                        :oneModuleId="oneModule.id"
                        :formData="formData"
                        :oneModuleName="oneModule.moduleName" :saveData="saveData[oneModule.id]"
                        class="es-template__content" @callInterface="callInterface"></TemplateComp>

          <div class="es-template__footer">
            <el-button v-if="indexOne > 0" @click="handlerStep('prev')">上一步</el-button>
            <el-button v-if="indexOne === modules.length-1" :disabled="loading" :loading="loading || btnLoading"
                       plain
                       type="danger" @click="submitAllForm()">提交
            </el-button>
            <el-button v-if="indexOne < modules.length-1" @click="handlerStep('next')">下一步</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import TemplateComp   from './TemplateComp'
import validate       from '../hooks/validate'
import getFormData    from '../hooks/getFormData'
import business       from '../hooks/business'
import submitForm     from '../hooks/submitForm'
import queryFormData  from '../hooks/queryFormData'
import useEmits       from "../hooks/useEmits";

import html2canvas from 'html2canvas';
import jsPDF       from 'jspdf';

export default {
  name: "TemplateViews",
  mixins: [validate, getFormData, submitForm, business, queryFormData, useEmits],
  components: {TemplateComp},
  props: {
    config: {type: Object},
    formData: {type: Object},
    readOnly: {type: Boolean, default: false},
    bizParams: {type: Object},
    extraParams: {type: Object},
  },
  provide() {
    return {
      _tempV: this
    };
  },
  data() {
    return {
      current: 0,
      controlProps: {},
      modules: [],
      template: {},
      moduleInfo: {},
      // show/hide
      showSubmit: true,
      loading: false,
      pdfLoading: false,
      btnLoading: false,
      errorMessage: {},
    }
  },
  computed: {
    // 是否tabs模式
    isTabs() {
      return this.controlProps.pageStyle && this.controlProps.pageStyle === 'tabs'
    },

    isPageLoad() {
      return this.isTabs ? this.controlProps.isPageLoad === 'true' : false
    },

    isVertical() {
      return this.controlProps.direction === 'vertical'
    },
  },
  watch: {
    config: {
      handler(newVal, oldVal) {
        if (newVal && newVal.prop) {
          this.__resetTemp();
          this.controlProps = newVal.prop
          if (newVal.modules) {
            this.modules = newVal.modules
          }
          if (newVal.moduleInfo) {
            this.moduleInfo = newVal.moduleInfo
          }
          if (newVal.template) {
            this.template = newVal.template
          }
          // this.queryModuleData()
        }
      },
      deep: true,
      immediate: true
    },

    bizParams: {
      handler(newVal, oldVal) {
        if (newVal && Object.keys(newVal).length > 0 && Object.keys(this.moduleInfo).length > 0) {
          this.queryModuleData()
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    __resetTemp() {
      this.modules = []
      this.controlProps = {}
      this.template = {}
      this.components = []
      this.saveData = {}
      this.loadPage = {}
      this.current = 0
      this.showSubmit = true
      this.btnLoading = false
    },

    resetData() {
      this.saveData = {}
      this.current = 0
      this.loadPage = {}
    },


    handleChange(model, value, control) {
      this.$emit('change', model, value, control)
    },

    /**
     * 导出PDF
     * @param oneModule
     */
    exportPdf(oneModule) {
      this.pdfLoading = true
      let oneModuleEle = document.getElementById(oneModule.id);
      let btnOneModuleEle = document.getElementById('btn_' + oneModule.id);
      oneModuleEle.removeChild(btnOneModuleEle);
      this.downPdf(oneModule.moduleName, oneModuleEle);
      oneModuleEle.appendChild(btnOneModuleEle);
      this.pdfLoading = false
    },

    downPdf(pdfName, ele) {
      pdfName = pdfName + ".pdf"
      html2canvas(ele, {
        dpi: 300,
        // allowTaint: true,  //允许 canvas 污染， allowTaint参数要去掉，否则是无法通过toDataURL导出canvas数据的
        useCORS: true  //允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
      }).then((canvas) => {
        let contentWidth = canvas.width;
        let contentHeight = canvas.height;
        //一页pdf显示html页面生成的canvas高度;
        let pageHeight = contentWidth / 592.28 * 841.89;
        //未生成pdf的html页面高度
        let leftHeight = contentHeight;
        //页面偏移
        let position = 0;
        //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
        let imgWidth = 595.28;
        let imgHeight = 595.28 / contentWidth * contentHeight + 100;
        //添加水印
        let ctx = canvas.getContext("2d")
        let watermarkerCnt = contentHeight / 200
        for (let i = 0; i < watermarkerCnt; i++) {
          ctx.rotate((-5 * Math.PI) / 180); // 水印初始偏转角度
          ctx.font = "30px microsoft yahei";
          ctx.fillStyle = "rgba(213,213,213,0.5)";
          let watermarkerStr = ''
          for (let j = 0; j < 10; j++) {
            watermarkerStr += '小榄村镇银行      '
          }
          ctx.fillText(watermarkerStr, -300, (i + 1) * 200);
          ctx.rotate((5 * Math.PI) / 180); // 把水印偏转角度调整为原来的，不然他会一直转
        }

        let pageData = canvas.toDataURL('image/jpeg', 1.0);
        let pdf = new jsPDF('', 'pt', 'a4');
        //有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
        //当内容未超过pdf一页显示的范围，无需分页
        if (leftHeight < pageHeight) {
          //在pdf.addImage(pageData, 'JPEG', 左，上，宽度，高度)设置在pdf中显示；
          pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
          // pdf.addImage(pageData, 'JPEG', 20, 40, imgWidth, imgHeight);
        } else {    // 分页
          while (leftHeight > 0) {
            pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
            leftHeight -= pageHeight;
            position -= 841.89;
            //避免添加空白页
            if (leftHeight > 0) {
              pdf.addPage();
            }
          }
        }
        //可动态生成
        pdf.save(pdfName);
      })
    },

    /**
     * @name tabsChange
     * @param activeKey
     */
    tabsChange(activeKey) {
      if (this.isPageLoad && !this.loadPage[activeKey]) {
        this.queryModuleData()
      }
    },

    /**
     * 在离开当前tab前，检查二级模块是否需要重新从后端加载数据，或使用前端最新数据
     */
    beforeLeave(newActiveName, oldActiveName) {
      if (oldActiveName !== undefined && this.modules[oldActiveName]) {
        const oneModuleId = this.modules[oldActiveName].id
        if (this.modules[oldActiveName].twoModules) {
          this.modules[oldActiveName].twoModules.forEach(twoModule => {
            const twoModuleId = twoModule.id
            if (this.isViewTempType(oneModuleId, twoModuleId) === false) {
              if (this.$refs[oneModuleId][0] && this.$refs[oneModuleId][0].$refs[twoModuleId][0]) {
                this.$refs[oneModuleId][0].$refs[twoModuleId][0].getFormData(false, true).then(moduleData => {
                  this.$set(this.saveData[oneModuleId], twoModuleId, moduleData)
                })
              }
            }
          })
        }
      }
      return true
    },

    /**
     * @name handlerStep
     * @param type
     */
    handlerStep(type) {
      if (type === 'next') {
        this.beforeLeave(null, this.current++)
      } else if (type === 'prev') {
        this.beforeLeave(null, this.current--)
      }
    }
  }
}
</script>
