import {Component, Vue, Prop, Watch} from 'vue-property-decorator';
import { Getter, State } from 'vuex-class';
import { reduce, ceil, subtract, divide } from 'lodash';
import html2canvas from 'html2canvas';
import uuidv4 from 'uuid/v4';
import Upload from '@editor/component/DynamicForm/component/Upload/index.vue';
import editorApi from '@api/editor.api';
import config from '@config/index';
import { getStyle } from '@service/utils.service';

@Component({ components: { Upload }, name: 'BasicPageForm' })
export default class DynamicForm extends Vue {
  @Getter('pageInfo') pageInfo;
  @Getter('pageData') pageData;
  @State(state => state.tenant.cartAndShareBtn) cartAndShareBtn;
  @Prop(Boolean) value;
  validTime: array = [];
  showPopup: boolean = false;
  loadingSave: boolean = false;
  loadingPreview: boolean = false;
  formCustom: PageInfo = {};
  ruleCustom: object = {
    pageName: [
      { required: true, message: '请输入页面名称', trigger: 'blur' }
    ],
    shareOpenMethod: [
      { validator: this.validateOpenMethod, trigger: 'blur'  }
    ],
  };

  get enableShare() {
    return this.pageData.props?.btAttachVal.some(item => item.persets === '分享');
  }

  @Watch('pageData', { immediate: true })
  onPageDataChange(newVal) {
    const { pageName, pageDescribe, pageKeywords, coverImage, isPublish, isTemplate, page, validStartTime, validEndTime, redirectUrl } = this.pageInfo;
    const { shareOpenMethod, shareCoverImage, diversion } = page.props;
    this.formCustom = { pageName, pageDescribe, pageKeywords, coverImage, isPublish: !!isPublish, isTemplate: !!isTemplate, shareCoverImage, shareOpenMethod, diversion, validStartTime, validEndTime, redirectUrl };
    this.validTime = validStartTime && validEndTime ? [validStartTime, validEndTime] : [];
    // `${validStartTime} - ${validEndTime}` : '';
  }

  @Watch('value')
  onValueChange(val) {
    console.log('onValueChange', val);
    this.showPopup = val;
    this.loadingSave = false;
    this.loadingPreview = false;
  }

  handleSubmit(type) {
    this.$refs.formCustom?.validate(async (valid) => {
      if (valid) {
        if (type === 'save') {
          this.loadingSave = true;
        } else if (type === 'preview') {
          this.loadingPreview = true;
        }
        await this.createCoverImage();
        this.$emit('submit', type, { ...this.formCustom, isPublish: this.formCustom.isPublish ? 1 : 0, isTemplate: this.formCustom.isTemplate ? 1 : 0 });
      }
    });
  }

  change(val) {
    this.$emit('input', val);
  }

  validTimeChange(val) {
    if (val.length && val[0] && val[1]) {
      if (val[1].slice(-8) === '00:00:00') {
        val[1] = val[1].replace('00:00:00', '23:59:59');
      }
    }
    this.validTime = val;
    this.formCustom.validStartTime = val[0] || '';
    this.formCustom.validEndTime = val[1] || '';
  }

  preview() {
    this.formCustom.pageName = this.formCustom.pageName || '未命名';
    this.handleSubmit('preview');
  }

  autoSave() {
    this.formCustom.pageName = this.formCustom.pageName || '未命名';
    this.handleSubmit('autoSave');
  }
  validateOpenMethod(rule, value, callback) {
    if (!value && this.enableShare) {
      callback(new Error('请选择分享打开方式'));
    } else {
      callback();
    }
  }

  changeStyle(type) {
    const gridEle = document.querySelector('.vue-grid-layout');
    gridEle.childNodes.forEach(v => {
      if (v.classList && v.classList.contains('vue-grid-item') && !v.classList.contains('vue-grid-placeholder')) {
        if (type === 'forward') {
          const transform = getStyle(v, 'transform');
          const transformY = transform.split('(')[1].split(')')[0].split(',')[5];
          v.style.transform = 'none';
          v.style.top = `${transformY}px`;

        } else if (type === 'backward') {
          const top = getStyle(v, 'top');
          v.style.transform = `translate3d(0px, ${top}px, 0px)`;
          v.style.top = 'auto';
        }
      }
    });
  }

  async createCoverImage() {
    try {
      const imgName = btoa(`coverImage-${uuidv4().substr(0, 8)}`);
      const gridEle = document.querySelector('.Dcm-container-panel');
      this.changeStyle('forward');
      const canvas = await html2canvas(gridEle as HTMLElement, { useCORS: true, allowTaint: true });
      this.changeStyle('backward');
      const base64 = canvas.toDataURL();
      const { data: { uptoken } } = await editorApi.getUpToken();
      const { data: { key } } = await editorApi.uploadBase64(base64.split(',')[1], imgName, `UpToken ${uptoken}`);
      this.formCustom.coverImage = config.qiniuHost + '/' + key;
    } catch (e) {
      console.log(e);
    }
  }
}