/* eslint-disable no-undef */
/*
 *
 * Create
 *
 */

import PropTypes from 'prop-types';

import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { createStructuredSelector } from 'reselect';
import { injectIntl, intlShape } from 'react-intl';
import isEmpty from 'lodash/isEmpty';
import cloneDeep from 'lodash/cloneDeep';
import forEach from 'lodash/forEach';
import isEqual from 'lodash/isEqual';
import get from 'lodash/get';
import { CapRow, CapColumn, CapButton, CapCard, CapSpin, CapInput, CapHeading, CapDivider, CapIcon, CapLink, CapLabel, CapNotification, CapSlideBox } from '@capillarytech/cap-ui-library';
import makeSelectCreate, {makeSelectTemplates, getAssetDetails, getContentAssetDetails} from './selectors';
import * as actions from './actions';
import richmediaschema from './richmediaschema';
import './_createRichmedia.scss';
import messages from './messages';
import FormBuilder from '../../../../v2Components/FormBuilder';
import WechatRichmediaTemplatePreview from '../../../../v2Components/TemplatePreview/WechatRichmediaTemplatePreview';
import noImage from '../../../../assets/noImage.png';
import Pagination from '../../../../v2Components/Pagination';
import { CAP_SPACE_08, CAP_SPACE_12, CAP_SPACE_16 } from '@capillarytech/cap-ui-library/styled/variables';
import { GA } from '@capillarytech/cap-ui-utils';
import { CREATE, EDIT, TRACK_CREATE_WECHAT, TRACK_EDIT_WECHAT } from '../../../App/constants';
import { gtmPush } from '../../../../utils/gtmTrackers';
import { WECHAT } from '../../../CreativesContainer/constants';
import { getCdnUrl } from '../../../../utils/cdnTransformation';
import injectSaga from '../../../../utils/injectSaga';
import injectReducer from '../../../../utils/injectReducer';
import { v2WechatRichmediaTemplatesCreateSagas } from './sagas';
import v2WechatRichmediaTemplatesCreateReducer from './reducer';
import { compose } from 'redux';


export class Create extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    let templateData = {};
    let isEdit = false;
    let totalContentBlocks = 0;
    let mediaId = "";
    let templateId = "";
    let templateName = "";
    let isIframe = false;
    if (props.location.query.type === "embedded" && props.location.query.module === "library" && props.mode === 'EDIT' && !props.location.query.isEditFromCampaigns) {
      isIframe = true;
    }
    if (props.mode === 'EDIT') {
      templateData = props.templateData;
      isEdit = true;
      totalContentBlocks = props.totalContentBlocks;
      mediaId = props.mediaId;
      templateId = props.templateId;
      templateName = props.templateName;
    }
    this.state = {
      richmediaSchema: richmediaschema,
      map: {
        "image-value": {
          onUpload: this.uploadImage,
        },
        "title-value": {
          onChange: this.onFormDataChange,
        },
        "author-value": {
          onChange: this.onFormDataChange,
        },
        "cover-abstract-value": {
          onChange: this.onFormDataChange,
        },
        "source-link-value": {
          onChange: this.onFormDataChange,
        },
        "content-value": {
          getEditorInstanse: this.getEditorInstanse,
          onContentChange: this.onContentChange,
          onFocusOut: this.focusOutFromCkEditor,
          onFocusIn: this.focusInFromCkeditor,
        },
        "show-cover-pic-value": {
          onChange: this.onFormDataChange,
        },
        "post-comments-value": {
          onChange: this.onFormDataChange,
        },
        "content-image-value": {
          onUpload: this.uploadImage,
        },
      },
      isEdit,
      isFormValid: true,
      templateData,
      currentContentId: 0,
      totalContentBlocks,
      templateName,
      templateId,
      mediaId,
      isIframe,
      hovered: false,
      loading: false,
      showPreview: false,
      focusOut: true,
      showModal: false,
      modalContent: {
        title: this.props.intl.formatMessage(messages.modalTitle),
        body: this.props.intl.formatMessage(messages.modalBody),
        type: 'confirm',
        id: 'template-back-confirm-modal',
      },
      showExistingTemplates: false,
      existingTemplatesPageNo: 1,
      existingTemplatesPageLimit: 25,
      sortBy: 'Most Recent',
      searchText: '',
      pagination: true,
      scrollDebounce: true,
    };
    this.onFormDataChange = this.onFormDataChange.bind(this);
    this.cancelHandler = this.cancelHandler.bind(this);
    this.templateNameHandler = this.templateNameHandler.bind(this);
    this.saveHandler = this.saveHandler.bind(this);
    this.previewHandler = this.previewHandler.bind(this);
    this.setFormValidity = this.setFormValidity.bind(this);
    this.injectEvents = this.injectEvents.bind(this);
    this.injectSections = this.injectSections.bind(this);
    this.injectContainer = this.injectContainer.bind(this);
    this.injectColLabelSection = this.injectColLabelSection.bind(this);
    this.injectMultiColSection = this.injectMultiColSection.bind(this);
    this.getMappedEvent = this.getMappedEvent.bind(this);
    this.updateTotalContentBlocks = this.updateTotalContentBlocks.bind(this);
    this.insertTemplateData = this.insertTemplateData.bind(this);
    this.uploadImage = this.uploadImage.bind(this);
    this.returnCardLayout = this.returnCardLayout.bind(this);
    this.menuOnClickEvent = this.menuOnClickEvent.bind(this);
    this.showErrorMessage = this.showErrorMessage.bind(this);
    this.returnCurrentFormData = this.returnCurrentFormData.bind(this);
    this.returnCurrentSchema = this.returnCurrentSchema.bind(this);
    // this.handleFrameTasks = this.handleFrameTasks.bind(this);
    this.getCurrentWindow = this.getCurrentWindow.bind(this);
    // this.startLoading = this.startLoading.bind(this);
    this.moveToTemplates = this.moveToTemplates.bind(this);
    this.showNext = this.showNext.bind(this);
    this.prepareWeChatRichmediaPreviewData = this.prepareWeChatRichmediaPreviewData.bind(this);
    this.injectMessages = this.injectMessages.bind(this);
  }
  componentDidMount = () => {
    if (!this.state.isEdit) {
      this.updateTotalContentBlocks();
    }
  }
  componentWillReceiveProps = (nextProps) => {
    if (nextProps.isGetFormData && !this.props.isFullMode && this.state.isEdit && !this.props.location.query.isEditFromCampaigns) {
      nextProps.getFormData(this.getFormData());
    } else if (nextProps.isGetFormData && this.props.isGetFormData !== nextProps.isGetFormData && (this.props.isFullMode || !this.state.isEdit || this.props.location.query.isEditFromCampaigns)) {
      this.saveHandler();
    }
    if (nextProps.Create.saveTemplateRes && !isEmpty(nextProps.Create.saveTemplateRes) && nextProps.Create.saveTemplateSuccess && !isEqual(nextProps.Create.saveTemplateRes, this.props.Create.saveTemplateRes)) {
      this.setState({loading: false});
      CapNotification.success({
        message: this.props.intl.formatMessage(messages.saveSuccess),
      });
    }
    if (!nextProps.Create.saveTemplateSuccess && nextProps.Create.saveTemplateSuccess !== undefined && nextProps.Create.saveTemplateErrorMessage && nextProps.Create.saveTemplateErrorMessage !== this.props.Create.saveTemplateErrorMessage) {
      this.setState({loading: false});
      this.showErrorMessage(this.props.intl.formatMessage(messages[nextProps.Create.saveTemplateErrorMessage] || messages.somethingWentWrong));
      this.props.onValidationFail();
    }
    if (!isEqual(nextProps.templateName, this.props.templateName)) {
      this.setState({templateName: nextProps.templateName});
    }
  }
  componentWillUnmount() {
    this.props.actions.clearContentImageStore();
  }
  onHover = (data) => {
    this.setState({hovered: data});
  }
  onHoverRemove = (data) => {
    this.setState({hovered: data});
  }
  onFormDataChange = (currentFormData) => {
    const templateData = cloneDeep(this.state.templateData);
    templateData[this.state.currentContentId].formData = cloneDeep(currentFormData);
    this.setState({templateData});
  }
  onContentChange = (evt) => {
    const templateData = cloneDeep(this.state.templateData);
    templateData[this.state.currentContentId].formData['content-value'] = evt.editor.getData();
    this.setState({templateData});
  }
  getEditorInstanse = (instance, id) => {
    window.CKEDITOR.on( 'instanceReady', ( event ) => {
      this.setState({editorInstanse: event.editor});
      event.editor.on( 'focus', () => {
        this.setState({editorInstanse: event.editor});
      });
    });
    //this.setState({editorInstanse: instance});
  }
  getMappedEvent = (id, event) => {
    const map = this.state.map;
    // if (!map[id] || !map[id][event]) {
    // }
    return map[id][event];
  }
  setFormValidity = (isFormValid) => {
    this.setState({isFormValid});
  }
  getCurrentWindow(e) {
    const response = {
      action: e.action,
      value: 'edit',
      direction: e.value,
    };
    parent.postMessage(JSON.stringify(response), '*');
  }
  getFormData(templateParams) {
    /**
     * This method would be called in two scenario
     *
     * Scenario 1:
     * ===========
     *  When a user selects a template. Edit container would be loaded with read only value. On click of done, This method would be invoked.
     *  In this scenario we depend up on props to parse this data
     *
     * Scenario 2:
     * ===========
     *  When a user creates a new richmedia template.
     *  In this scenario we depend up on state and function param to parse this data.
     *
     *  Considering the above scenarios, Parsing based on Props is considered as the default approach and fallback will be based on state.
     */
    const { templateData, Templates: templates, templateId: templateIdFromProp, templateName: templateNameFromProp} = this.props;
    const { mediaId, mediaList, templateId, templateName } = templateParams || {};
    const message = {
      mediaList: get(templateData, 'templateDetails.versions.base.mediaList', mediaList),
      media_id: get(templateData, 'templateDetails.versions.base.mediaId', mediaId),
      definition: {
        msgtype: "MPNEWS",
        msgcontent: "RICH_MEDIA_WECHAT",
      },
    };
    message.mediaList = message.mediaList.map((media) => ({...media, content: encodeURIComponent(media.content)}));
    const data = {
      data: message,
      accountId: get(templates, 'selectedWeChatAccount.id'),
      template_id: templateIdFromProp || templateId,
      Title: templateNameFromProp || templateName,
      OriginalId: get(templates, 'selectedWeChatAccount.sourceAccountIdentifier'),
      TopColor: "#000000",
      touser: "{{wechat_open_id}}",
      creative_template_id: templateIdFromProp || templateId,
    };
    const response = {
      action: "getFormData",
      value: data,
      validity: this.state.isFormValid,
      type: "WECHAT",
    };
    return response;
  }
  injectMessages(elem) {
    const temp = elem;
    if (temp.value && messages[temp.value]) {
      temp.value = this.props.intl.formatMessage(messages[temp.value]);
    }
    if (temp.label && messages[temp.label]) {
      temp.label = this.props.intl.formatMessage(messages[temp.label]);
    }
    if (temp.errorMessage && messages[temp.errorMessage]) {
      temp.errorMessage = this.props.intl.formatMessage(messages[temp.errorMessage]);
    }
    if (temp.placeholder && messages[temp.placeholder]) {
      temp.placeholder = this.props.intl.formatMessage(messages[temp.placeholder]);
    }
    // if (temp.value && messages[temp.value] && temp.metaType === 'label') {
    //   temp.value = this.props.intl.formatMessage(messages[temp.value]);
    // }
    if (temp.inductiveText && messages[temp.inductiveText]) {
      temp.inductiveText = this.props.intl.formatMessage(messages[temp.inductiveText]);
    }
    if (temp.options) {
      forEach(temp.options, (option, id) => {
        if (messages[option]) {
          temp.options[id] = this.props.intl.formatMessage(messages[option]);
        }
      });
    }
    return temp;
  }
  showErrorMessage = (errorMessage) => {
    CapNotification.error({
      message: errorMessage,
    });
  }
  checkFormFieldsCount = () => {
    const templateData = cloneDeep(this.state.templateData);
    let isLimitExceeded = false;
    forEach(templateData, (content) => {
      if (isEmpty(content)) {
        isLimitExceeded = true;
      }
      if (content.formData['title-value'].length > 64) {
        this.showErrorMessage(`${this.props.intl.formatMessage(messages.titleCharacterCount)} ${content.formData['title-value'].length - 64} characters`);
        isLimitExceeded = true;
      }
      if (content.formData['author-value'].length > 8) {
        this.showErrorMessage(`${this.props.intl.formatMessage(messages.authorCharacterCount)} ${content.formData['author-value'].length - 8} characters`);
        isLimitExceeded = true;
      }
      if (content.formData['cover-abstract-value'].length > 120) {
        this.showErrorMessage(`${this.props.intl.formatMessage(messages.coverAbstractCharacterCount)} ${content.formData['cover-abstract-value'].length - 120} characters`);
        isLimitExceeded = true;
      }
      return isLimitExceeded;
    });
    return isLimitExceeded;
  }
  // startLoading(ifEdit) {
  //   if (ifEdit) {
  //     this.setState({loading: true});
  //   }
  // }
  moveToTemplates() {
    const modalContent = {
      title: this.props.intl.formatMessage(messages.modalTitle),
      body: this.props.intl.formatMessage(messages.modalBody),
      type: 'confirm',
      id: 'template-back-confirm-modal',
      show: true,
    };
    this.setState({modalContent, showModal: true});
  }
  handleCancelModal = () => {
    this.setState({showModal: false});
  }
  showNext() {
    const response = {
      action: "showNext",
      value: true,
    };
    parent.postMessage(JSON.stringify(response), '*');
  }
  injectEvents = (schema) => {
    const temp = schema;
    if (temp.standalone) {
      temp.standalone.sections = this.injectSections(temp.standalone.sections);
    }
    if (temp.containers) {
      forEach(temp.containers, (container) => {
        let tempContainer = container;
        tempContainer = this.injectContainer(tempContainer);
        return tempContainer;
      });
    }
    return schema;
  }
  injectContainer = (container) => {
    const temp = container;
    if (temp.type === 'tabs') {
      temp.injectedEvents = {};
      forEach(temp.supportedEvents, (event) => {
        temp.injectedEvents[event] = this.getMappedEvent(temp.id, event);
      });
      forEach(temp.panes, (pane) => {
        const tempPane = pane;
        tempPane.sectionsHeaders = this.injectSections(tempPane.sectionsHeaders);
        tempPane.sections = this.injectSections(tempPane.sections);
      });
    }
    return temp;
  }
  injectSections = (sections) => {
    forEach(sections, (section) => {
      let temp = section;
      if (temp.type === 'col-label') {
        temp = this.injectColLabelSection(temp);
      } else if (section.type === 'multicols') {
        temp = this.injectMultiColSection(temp);
      } else if (section.type === 'parent') {
        temp = this.injectSections(temp.childSections);
      }
    });
    return sections;
  }
  injectColLabelSection = (section) => {
    forEach(section.inputFields, (inputField) => {
      let temp = inputField;
      temp.injectedEvents = {};
      forEach(inputField.supportedEvents, (event) => {
        temp.injectedEvents[event] = this.getMappedEvent(inputField.id, event);
      });
      temp = this.injectMessages(temp);
      return true;
    });
    forEach(section.actionFields, (actionField) => {
      let temp = actionField;
      temp.injectedEvents = {};
      forEach(actionField.supportedEvents, (event) => {
        temp.injectedEvents[event] = this.getMappedEvent(actionField.id, event);
      });
      temp = this.injectMessages(temp);
      return true;
    });
    return section;
  }
  injectMultiColSection = (section) => {
    forEach(section.inputFields, (inputField) => {
      forEach(inputField.cols, (col) => {
        let temp = col;
        temp.injectedEvents = {};
        forEach(col.supportedEvents, (event) => {
          temp.injectedEvents[event] = this.getMappedEvent(col.id, event);
        });
        temp = this.injectMessages(temp);
        return true;
      });
    });
    forEach(section.actionFields, (actionField) => {
      forEach(actionField.cols, (col) => {
        let temp = col;
        temp.injectedEvents = {};
        forEach(col.supportedEvents, (event) => {
          temp.injectedEvents[event] = this.getMappedEvent(col.id, event);
        });
        temp = this.injectMessages(temp);
        return true;
      });
    });
    return section;
  }
  templateNameHandler = (ev) => {
    const { value } = ev.target;
    this.setState({templateName: value});
  }
  cancelHandler = () => {
    const type = this.props.location.query.type;
    this.props.router.push({
      pathname: `/wechat`,
      query: type === 'embedded' ? {type: 'embedded'} : {},
    });
  }
  closeSlideBox = () => {
    this.setState({showPreview: false});
  }
  deducePostCommentsData = (data) => {
    let postCommentsData = {};
    if (data && data.toLowerCase() === 'anyone') {
      postCommentsData = {
        need_open_comment: 1,
        only_fans_can_comment: 0,
      };
    } else if (data && data.toLowerCase() === 'only followers') {
      postCommentsData = {
        need_open_comment: 1,
        only_fans_can_comment: 1,
      };
    } else {
      postCommentsData = {
        need_open_comment: 0,
        only_fans_can_comment: 0,
      };
    }
    return postCommentsData;
  }
  prepareMediaList = () => {
    const templateData = cloneDeep(this.state.templateData);
    const mediaList = [];
    forEach(templateData, (contentData) => {
      const postCommentsData = this.deducePostCommentsData(contentData.formData['post-comments-value']);
      const filteredContent = {
        title: contentData.formData['title-value'],
        author: contentData.formData['author-value'] ? contentData.formData['author-value'] : '',
        digest: contentData.formData['cover-abstract-value'] ? contentData.formData['cover-abstract-value'] : '',
        content: contentData.formData['content-value'],
        content_source_url: contentData.formData['source-link-value'],
        show_cover_pic: contentData.formData['show-cover-pic-value'] === true ? 1 : 0,
        need_open_comment: postCommentsData.need_open_comment,
        only_fans_can_comment: postCommentsData.only_fans_can_comment,
        thumb_media_id: contentData.mediaId,
        image_url: getCdnUrl({url: contentData.imageUrl, channelName: 'WECHAT'}),
      };
      mediaList.push(filteredContent);
    });
    return mediaList;
  }
  prepareWeChatRichmediaPreviewData = () => {
    const templateData = cloneDeep(this.state.templateData);
    const returnObj = [];
    forEach(templateData, (contentData, contentIndex) => {
      const id = parseInt(contentIndex, 10);
      if (id === 0) {
        returnObj.push(
          <div style={{ width: "100%", height: 116, position: "relative" }}>
            <CapRow useLegacy>
              <img alt="default" width="100%" height="110px" src={contentData.imageUrl} />
              <div style={{ position: "absolute", bottom: "5%", left: "5%" }}>{contentData.formData['title-value'] ? contentData.formData['title-value'] : ""}</div>
            </CapRow>
            {Object.keys(templateData).length === 1 ?
              <CapRow useLegacy style={{ height: 32 }}>
                {contentData.formData['cover-abstract-value'] ? contentData.formData['cover-abstract-value'] : ""}
              </CapRow>
              :
              ""
            }
          </div>
        );
      } else {
        returnObj.push(
          <CapRow style={{ "width": "100%", "height": 64, "border-bottom": "0.5px solid lightgrey" }}>
            <CapColumn style={{ padding: "5% 0% 0% 5%", float: "left" }}>
              {contentData.formData['title-value']}
            </CapColumn>
            <CapColumn style={{ float: "right" }}>
              <img alt="default" width="60px" height="60px" src={contentData.imageUrl} style={{ "padding-right": "10%", "float": "left" }}/>
            </CapColumn>
          </CapRow>
        );
      }
    });
    return returnObj;
  }
  previewHandler = () => {
    this.setState({showPreview: true});
  }
  saveHandler = () => {
    let isFormValid = this.validateFormFields();
    const { getFormData, onValidationFail } = this.props;
    if (isEmpty(this.state.templateName)) {
      this.showErrorMessage(this.props.intl.formatMessage(messages.emptyTemplateName));
      isFormValid = false;
    }
    if (isFormValid) {
      const mediaList = this.prepareMediaList();
      const saveObj = {};
      saveObj.name = this.state.templateName.trim();
      saveObj.appId = this.props.Templates.selectedWeChatAccount.configs.wechat_app_id;
      saveObj.appSecret = this.props.Templates.selectedWeChatAccount.configs.wechat_app_secret;
      saveObj.versions = {
        base: {
          OriginalId: this.props.Templates.selectedWeChatAccount.sourceAccountIdentifier,
          mediaList,
        },
        history: [],
      };
      saveObj.definition = {
        msgtype: "MPNEWS",
        msgcontent: "RICH_MEDIA_WECHAT",
      };
      const isEdit = this.state.isEdit;
      if (isEdit) {
        saveObj._id = this.props.templateId;
        saveObj.mediaId = this.props.mediaId;
        saveObj.type = "WECHAT";
      }
      this.setState({loading: true});
      this.props.actions.saveTemplate(saveObj, (response) => {
        // CapNotification.success({
        //   message: this.props.intl.formatMessage(messages.saveSuccess),
        // });
        const timeTaken = GA.timeTracker.stopTimer(isEdit ? TRACK_EDIT_WECHAT : TRACK_CREATE_WECHAT, {
          category: 'Creatives',
          action: isEdit ? TRACK_EDIT_WECHAT : TRACK_CREATE_WECHAT,
          label: 'RichMedia',
        });
        gtmPush('creativeDetails', {
          id: response.templateId._id || response.templateId,
          name: saveObj?.name,
          channel: `${WECHAT} Richmedia`,
          timeTaken,
          mode: isEdit ? EDIT : CREATE
        });
        if (getFormData) {
          getFormData(this.getFormData({
            mediaId: response.mediaId,
            templateId: response.templateId,
            mediaList,
            templateName: saveObj.name,
          }));
        }
      });
    } else {
      onValidationFail();
    }
  }
  uploadImage = (data, uploadId) => {
    if (data.type === "wrong file") {
      this.showErrorMessage(this.props.intl.formatMessage(messages.wrongFormatFile));
    } else {
      const wechatParams = {
        appId: this.props.Templates.selectedWeChatAccount.configs.wechat_app_id,
        appSecret: this.props.Templates.selectedWeChatAccount.configs.wechat_app_secret,
        source: 'wechat',
      };
      this.setState({loading: true});
      this.props.actions.uploadAsset(data.file, data.type, data.fileParams, null, wechatParams, this.state.currentContentId, uploadId);
    }
  }
  updateTotalContentBlocks = () => {
    this.setState({
      totalContentBlocks: this.state.totalContentBlocks + 1,
    }, () => {
      this.insertTemplateData();
    });
  }
  insertTemplateData = () => {
    const templateData = cloneDeep(this.state.templateData);
    templateData[this.state.totalContentBlocks - 1] = {
      formData: {},
      imageUrl: "",
      mediaId: "",
    };
    this.setState({templateData});
  }
  updateImageData = () => {
    const templateData = cloneDeep(this.state.templateData);
    if (this.props.ImageData && !isEmpty(this.props.ImageData[this.state.currentContentId]) && this.props.ImageData[this.state.currentContentId].metaInfo && this.props.ImageData[this.state.currentContentId].metaInfo.secure_file_path && this.props.ImageData[this.state.currentContentId].metaInfo.mediaId && templateData[this.state.currentContentId].imageUrl !== this.props.ImageData[this.state.currentContentId].metaInfo.secure_file_path) {
      templateData[this.state.currentContentId].imageUrl = this.props.ImageData[this.state.currentContentId].metaInfo.secure_file_path;
      templateData[this.state.currentContentId].mediaId = this.props.ImageData[this.state.currentContentId].metaInfo.mediaId;
      this.setState({templateData, loading: false});
    }
  }
  viewContent = (id, e) => {
    e.stopPropagation();
    this.setState({currentContentId: id});
  }
  deleteContent = (id, e) => {
    e.stopPropagation();
    const modalContent = {
      title: this.props.intl.formatMessage(messages.modalTitle),
      body: this.props.intl.formatMessage(messages.deleteContent),
      type: 'confirm',
      id: 'template-delete-confirm-modal',
      show: true,
      contentId: id,
    };
    this.setState({showModal: true, modalContent});
  }
  handleDelete = (modalContent) => {
    const templateData = cloneDeep(this.state.templateData);
    let totalContentBlocks = this.state.totalContentBlocks;
    let currentContentId = this.state.currentContentId;
    let index = 0;
    for (index = modalContent.contentId; index <= (totalContentBlocks - 2); index += 1) {
      templateData[index] = templateData[index + 1];
    }
    delete templateData[index];
    currentContentId = (totalContentBlocks - 1) === modalContent.contentId ? modalContent.contentId - 1 : modalContent.contentId;
    totalContentBlocks -= 1;
    this.setState({templateData, totalContentBlocks, currentContentId, showModal: false});
  }
  moveContentDownward = (id, e) => {
    e.stopPropagation();
    const templateData = cloneDeep(this.state.templateData);
    let currentContentId = this.state.currentContentId;
    const temp = cloneDeep(templateData[id]);
    templateData[id] = cloneDeep(templateData[id + 1]);
    templateData[id + 1] = temp;
    currentContentId = id + 1;
    this.setState({templateData, currentContentId});
  }
  moveContentUpward = (id, e) => {
    e.stopPropagation();
    const templateData = cloneDeep(this.state.templateData);
    let currentContentId = this.state.currentContentId;
    const temp = cloneDeep(templateData[id]);
    templateData[id] = cloneDeep(templateData[id - 1]);
    templateData[id - 1] = temp;
    currentContentId = id - 1;
    this.setState({templateData, currentContentId});
  }
  getCardActionBar = (contentBlocks, id) => (
    <div className="card-nav-container">
      <CapLink
        onClick={(e) => this.deleteContent(id, e)}
        title={
          <CapIcon
            size="s"
            type="close"
          />
        }
      />
      <CapLink
        {...(id > 0 && {onClick: (e) => this.moveContentUpward(id, e)})}
        className={id < 1 ? 'disabled-action' : ''}
        title={<CapIcon
          size="s"
          type="arrow-up"
          style={{
            paddingLeft: '2px',
            paddingBottom: '6px',
          }}
        />}
      />
      <CapLink
        {...(id < contentBlocks - 1 && {onClick: (e) => this.moveContentDownward(id, e)})}
        className={contentBlocks - 1 === id ? 'disabled-action' : ''}
        title={<CapIcon
          size="s"
          type="arrow-down"
          style={{
            paddingLeft: '2px',
          }}
        />}
      />
    </div>
    )
  returnCardLayout = () => {
    const templateData = cloneDeep(this.state.templateData);
    const { isIframe, totalContentBlocks } = this.state;
    const returnObj = [];
    forEach(templateData, (contentData, contentId) => {
      const id = parseInt(contentId, 10);
      const imageUrl = contentData.imageUrl || noImage;
      const { formData = {} } = contentData;
      if (id === 0) {
        returnObj[id] = (
          <div>
            <CapRow
              style={{ width: `${totalContentBlocks === 1 ? '260px' : '292px'}`,
                height: `${totalContentBlocks === 1 ? '252px' : '156px'}`,
                display: 'flex',
              }}
              className={id === this.state.currentContentId ? "richmedia-card richmedia-card-clicked" : "richmedia-card"}
            >
              <CapCard
                id={id}
                bordered={false}
                bodyStyle={{
                  padding: 0,
                  borderRadius: '4px',
                  width: '244px',
                  border: '1px solid #e8e8e8',
                }}
                onClick={(e) => this.viewContent(id, e)}
              >
                <div>
                  <div className={`custom-image ${totalContentBlocks !== 1 && "custom-image-border-bottom"}`}>
                    <img alt="" width="100%" height="136px" src={imageUrl} />
                    {totalContentBlocks !== 1 && <div className="name-container">
                      <CapHeading type="h4">{formData['title-value'] || this.props.intl.formatMessage(messages.title)}</CapHeading>
                    </div>}
                  </div>
                  {totalContentBlocks === 1 &&
                  <div className="custom-card">
                    <CapHeading type="h4" className="overflow-wrap-fields">{formData['title-value'] || this.props.intl.formatMessage(messages.title)}</CapHeading>
                    <CapLabel type="label9" className="overflow-wrap-fields">{formData['cover-abstract-value'] || this.props.intl.formatMessage(messages.coverAbstract)}</CapLabel>
                  </div>
                }
                </div>
              </CapCard>
              {!isIframe && totalContentBlocks !== 1 &&
                this.getCardActionBar(totalContentBlocks, id)}
            </CapRow>
          </div>
          );
      } else {
        returnObj[id] = (
          <div>
            <CapRow
              style={{ width: 296, height: 72 }} className={id === this.state.currentContentId ? "richmedia-card-rectangle richmedia-card-rectangle-clicked" : "richmedia-card-rectangle"}
              onClick={(e) => this.viewContent(id, e)}
            >
              <div className="richmedia-card-container">
                <CapColumn span={18} className="overflow-wrap-fields title" >
                  <CapLabel type="label9">{formData['title-value'] || this.props.intl.formatMessage(messages.title)}</CapLabel>
                </CapColumn>
                <CapColumn span={6} className="image">
                  <img alt="" width="40px" height="40px" src={imageUrl} />
                </CapColumn>
                {!isIframe && this.getCardActionBar(totalContentBlocks, id)}
              </div>
            </CapRow>
          </div>
          );
      }
    });
    return (
      <div>{returnObj}</div>
    );
  }
  isTitleRepeated = () => {
    const templateData = cloneDeep(this.state.templateData);
    const titleSet = new Set();
    let isRepeated = false;
    forEach(templateData, (content) => {
      const setSizeBefore = titleSet.size;
      titleSet.add((content.formData['title-value'] || '').toLowerCase());
      const setSizeAfter = titleSet.size;
      if (setSizeAfter === setSizeBefore) {
        isRepeated = true;
      }
    });
    return isRepeated;
  }
  isFormEmpty = () => {
    const templateData = cloneDeep(this.state.templateData);
    let isFormEmpty = false;
    forEach(templateData, (content) => {
      if (isEmpty(content.formData)) {
        isFormEmpty = true;
      }
    });
    return isFormEmpty;
  }
  validateFormFields = () => {
    let isValid = true;
    const currentContent = this.state.templateData[this.state.currentContentId];
    if (this.isFormEmpty()) {
      this.showErrorMessage(this.props.intl.formatMessage(messages.formEmpty));
      isValid = false;
      return isValid;
    }
    if (isEmpty(currentContent.formData['title-value'])) {
      this.showErrorMessage(this.props.intl.formatMessage(messages.titleEmpty));
      isValid = false;
      return isValid;
    }
    if (isEmpty(currentContent.imageUrl) || isEmpty(currentContent.mediaId)) {
      this.showErrorMessage(this.props.intl.formatMessage(messages.noImage));
      isValid = false;
      return isValid;
    }
    if (isEmpty(currentContent.formData['source-link-value'])) {
      this.showErrorMessage(this.props.intl.formatMessage(messages.sourceLinkEmpty));
      isValid = false;
      return isValid;
    }
    if (isEmpty(currentContent.formData['content-value'])) {
      this.showErrorMessage(this.props.intl.formatMessage(messages.contentEmpty));
      isValid = false;
      return isValid;
    }
    if (this.checkFormFieldsCount(currentContent.formData)) {
      isValid = false;
      return isValid;
    }
    if (this.isTitleRepeated()) {
      this.showErrorMessage(this.props.intl.formatMessage(messages.titleNameRepeated));
      isValid = false;
      return isValid;
    }
    if (!isEmpty(currentContent.formData['source-link-value'])) {
      isValid = currentContent.formData['source-link-value'].match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/g);
      if (!isValid) {
        this.showErrorMessage(this.props.intl.formatMessage(messages.wrongUrl));
        return isValid;
      }
    }
    return isValid;
  }
  menuOnClickEvent() {
    const isFormValid = this.validateFormFields();
    if (!isFormValid) {
      return false;
    }
    this.setState({
      currentContentId: this.state.totalContentBlocks,
    }, () => {
      this.updateTotalContentBlocks();
    });
    return true;
  }

  onChooseExistingTemplate = (template, e) => {
    e.stopPropagation();
    const content = get(template, 'versions.base.mediaList[0]', {});
    let postCommentsValue = 'No one';
    const templateData = cloneDeep(this.state.templateData);

    if (content.only_fans_can_comment && content.need_open_comment) {
      postCommentsValue = 'Only followers';
    } else if (content.need_open_comment) {
      postCommentsValue = 'Anyone';
    }

    templateData[this.state.currentContentId] = {
      formData: {
        'title-value': content.title,
        'author-value': content.author,
        'cover-abstract-value': content.digest,
        'content-value': content.content,
        'source-link-value': content.content_source_url,
        'post-comments-value': postCommentsValue,
        'show-cover-pic-value': content.show_cover_pic,
      },
      imageUrl: content.image_url,
      mediaId: content.thumb_media_id,
    };
    this.setState({ templateData });
    this.onCloseExistingTemplatesSlideBox();
  }

  getExistingTemplates = () => {
    const { searchText, sortBy, existingTemplatesPageNo, existingTemplatesPageLimit } = this.state;
    const { selectedWeChatAccount } = this.props.Templates;

    this.setState({showExistingTemplates: true});
    const queryParams = {
      name: searchText || '',
      sortBy,
      wecrmId: selectedWeChatAccount.configs.wecrm_app_id,
      wecrmToken: selectedWeChatAccount.configs.wecrm_token,
      originalId: selectedWeChatAccount.sourceAccountIdentifier,
      page: existingTemplatesPageNo,
      perPage: existingTemplatesPageLimit,
    };
    this.props.actions.getAllTemplates('wechat', queryParams);
  }

  searchTemplate = (data) => {
    this.setState({searchText: data}, () => {
      this.getExistingTemplates();
    });
  }

  onPaginationChange = () => {
    if (this.props.Create.pagination && this.state.scrollDebounce) {
      this.setState((prevState) => ({
        existingTemplatesPageNo: prevState.existingTemplatesPageNo + 1,
        scrollDebounce: false,
      }),
      () => {
        this.getExistingTemplates();
        setTimeout(() => {
          this.setState({ scrollDebounce: true });
        }, 500);
      });
    }
  }

  existingTemplatesContent = () => {
    const { getAllTemplatesInProgress, templates = [] } = this.props.Create;
    return (
      <CapSpin style={{textAlign: "center"}} spinning={getAllTemplatesInProgress}>
        <CapInput.Search
          className="search-text"
          style={{ width: '100%', marginBottom: CAP_SPACE_16 }}
          placeholder={this.props.intl.formatMessage(messages.searchText)}
          value={this.state.searchText}
          onChange={(e) => this.searchTemplate(e.target.value)}
          onClear={() => this.searchTemplate('')}
        />
        <Pagination style={{ height: 'calc(100vh - 150px)', overflowY: 'auto' }} onPageChange={templates.length && this.onPaginationChange}>
          { templates.map((template) => (
            <CapCard
              key={template._id}
              bordered={false}
              bodyStyle={{
                padding: 0,
                borderRadius: '4px',
                width: '276px',
                border: '16px solid #f4f5f7',
              }}
              onClick={(e) => this.onChooseExistingTemplate(template, e)}
              style={{ paddingBottom: CAP_SPACE_12 }}
              >
              <div>
                <div className="custom-image">
                  <img alt="" width="244px" height="136px" src={template.versions.base.mediaList[0].image_url} />
                </div>
                <div className="existing-template-title-card">
                  <CapHeading type="h5" className="overflow-wrap-fields">{template.name || this.props.intl.formatMessage(messages.title)}</CapHeading>
                </div>
              </div>
            </CapCard>
            ))
          }
        </Pagination>
      </CapSpin>
    );
  }

  onCloseExistingTemplatesSlideBox = () => {
    this.setState({
      showExistingTemplates: false,
      existingTemplatesPageNo: 1,
      existingTemplatesPageLimit: 25,
      searchText: '',
      pagination: true,
    });
  }

  updateContentData = () => {
    if (this.state.editorInstanse) {
      this.state.editorInstanse.insertHtml(`<img src='${this.props.ContentImageData.metaInfo.wechatUrl}' alt='Image'>`);
    }
    this.props.actions.clearContentImageStore();
    this.setState({loading: false});
  }
  returnContentMenu = () => {
    const addRichMediaMenu = (
      <>
        <div style={{width: '292px'}}><CapDivider /></div>
        <CapHeading type="h5" style={{marginBottom: '8px'}}>{this.props.intl.formatMessage(messages.addRichMediaContent)}</CapHeading>
        <CapButton type="dashed" onClick={this.getExistingTemplates} prefix={<CapIcon size="s" type="media" />} style={{backgroundColor: 'white', width: '142px', marginRight: CAP_SPACE_08, paddingLeft: CAP_SPACE_12}}>{this.props.intl.formatMessage(messages.existingMedia)}</CapButton>
        <CapButton type="dashed" onClick={this.menuOnClickEvent} prefix={<CapIcon size="s" type="add-media" />} style={{backgroundColor: 'white'}}>{this.props.intl.formatMessage(messages.newMedia)}</CapButton>
      </>
    );
    return addRichMediaMenu;
  }
  focusOutFromCkEditor = () => {
    this.setState({focusOut: true});
  }
  focusInFromCkeditor = () => {
    this.setState({focusOut: false});
  }
  returnCurrentSchema = () => {
    let schema = cloneDeep(this.state.richmediaSchema);
    if (this.state.isIframe) {
      const disabledFormSchema = cloneDeep(this.state.richmediaSchema);
      disabledFormSchema.standalone.sections[0].childSections[0].inputFields[0].cols[0].disabled = true;
      disabledFormSchema.standalone.sections[0].childSections[0].inputFields[1].cols[0].disabled = true;
      disabledFormSchema.standalone.sections[0].childSections[0].inputFields[2].cols[0].disabled = true;
      disabledFormSchema.standalone.sections[0].childSections[0].inputFields[3].cols[0].disabled = true;
      disabledFormSchema.standalone.sections[0].childSections[0].inputFields[4].cols[0].disabled = true;
      disabledFormSchema.standalone.sections[0].childSections[0].inputFields[5].cols[0].disabled = true;
      disabledFormSchema.standalone.sections[0].childSections[2].inputFields[0].cols[0].disabled = true;
      disabledFormSchema.standalone.sections[0].childSections[0].inputFields[4].cols[0].componentProps.disabled = true;
      disabledFormSchema.standalone.sections[0].childSections[1].childSections[0].childSections[0].inputFields[0].cols[1].disabled = true;
      disabledFormSchema.standalone.sections[0].childSections[2].inputFields[2].cols[0].disabled = true;
      if (this.state.editorInstanse) {
        this.state.editorInstanse.setReadOnly(true);
      }
      schema = this.injectEvents(disabledFormSchema);
      return schema;
    }
    if (this.state.editorInstanse && this.state.focusOut) {
      schema.standalone.sections[0].childSections[1].childSections[0].childSections[0].inputFields[0].cols[1].disabled = true;
    } else if (this.state.editorInstanse && !this.state.focusOut) {
      schema.standalone.sections[0].childSections[1].childSections[0].childSections[0].inputFields[0].cols[1].disabled = false;
    }
    schema = this.injectEvents(schema);
    return schema;
  }
  returnCurrentFormData = () => {
    const formData = this.state.templateData && !isEmpty(this.state.templateData[this.state.currentContentId]) && this.state.templateData[this.state.currentContentId].formData ? cloneDeep(this.state.templateData[this.state.currentContentId].formData) : {};
    return formData;
  }
  isLoading = () => {
    const isLoading = this.state.loading;
    if (!isLoading && this.props.setIsLoadingContent) {
      this.props.setIsLoadingContent(isLoading);
    }
    return isLoading;
  }
  render() {
    const cardLayout = this.returnCardLayout();
    const contentMenu = this.returnContentMenu();
    const schema = this.returnCurrentSchema();
    const formData = this.returnCurrentFormData();
    const { isIframe } = this.state;
    const { intl } = this.props;
    this.updateImageData();
    if (this.props.ContentImageData && this.props.ContentImageData.metaInfo && this.props.ContentImageData.metaInfo.wechatUrl) {
      this.updateContentData();
    }
    return (
      <div className="richmedia-container">
        <CapSpin spinning={this.isLoading()}>
          {this.state.showPreview && <WechatRichmediaTemplatePreview
            show={this.state.showPreview}
            closeSlideBox={this.closeSlideBox}
            header={this.state.templateName}
            width={50}
            showSlidebox
            const type={this.props.location && this.props.location.query.type ? this.props.location.query.type : ''}
            content={this.prepareMediaList()}
          />}
          <div>
            <div className={`wechat-container ${isIframe && "embedded-mode"}`}>
              <CapRow className="wechat-form-container">
                <CapColumn span={9}>
                  {cardLayout}
                  {!this.state.isIframe && contentMenu}
                </CapColumn>
                <CapColumn span={15}>
                  { !isIframe && <CapInput
                    label={this.props.intl.formatMessage(messages.nameOfTemplate)}
                    value={this.state.templateName}
                    onChange={this.templateNameHandler}
                    size="large"
                    style={{
                      marginBottom: '24px',
                    }}
                    className="richmedia-template-name"
                  />}
                  <FormBuilder
                    key={this.state.currentContentId}
                    schema={schema}
                    onChange={this.onFormDataChange}
                    parent={this}
                    formData={formData}
                    onFormValidityChange={this.setFormValidity}
                    location={this.props.location}
                    usingTabContainer={false}
                    router={this.props.router}
                    modal={this.state.modalContent}
                    showModal={this.state.showModal}
                    handleCancelModal={this.handleCancelModal}
                    iframeParent={parent}
                    handleDelete={this.handleDelete}
                  />
                </CapColumn>
              </CapRow>
            </div>
          </div>
          <CapSlideBox
            header={(
              <CapHeading type="h3">
                {intl.formatMessage(messages.existingMediaHeader)}
              </CapHeading>
            )}
            content={this.existingTemplatesContent()}
            show={this.state.showExistingTemplates}
            handleClose={this.onCloseExistingTemplatesSlideBox}
            size="size-s"
          />
        </CapSpin>
      </div>
    );
  }
}

Create.propTypes = {
  location: PropTypes.object,
  router: PropTypes.object,
  mode: PropTypes.string,
  templateData: PropTypes.object,
  totalContentBlocks: PropTypes.integer,
  templateName: PropTypes.string,
  templateId: PropTypes.string,
  mediaId: PropTypes.string,
  Templates: PropTypes.object,
  ImageData: PropTypes.object,
  actions: PropTypes.object,
  Create: PropTypes.object,
  intl: intlShape.isRequired,
  ContentImageData: PropTypes.object,
  isFullMode: PropTypes.bool,
  isGetFormData: PropTypes.bool,
  getFormData: PropTypes.func,
  onValidationFail: PropTypes.func,
  setIsLoadingContent: PropTypes.func,
};

const mapStateToProps = createStructuredSelector({
  Create: makeSelectCreate(),
  Templates: makeSelectTemplates(),
  ImageData: getAssetDetails(),
  ContentImageData: getContentAssetDetails(),
});

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(actions, dispatch),
  };
}

const withConnect = connect(mapStateToProps, mapDispatchToProps);
const withSaga = injectSaga({ key: 'weChatRichmediaCreate', saga: v2WechatRichmediaTemplatesCreateSagas });
const withReducer = injectReducer({ key: 'weChatRichmediaCreate', reducer: v2WechatRichmediaTemplatesCreateReducer });

export default compose(withSaga, withReducer, withConnect)(injectIntl(Create));
