/*
*
* WeChat
*
*/

import PropTypes from 'prop-types';

import React from 'react';
import { bindActionCreators } from 'redux';
import { intlShape, FormattedMessage } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import { CapRow, CapColumn, CapSpin, CapCustomCard, CapButton, CapHeading } from '@capillarytech/cap-ui-library';
import isEmpty from 'lodash/isEmpty';
import cloneDeep from 'lodash/cloneDeep';
import forEach from 'lodash/forEach';
import isEqual from 'lodash/isEqual';
import findIndex from 'lodash/findIndex';
import map from 'lodash/map';
import set from 'lodash/set';
import get from 'lodash/get';
import { makeSelectTemplates } from '../../Templates/selectors';
import { makeSelectMetaEntities, makeSelectFetchingSchema, setInjectedTags } from '../../Cap/selectors';
import makeSelectWeChat from './selectors';
import messages from './messages';
import * as actions from './actions';
import FormBuilder from '../../../v2Components/FormBuilder';
import {getMessageObject} from '../../../utils/messageUtils';
import * as templateActions from '../../Templates/actions';
import './_mapTemplates.scss';
import withCreatives from '../../../hoc/withCreatives';
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 injectReducer from '../../../utils/injectReducer';
import v2WechatMapTemplatesReducer from './reducer';
import * as globalActions from '../../Cap/actions';
const SELECT_TEMPLATE_MODE = "selectTemplate";
const MAP_TEMPLATE_MODE = "mapTemplateMode";
const URL = "URL";
const MINI_PROGRAM = "Mini-Program";
const { CapCustomCardList } = CapCustomCard;

export class MapTemplates extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.state = {
      schema: {},
      baseSchema: {},
      formData: {},
      activeMode: SELECT_TEMPLATE_MODE,
      map: {
        "discard-button": {
          discardValues: this.discardValues,
        },
        "cancel-button": {
          cancelTemplate: this.cancelTemplate,
        },
        "save-button": {
          saveFormData: this.saveFormData,
        },
        "wechat-template": {
          onSelect: this.selectWechatTemplate,
        },
        "wechat-accounts": {
          onSelect: this.selectWechatAccount,
        },
        "template-link": {
          onChange: this.setContent,
        },
        "is-internal-url": {
          onChange: this.internalUrlChecked,
        },
        "template-redirect-options-radio": {
          onChange: this.onRedirectOptionSelection,
        },

      },
      selectedTemplateTags: [],
      isEdit: false,
      editTemplateData: {},
      isFormValid: true,
      checkValidation: false,
      startValidation: false,
      injectedTags: {},
      isLoading: true,
      showModal: false,
      modalContent: {
        title: this.props.intl.formatMessage(messages.alertMessage),
        body: this.props.intl.formatMessage(messages.goBackTemporaryChangesLost),
        type: 'confirm',
        id: 'template-back-confirm-modal',
      },
    };

    this.saveFormData = this.saveFormData.bind(this);
    this.onFormDataChange = this.onFormDataChange.bind(this);
    this.setTemplateOptions = this.setTemplateOptions.bind(this);
    this.cancelTemplate = this.cancelTemplate.bind(this);
    this.setSelectedTemplateData = this.setSelectedTemplateData.bind(this);
    this.discardValues = this.discardValues.bind(this);
    this.internalUrlChecked = this.internalUrlChecked.bind(this);
    this.getTagsFromContent = this.getTagsFromContent.bind(this);
    this.onTagSelect = this.onTagSelect.bind(this);
    this.insertAtCursor = this.insertAtCursor.bind(this);
    this.setFormValidity = this.setFormValidity.bind(this);
    this.setContent = this.setContent.bind(this);
    this.prepareWeChatPreviewData = this.prepareWeChatPreviewData.bind(this);
    this.setEditData = this.setEditData.bind(this);
    this.maskTemplateUrl = this.maskTemplateUrl.bind(this);
    this.unMaskTemplateUrl = this.unMaskTemplateUrl.bind(this);
    this.resetState = this.resetState.bind(this);
    this.resetSchema = this.resetSchema.bind(this);
    this.getCurrentWindow = this.getCurrentWindow.bind(this);
    this.startLoading = this.startLoading.bind(this);
    this.startTemplateCreation = this.startTemplateCreation.bind(this);
    this.selectWechatTemplate = this.selectWechatTemplate.bind(this);
    this.removeActionButtons = this.removeActionButtons.bind(this);
    this.setWechatAccountOptions = this.setWechatAccountOptions.bind(this);
    this.selectWechatAccount = this.selectWechatAccount.bind(this);
    this.injectMessages = this.injectMessages.bind(this);
    this.hideSchemaElementsByModule = this.hideSchemaElementsByModule.bind(this);

    this.injectEvents = this.injectEvents.bind(this);
    this.injectSections = this.injectSections.bind(this);
    this.injectContainer = this.injectContainer.bind(this);
    this.injectParentSection = this.injectParentSection.bind(this);
    this.injectColLabelSection = this.injectColLabelSection.bind(this);
    this.injectMultiColSection = this.injectMultiColSection.bind(this);
    this.getMappedEvent = this.getMappedEvent.bind(this);
    this.showNext = this.showNext.bind(this);
    this.getFormData = this.getFormData.bind(this);
    this.updateSchema = false;
    this.fetchedWeCrmAccount = false;
    this.isAccountChange = false;
  }
  componentWillMount() {
    const query = {
      layout: 'WECHAT',
      type: 'LAYOUT',
      version: 'v2', //gets initial schema when v2 is specified
      context: this.props.location.query.type === 'embedded' ? this.props.location.query.module : 'default',
    };
    this.props.globalActions.fetchSchemaForEntity(query);
    this.props.actions.getWeCrmAccounts();
    if (get(this.props, 'params.id', false)) {
      this.props.actions.getTemplateDetails(this.props.params.id);
      this.setState({isEdit: true});
    }
    if (this.props.Templates.selectedWeChatAccount || (this.props.location.query.type === 'embedded' && this.props.location.query.module === 'loyalty')) {
      if (this.props.Templates.selectedWeChatAccount) {
        const params = {
          name: '',
          sortBy: 'Most Recent',
          wecrmId: this.props.Templates.selectedWeChatAccount.configs.wecrm_app_id,
          wecrmToken: this.props.Templates.selectedWeChatAccount.configs.wecrm_token,
          originalId: this.props.Templates.selectedWeChatAccount.sourceAccountIdentifier,
        };
        this.props.actions.getDefaultWeChatTemplates('wechat', params);
      } else {
        this.setWechatAccountOptions(this.props.WeChat.weCrmAccounts);
      }
    }
  }

  componentDidMount() {
    const query = {
      layout: 'WECHAT',
      type: 'LAYOUT',
      version: 'v2', //gets initial schema when v2 is specified
      context: this.props.location.query.type === 'embedded' ? this.props.location.query.module : 'default',
      embedded: this.props.location.query.type === 'embedded' ? this.props.location.query.type : 'full',
    };
    this.props.globalActions.fetchSchemaForEntity(query);
  }

  componentWillReceiveProps(nextProps) {
    const { location } = this.props;
    if (nextProps.isGetFormData && !this.props.isFullMode && this.state.isEdit) {
      this.props.getFormData(this.getFormData());
    } else if (nextProps.isGetFormData && this.props.isGetFormData !== nextProps.isGetFormData && (this.props.isFullMode || !this.state.isEdit)) {
      this.setState({startValidation: true});
    }
    if (!isEqual(nextProps.weChatMaptemplateStep, this.props.weChatMaptemplateStep)) {
      this.setState({ activeMode: nextProps.weChatMaptemplateStep === 0 ? SELECT_TEMPLATE_MODE : MAP_TEMPLATE_MODE });
    }
    if (nextProps.metaEntities && nextProps.metaEntities.layouts && nextProps.metaEntities.layouts.length > 0 && isEmpty(this.state.schema) && !nextProps.WeChat.getTemplateDetailsInProgress) {
      this.injectEvents(nextProps.metaEntities.layouts[0].definition);
      const query = {
        layout: 'WECHAT',
        type: 'TAG',
        version: 'v2', //gets initial schema when v2 is specified
        context: location.query.type === 'embedded' ? location.query.module : 'default',
        embedded: location.query.type === 'embedded' ? location.query.type : 'full',
      };
      if (this.props.getDefaultTags) { // handling dynamic tags in library mode, but handling static and synamic tags in email and sms.
        query.context = this.props.getDefaultTags;
      }
      this.props.globalActions.fetchSchemaForEntity(query);
    }
    if (nextProps.metaEntities && nextProps.metaEntities.layouts && nextProps.metaEntities.layouts.length > 0 && !isEmpty(this.state.schema)) {
      if (nextProps.WeChat.weChatDefaultTemplate && !isEqual(nextProps.WeChat.weChatDefaultTemplate, this.props.WeChat.weChatDefaultTemplate)) {
        this.injectEvents(this.state.schema);
        if (nextProps.location.query.type === 'embedded' && nextProps.location.query.module === 'loyalty') {
          this.setTemplateOptions(nextProps.WeChat.weChatTemplates);
        } else {
          this.setTemplateOptions(nextProps.WeChat.weChatDefaultTemplate);
        }
      }
      if ((location.query.type === 'embedded' && (location.query.module === 'loyalty' || location.query.module === 'outbound')) && !isEmpty(nextProps.WeChat.templateDetails) && !isEqual(this.props.WeChat.templateDetails, this.state.editTemplateData) && this.isAccountChange === false) {
        this.setState({editTemplateData: nextProps.WeChat.templateDetails}, () => {
          if ( !isEmpty(this.state.baseSchema)) {
            this.setEditData();
          } else {
            this.setState({baseSchema: cloneDeep(this.state.schema)}, () => {
              this.setEditData();
            });
          }
        });
      }
      // has to be un commented when wechat edit is implemented in embedded mode.
      // if (nextProps.location.query.type === "embedded" && nextProps.location.query.module === "library" && nextProps.templateData && nextProps.templateData.versions) { // Edit of already added message in library mode
      //   this.setState({editTemplateData: nextProps.templateData}, () => {
      //     this.setEditData();
      //   });
      // }
      if (nextProps.params.id && !isEqual(nextProps.params.id, this.props.params.id)) {
        this.setState({isEdit: true});
      }
      if (this.state.isEdit && isEmpty(this.state.editTemplateData) && !isEmpty(nextProps.WeChat.weChatTemplates)) {
        const templateIndex = findIndex(nextProps.WeChat.weChatTemplates, {_id: nextProps.params.id});
        if (templateIndex > -1) {
          this.setState({editTemplateData: nextProps.WeChat.weChatTemplates[templateIndex]}, () => {
            if (isEmpty(this.state.baseSchema)) {
              this.setState({ baseSchema: cloneDeep(this.state.schema)}, () => {
                this.setEditData();
              });
            } else {
              this.setEditData();
            }
          });
        }
      }
      //To do => Uncomment in loyalty mode
      // if (nextProps.location.query.type === 'embedded') {
      //   if (location.query.module !== 'loyalty') {
      //     this.removeActionButtons();
      //   }
      // }

      if (nextProps.WeChat.createResponse && nextProps.WeChat.createResponse.templateId) {
        // this.resetSchema();
        let message;
        if (this.state.isEdit) {
          message = getMessageObject('success', this.props.intl.formatMessage(messages.wechatEditSuccess), true);
        } else {
          message = getMessageObject('success', this.props.intl.formatMessage(messages.wechatCreateSuccess), true);
        }
        this.props.globalActions.addMessageToQueue(message);
        this.props.actions.clearCreateResponse();
      }
      if (nextProps.WeChat.createTemplateError && !isEqual(nextProps.WeChat.createTemplateError, this.props.WeChat.createTemplateError)) {
        const message = getMessageObject('error', this.props.intl.formatMessage(messages.somethingWentWrong), true);
        this.props.globalActions.addMessageToQueue(message);
      }

      // 
      // this.injectEvents(nextProps.metaEntities.layouts[0].definition);
      // const query = {
      //   layout: 'WECHAT',
      //   type: 'TAG',
      //   context: location.query.type === 'embedded' ? location.query.module : 'default',
      // };
      // this.props.globalActions.fetchSchemaForEntity(query);
      if (location.query.type === 'embedded') {
        this.showNext();
      }

      if (!this.fetchedWeCrmAccount && !isEmpty(this.props.WeChat.weCrmAccounts) && (location.query.type === 'embedded' && location.query.module === 'loyalty')) {
        this.injectEvents(this.state.schema);
        this.setWechatAccountOptions(nextProps.WeChat.weCrmAccounts);
        this.fetchedWeCrmAccount = true;
      }
      if (!isEmpty(nextProps.WeChat.selectedWeChatAccount) && !isEqual(this.props.WeChat.selectedWeChatAccount, nextProps.WeChat.selectedWeChatAccount) && (location.query.type === 'embedded')) {
        const params = {
          name: '',
          sortBy: 'Most Recent',
          wecrmId: nextProps.WeChat.selectedWeChatAccount.configs.wecrm_app_id,
          wecrmToken: nextProps.WeChat.selectedWeChatAccount.configs.wecrm_token,
          originalId: nextProps.WeChat.selectedWeChatAccount.sourceAccountIdentifier,
        };
        this.props.actions.getDefaultWeChatTemplates('wechat', params);
      }

      if (isEmpty(nextProps.WeChat.selectedWeChatAccount) && (location.query.type === 'embedded')) {
        let selectedAccount = {};
        forEach(nextProps.WeChat.weCrmAccounts, (account) => {
          if (account.configs && account.configs.is_wecrm_enabled) {
            if (account.sourceAccountIdentifier === location.query.source_account_id) {
              selectedAccount = account;
            }
          }
        });
        if (!isEmpty(selectedAccount)) {
          this.props.actions.setWeChatAccount(selectedAccount);
        }
      }

      // if (location.query.type.type === 'embedded' && location.query.module === 'loyalty' && this.state.formData['wechat-template'] !== '') {
      // }
      if (!nextProps.WeChat.fetchingDefaultTemplates && nextProps.location.query.module === 'outbound' && nextProps.params.id !== undefined) {
        this.setState({ isLoading: false});
      }
      if (((!nextProps.WeChat.fetchingDefaultTemplates && !isEqual(nextProps.WeChat.fetchingDefaultTemplates, this.props.WeChat.fetchingDefaultTemplates) && nextProps.location.query.module !== 'loyalty') || (nextProps.location.query.module === 'loyalty'))) {
        this.setState({ isLoading: false});
      }

      if (nextProps.WeChat.fetchingDefaultTemplates && nextProps.location.query.module === 'loyalty' && nextProps.params.id === undefined) {
        this.setState({ isLoading: true});
      }
    }
  }

  componentWillUnmount() {
    this.resetState();
  }

  onFormDataChange(formData) {
    let selectedWechatTemplateIndex = -1;
    let selectedTemplate = {};
    let selectedTemplateData = {};
    if (this.props.location.query.type === 'embedded' && (this.props.location.query.module === 'loyalty')) {
      selectedTemplateData = this.state.editTemplateData;
      if (get(this.props, 'params.id', false) && isEmpty(this.props.WeChat.weChatTemplates) && isEqual(formData['wechat-template'], this.state.formData['wechat-template'])) {
        selectedTemplate = {
          template_id: this.props.WeChat.templateDetails.versions.base.template_id,
          title: this.props.WeChat.templateDetails.versions.base.Title,
          content: this.props.WeChat.templateDetails.versions.base.content,
        };
        selectedTemplateData = this.props.WeChat.templateDetails;
      } else {
        const editTemplateData = this.state.editTemplateData;
        forEach(this.props.WeChat.weChatTemplates, (template) => {
          if (template.versions.base.template_id === formData['wechat-template'] && formData['wechat-template'] !== get(editTemplateData, 'versions.base.template_id') ) { // not changing if already selected templates comes
            selectedTemplate = {
              template_id: template.versions.base.template_id,
              title: template.versions.base.Title,
              content: template.versions.base.content,
            };
            this.isAccountChange = false;
            selectedTemplateData = template;
          }
        });
      }
    } else if (this.state.isEdit && this.state.editTemplateData.versions) {
      selectedTemplateData = cloneDeep(this.state.editTemplateData);
      selectedTemplate = {
        template_id: selectedTemplateData.versions.base.template_id,
        title: selectedTemplateData.versions.base.Title,
        content: selectedTemplateData.versions.base.content,
      };
    } else if (!this.state.isEdit) {
      selectedWechatTemplateIndex = findIndex(this.props.WeChat.weChatDefaultTemplate, {template_id: formData['wechat-template']});
      selectedTemplate = this.props.WeChat.weChatDefaultTemplate[selectedWechatTemplateIndex];
    }

    if (!isEqual(formData['wechat-template'], this.state.formData['wechat-template'])) {
      this.updateSchema = true;
    }
    if (this.isAccountChange) {
      selectedTemplateData = {};
    }
    const newState = {formData};
    if (!isEqual(this.state.editTemplateData, selectedTemplateData)) {
      newState.editTemplateData = selectedTemplateData;
    }
    if (!isEqual(this.state.formData, formData)) {
      this.setState(newState, () => {
        if (!isEmpty(this.state.editTemplateData) && this.props.location.query.type === 'embedded' && this.props.location.query.module === 'loyalty') {
          this.setEditData();
        }
        if (this.props.WeChat.selectedWeChatAccount && !isEqual(this.props.WeChat.selectedWeChatAccount.name, formData['wechat-accounts']) && this.props.location.query.type === 'embedded' && this.props.location.query.module === 'loyalty') {
          let selectedAccount = {};
          forEach(this.props.WeChat.weCrmAccounts, (account) => {
            if (account.configs && account.configs.is_wecrm_enabled) {
              if (account.name === formData['wechat-accounts']) {
                selectedAccount = account;
              }
            }
          });
          this.props.actions.setWeChatAccount(selectedAccount);
          this.setSelectedTemplateData({});
        }
        if ((selectedWechatTemplateIndex !== -1 || this.state.isEdit) && !isEmpty(selectedTemplate)) {
          let templateData = {};
          if (this.state.isEdit && !isEmpty(this.state.editTemplateData)) {
            templateData = {
              template_id: this.state.editTemplateData.versions.base.template_id,
              title: this.state.editTemplateData.versions.base.Title,
              content: this.state.editTemplateData.versions.base.content,
            };
            if (this.props.location.query.type === 'embedded' && this.props.location.query.module === 'loyalty') {
              if (isEqual(this.props.WeChat.selectedWeChatAccount.name, formData['wechat-accounts'])) {
                this.setSelectedTemplateData(selectedTemplate);
              }
            } else {
              const templateTags = this.getTagsFromContent(templateData.content);
              this.prepareWeChatPreviewData(templateData, templateTags);
            }
          } else if (!this.updateSchema) {
            const templateTags = this.getTagsFromContent(selectedTemplate.content);
            this.prepareWeChatPreviewData(selectedTemplate, templateTags);
          } else {
            this.updateSchema = false;
            this.setSelectedTemplateData(selectedTemplate);
          }
        } else {
          let selectedAccount = {};
          forEach(this.props.WeChat.weCrmAccounts, (account) => {
            if (account.configs && account.configs.is_wecrm_enabled) {
              if (account.name === formData['wechat-accounts']) {
                selectedAccount = account;
              }
            }
          });
          this.props.actions.setWeChatAccount(selectedAccount);
        }
      });
    }
  }

  onTagSelect(data, currentTab, value) {
    const editorId = (value.id).replace('tagList', 'template');
    this.insertAtCursor(document.getElementById(editorId), `{{${data}}}`, currentTab);
    document.getElementById(editorId).focus();
  }

  getFormData(formData) {
    let { editTemplateData} = this.state;
    const selectedWeChatAccount = (!isEmpty(this.props.Templates.selectedWeChatAccount) ? this.props.Templates.selectedWeChatAccount : this.props.WeChat.selectedWeChatAccount);
    if (isEmpty(editTemplateData)) {
      editTemplateData = formData;
    }
    const data = {
      accountId: selectedWeChatAccount.id,
      template_id: editTemplateData.versions.base.template_id,
      Title: editTemplateData.versions.base.Title,
      Tag: [],
      TopColor: "#000000",
      data: {},
      BrandId: (selectedWeChatAccount.configs.brand_id ? selectedWeChatAccount.configs.brand_id : ''),
      OriginalId: selectedWeChatAccount.sourceAccountIdentifier,
      content: encodeURIComponent(editTemplateData.versions.base.content),
      isInternalUrl: this.state.formData['is-internal-url'],
      creative_template_id: editTemplateData._id,
      touser: "{{wechat_open_id}}",
    };
    if (this.state.formData['template-redirect-options-radio'] === MINI_PROGRAM) {
      const miniprogram = {};
      miniprogram.appid = this.state.formData['template-mini-program-id'] || '';
      miniprogram.pagepath = this.state.formData['template-mini-program-page-path'] || '';
      data.miniprogram = miniprogram;
      data.url = "notset";
    } else if (this.state.formData['template-redirect-options-radio'] === URL) {
      data.url = this.state.formData['is-internal-url'] ? this.maskTemplateUrl(this.state.formData['template-link']) : this.state.formData['template-link'];
    }
    forEach(this.state.selectedTemplateTags, (templateTag) => {
      const tagName = templateTag.substr(0, templateTag.indexOf('.'));
      let newTagname = tagName;
      data.Tag.push(tagName);
      if (tagName.match(/first/i)) {
        newTagname = "Header";
      }
      if (tagName.match(/remark/i)) {
        newTagname = "Footer";
      }
      data.data[tagName] = {};
      data.data[tagName] = {
        value: this.state.formData[`template-${newTagname}`],
        color: "#00000",
      };
    });
    const response = {
      action: "getFormData",
      value: data,
      validity: this.state.isFormValid,
      type: "WECHAT",
    };
    return response;
  }

  getCurrentWindow(e) {
    const response = {
      action: e.action,
      value: 'edit',
      direction: e.value,
    };
    parent.postMessage(JSON.stringify(response), '*');
  }

  getTagsFromContent(string) {
    const foundTags = [];
    const rxp = /{{([^}]+)}}/g;
    let curMatch;
    /* eslint-disable */
    while ( curMatch = rxp.exec( string ) ) {
      foundTags.push( curMatch[1] );
    }
    return foundTags;
  }
  
  startLoading(ifEdit) {
    
    if (ifEdit) {
      this.setState({loading: true});
    }
  }
  
  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]);
    }
    return temp;
  }
  
  setSelectedTemplateData(weChatData) {
    const { intl } = this.props;
    let schema = cloneDeep(this.state.baseSchema);
    // schema.standalone.sections[0].childSections[1].childSections[0].childSections[1].inputFields = [];
    if (isEmpty(weChatData)) {
      // schema.standalone.sections[0].childSections[1].childSections[0].childSections[1].inputFields = [];
      const formData=cloneDeep(this.state.formData);
      formData['wechat-template']="";
      this.setState({schema,formData});
      this.isAccountChange = true;
      return;
    }
    
    const {map} = cloneDeep(this.state);
    const templateTags = this.getTagsFromContent(weChatData.content);
    const formData = cloneDeep(this.state.formData);
    formData['wechat-template'] = weChatData.template_id;
    forEach(templateTags, (tag) => {
      const tagTitle = tag.substr(0, tag.indexOf('.'));
      let title = tagTitle;
      
      if (tagTitle.match(/first/i)) {
        title = "Header";
      }
      if (tagTitle.match(/remark/i)) {
        title = "Footer";
      }

      const colsData = [];
      if(this.props.location.query.type !== 'embedded') {
        colsData.push({
          type: "multicols",
          inputFields: [
            {
              rowClassName: 'tag-container',
              cols: [{
                width: 23,
                id: `tagList-${title}`,
                label: "Tags",
                type: "tag-list",  //Resembles component to be used
                metaType: "List",
                datatype: "select",
                required: true,
                fluid: true,
                onlyDisplay: true,
                styling: "semantic",
                order: 1,
                customComponent: true,
                supportedEvents: [
                  'onTagSelect',
                ],
                style: {marginBottom: 'unset', height: '24px', },
                className: 'add-label',
              }],
            }
          ],
        });
      }
      
      map[`tagList-${title}`] = {
        onTagSelect: this.onTagSelect,
      };
      
      colsData.push({
        type: "multicols",
        inputFields: [
          {
            cols: [
              {
                id: `template-${title}`,
                placeholder: `${title}`,
                type: "input",  //Resembles component to be used
                metaType: "text",
                datatype: "string",
                errorMessage: "Invalid content",
                required: true,
                fluid: true,
                disabled: (this.props.location.query.type === 'embedded' && this.state.isEdit),
                label: title,
                styling: "semantic",
                order: 1,
                width: 23,
                // offSet: 2,
                customComponent: false,
                standalone: true,
                supportedEvents: [
                  'onChange',
                ],
                size: "large",
              },
            ],
          }
        ],
      });
      
      map[`template-${title}`] = {
        onChange: this.setContent,
      };
      
      schema.standalone.sections[0].childSections[1].childSections[0].childSections.push(...colsData);
    });

    schema.standalone.sections[0].childSections[1].childSections[0].childSections.push({
      type: "col-label",
      inputFields: [{
        id: 'redirect-options-heading',
        type: "label",
        metaType: "text",
        datatype: "string",
        value: intl.formatMessage(messages.redirectOptionsHeadingValue),
        required: true,
        fluid: true,
        headingType: "h4",
        disabled: (this.props.location.query.type === 'embedded' && this.state.isEdit),
        styling: "semantic",
        style: {
          marginTop: 24
        },
        order: 1,
        width: 23,
        customComponent: false,
        standalone: true,
      },
    ]},{
      type: "multicols",
        inputFields: [
          {
          rowClassName: 'redirect-options-row',
          cols: [
            {
              id: 'template-redirect-options-radio',
              type: "radioGroup",
              metaType: "text",
              datatype: "string",
              options: [
                {
                  value: URL,
                  label: intl.formatMessage(messages.redirectOptionURL)
                }, 
                {
                  value: MINI_PROGRAM,
                  label: intl.formatMessage(messages.redirectOptionMiniProgram)
                }
              ],
              errorMessage: intl.formatMessage(messages.redirectionOptionError),
              required: true,
              fluid: true,
              disabled: (this.props.location.query.type === 'embedded' && this.state.isEdit),
              style: {
                marginTop: 8,
                display: 'grid',
              },
              styling: "semantic",
              order: 1,
              width: 23,
              customComponent: false,
              standalone: true,
              supportedEvents: [
                'onChange'
              ],
            },
          ],
        },
      ]});
    
      if (this.state.isEdit) {
        forEach(this.state.editTemplateData.versions.base.Tag, (tag) => {
          let tagName = tag;
          if (tag.match(/first/i)) {
            tagName = "Header";
          }
          if (tag.match(/remark/i)) {
            tagName = "Footer";
          }
          formData[`template-${tagName}`] = this.state.editTemplateData.versions.base.data[tag].value;
        });
        if (this.state.editTemplateData.versions.base.url && this.state.editTemplateData.versions.base.url !== "notset") {
          formData['template-redirect-options-radio'] = URL;
          formData[`template-link`] = this.state.editTemplateData.versions.base.isInternalUrl ? this.unMaskTemplateUrl(this.state.editTemplateData.versions.base.url) : this.state.editTemplateData.versions.base.url;
          schema.standalone.sections[0].childSections[1].childSections[0].childSections.push(this.getURLSchema());
        }
        if (this.state.editTemplateData.versions.base.isInternalUrl) {
          formData['is-internal-url'] = this.state.editTemplateData.versions.base.isInternalUrl;
        }
        if (this.state.editTemplateData.versions.base.miniprogram && this.state.editTemplateData.versions.base.miniprogram.appid && this.state.editTemplateData.versions.base.miniprogram.pagepath) {
          formData['template-redirect-options-radio'] = MINI_PROGRAM;
          formData['template-mini-program-id'] = this.state.editTemplateData.versions.base.miniprogram.appid;
          formData['template-mini-program-page-path'] = this.state.editTemplateData.versions.base.miniprogram.pagepath;
          schema.standalone.sections[0].childSections[1].childSections[0].childSections.push(this.getMiniProgramSchema());
        }
        // schema.standalone.sections[0].childSections[1].childSections[1].inputFields[0].cols[0].content = weChatData.content;
      } else {
        // schema.standalone.sections[0].childSections[1].childSections[1].inputFields[0].cols[0].content = weChatData.content;
      }
      // schema.standalone.sections[0].childSections[1].childSections[1].inputFields[0].cols[0].content = weChatData.content;
      
      this.setState({schema, map, selectedTemplateTags: templateTags, formData, activeMode: MAP_TEMPLATE_MODE, weChatData}, () => {
        
        this.prepareWeChatPreviewData(weChatData, templateTags);
        this.props.onWeChatMaptemplateStepChange(1);
      });
    }
    
    resetState() {
      this.setState({
        formData: {},
        schema: {},
        baseSchema: {},
        selectedTemplateTags: [],
        isEdit: false,
        editTemplateData: {},
        isFormValid: true,
        checkValidation: false,
        startValidation: false,
        injectedTags: {},
        isLoading: true,
      });
    }
    
    resetSchema() {
      const formData = cloneDeep(this.state.formData);
      if (this.state.isEdit) {
        const templateData = {
          template_id: this.state.editTemplateData.versions.base.template_id,
          title: this.state.editTemplateData.versions.base.Title,
          content: this.state.editTemplateData.versions.base.content,
        };
        this.setSelectedTemplateData(templateData);
      } else {
        this.setState({ schema: this.state.baseSchema, formData: {'wechat-template': "" }});
        // this.setState({ schema: this.props.metaEntities.layouts[0].definition });
      }
    }
    
    setWechatAccountOptions(weCrmAccounts) {
      
      const schema = cloneDeep(this.state.schema);
      const formData = cloneDeep(this.state.formData);
      if (!isEmpty(weCrmAccounts)) {
        forEach(weCrmAccounts, (account) => {
          if (account.configs && account.configs.is_wecrm_enabled) {
            const options = schema?.standalone?.sections[0]?.childSections[1]?.childSections[0]?.childSections[0]?.inputFields[0]?.options;
            options && options.push({
              key: account.uuid,
              label: account.name,
              value: account.name,
            });
          }
          
          if (this.props.WeChat.templateDetails && this.props.WeChat.templateDetails.versions.base.OriginalId === account.sourceAccountIdentifier) {
            formData['wechat-accounts'] = account.name;
            this.props.actions.setWeChatAccount(account);
          }
        });
        this.setState({schema, formData, baseSchema: schema});
      }
    }
    
    selectWechatAccount(value, option) {
      // 
      // templateActions.setWeChatAccount();
    }
    
    setTemplateOptions(weChatData) {
      
      //const {schema, baseSchema} = this.state;
      const schema = cloneDeep(this.state.schema);
      const baseSchema = cloneDeep(this.state.schema);
      const baseSchemaTemplateOptionEmpty = (!isEmpty(baseSchema) && isEmpty(get(baseSchema, 'standalone.sections[0].childSections[1].childSections[0].childSections[0].inputFields[1].options', [])));
      schema.standalone.sections[0].childSections[1].childSections[0].childSections[0].inputFields[1].options = [];
      if (!isEmpty(baseSchema)) {
        baseSchema.standalone.sections[0].childSections[1].childSections[0].childSections[0].inputFields[1].options = [];
        
      } 
      forEach(weChatData, (template) => {
        schema.standalone.sections[0].childSections[1].childSections[0].childSections[0].inputFields[1].options.push({
          key: (template.versions) ? template.versions.base.template_id : template.template_id,
          label: (template.versions) ? template.name : `${template.title} : ${template.template_id}`,
          value: (template.versions) ? template.versions.base.template_id : template.template_id,
        });
        if ((!isEmpty(baseSchema) && this.props.location.query.module === 'loyalty') || (baseSchemaTemplateOptionEmpty)) {
          baseSchema.standalone.sections[0].childSections[1].childSections[0].childSections[0].inputFields[1].options.push({
            key: (template.versions) ? template.versions.base.template_id : template.template_id,
            label: (template.versions) ? template.name : `${template.title} : ${template.template_id}`,
            value: (template.versions) ? template.versions.base.template_id : template.template_id,
          });
        }
      });
      this.setState({schema, baseSchema: cloneDeep(baseSchema)}, () => {
        
        if (isEmpty(this.state.baseSchema)) {
          this.setState({baseSchema: cloneDeep(schema)});
        }
      });
    }
    
    setFormValidity(isFormValid) {
      this.setState({
        isFormValid,
        startValidation: false,
      });
      if(!isFormValid) {
        this.props.onValidationFail();
      }
    }
    
    setContent(content) {
      
    }
    
    setEditData() {
      
      const formData = cloneDeep(this.state.formData);
      const baseSchema = cloneDeep(this.state.baseSchema);
      if (isEmpty(baseSchema)) {
        return;
      }
      formData['wechat-template'] = this.state.editTemplateData.versions.base.template_id;
      if (this.props.location.query.module !== 'loyalty' && !isEmpty(baseSchema)) {
        baseSchema.standalone.sections[0].childSections[1].childSections[0].childSections[0].inputFields[1].options = [];
        baseSchema.standalone.sections[0].childSections[1].childSections[0].childSections[0].inputFields[1].options.push({
          key: this.state.editTemplateData.versions.base.template_id,
          label: this.state.editTemplateData.name,
          value: this.state.editTemplateData.versions.base.template_id,
        });
      }
      const templateData = {
        'template_id': this.state.editTemplateData.versions.base.template_id,
        'title': this.state.editTemplateData.versions.base.Title,
        'content': this.state.editTemplateData.versions.base.content,
      };
      
      this.setState({baseSchema, formData, isEdit: true}, () => {
        this.setSelectedTemplateData(templateData);
      })
    }
    
    maskTemplateUrl(url) {
      const selectedWeChatAccount = (!isEmpty(this.props.Templates.selectedWeChatAccount) ? this.props.Templates.selectedWeChatAccount : this.props.WeChat.selectedWeChatAccount);
      
      
      const appid = selectedWeChatAccount.configs.wecrm_app_id;
      const domain = selectedWeChatAccount.configs.domain;
      const maskedUrl = `${domain}/web?appid=${appid}&redirect_uri=${escape(url)}&response_type=code&scope=snsapi_base&state=STATE`;
      
      return maskedUrl;
    }
    
    unMaskTemplateUrl(url) {
      let startIndex, endIndex;
      startIndex = url.indexOf('&redirect_uri=') + 14;
      endIndex = url.indexOf('&response_type');
      return decodeURIComponent(url.substring(startIndex, endIndex));
    }
    
    getMappedEvent(id, event) {
      return (this.state.map[id] && this.state.map[id][event] ?  this.state.map[id][event] : () => {});
    }
    
    handleOnTagsContextChange = (data) => {
      
      const query = {
        layout: 'WECHAT',
        type: 'TAG',
        context: (data || '').toLowerCase() === 'all' ? 'default' : (data || '').toLowerCase(),
        embedded: this.props.location.query.type === 'embedded' ? this.props.location.query.type : 'full',
      };
      this.props.globalActions.fetchSchemaForEntity(query);
    }
    
    startTemplateCreation(data) {
      
    }
    
    selectWechatTemplate() {
      
    }
    
    removeActionButtons() {
      const schema = cloneDeep(this.state.schema);
      const headerCols = schema.standalone.sections[0].childSections[0].inputFields[0].cols;
      forEach(headerCols, (col) => {
        col.colStyle.display = 'none';
      });
      this.setState({schema});
    }
    
    showNext() {
      const response = {
        action: "showNext",
        value: true,
      };
      parent.postMessage(JSON.stringify(response), '*');
    }
    
    insertAtCursor(field, myValue, currentTab) {
      //IE support
      const myField = field;
      if (document.selection) {
        myField.focus();
        const sel = document.selection.createRange();
        sel.text = myValue;
      } else if (myField.selectionStart || myField.selectionStart === '0') { //MOZILLA and others
        const startPos = myField.selectionStart;
        const endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos)
        + myValue
        + myField.value.substring(endPos, myField.value.length);
        myField.selectionStart = startPos + myValue.length;
        myField.selectionEnd = startPos + myValue.length;
      } else {
        myField.value += myValue;
      }
      const formData = cloneDeep(this.state.formData);
      formData[field.id] = myField.value;
      this.onFormDataChange(formData);
    }
    
    internalUrlChecked() {
      
    }

    getURLSchema = () => ({
      type: "multicols",
      inputFields: [{
        rowClassName: 'link-row',
        cols: [
          {
            id: 'template-link',
            placeholder: this.props.intl.formatMessage(messages.templateLinkLabel),
            label: this.props.intl.formatMessage(messages.templateLinkLabel),
            type: "input",
            metaType: "text",
            datatype: "string",
            errorMessage: this.props.intl.formatMessage(messages.templateLinkError),
            required: true,
            fluid: true,
            disabled: (this.props.location.query.type === 'embedded' && this.state.isEdit),
            style: {
              fontSize: '14px',
              fontStyle: 'normal',
            },
            styling: "semantic",
            order: 1,
            width: 23,
            customComponent: false,
            standalone: true,
            supportedEvents: [
              'onChange',
            ],
            size: "large",
          },
        ],
      },
      {
        cols: [
          {
            id: "is-internal-url",
            label: this.props.intl.formatMessage(messages.internalUrlLabel),
            standalone: true,
            labelStyle: {
              backgroundColor: "white",
            },
            colStyle: {
              marginBottom: '24px',
            },
            style: {
              textAlign: 'left',
              color: '#262626',
              fontFamily: 'Open-Sans',
              lineHeight: '24px',
              fontSize: '14px',
              padding: '.5833em .833em',
              marginBottom: '24px',
              paddingLeft: '0',
            },
            type: "checkbox",
            disabled: (this.props.location.query.type === 'embedded' && this.state.isEdit),
            metaType: "text",
            datatype: "boolean",
            required: true,
            fluid: true,
            styling: "semantic",
            order: 1,
            width: 10,
            onlyDisplay: false,
            customComponent: false,
            supportedEvents: [
              'onChange',
            ],
          },
        ],
      }],
    })

    getMiniProgramSchema = () => ({
      type: "multicols",
      inputFields: [{
        rowClassName: 'mini-program-row',
        cols: [
          {
            id: 'template-mini-program-id',
            placeholder: this.props.intl.formatMessage(messages.miniWeChatPlaceholder),
            inductiveText: this.props.intl.formatMessage(messages.miniWechatIdInductive),
            label:  this.props.intl.formatMessage(messages.miniWechatIdLabel),
            type: "input",
            metaType: "text",
            datatype: "string",
            errorMessage: this.props.intl.formatMessage(messages.miniWechatIdError),
            required: true,
            fluid: true,
            disabled: (this.props.location.query.type === 'embedded' && this.state.isEdit),
            styling: "semantic",
            order: 1,
            width: 23,
            customComponent: false,
            standalone: true,
          },
        ],
      },
      {
        rowClassName: 'mini-program-row',
        cols: [
          {
            id: 'template-mini-program-page-path',
            placeholder: this.props.intl.formatMessage(messages.pagePathPlaceholder),
            inductiveText: this.props.intl.formatMessage(messages.pagePathInductive),
            label: this.props.intl.formatMessage(messages.pagePathLabel),
            type: "input",
            metaType: "text",
            datatype: "string",
            errorMessage: this.props.intl.formatMessage(messages.pagePathError),
            required: true,
            fluid: true,
            disabled: (this.props.location.query.type === 'embedded' && this.state.isEdit),
            styling: "semantic",
            order: 1,
            width: 23,
            customComponent: false,
            standalone: true,
          }
        ],
      }],
    })
    
    deletePreviousRedirectOptionSelection = () => {
      let schema = cloneDeep(this.state.schema);
      const formChildSections = get(schema, 'standalone.sections[0].childSections[1].childSections[0].childSections', []);
      const lastChildSection = formChildSections[formChildSections.length - 1];
      const lastInputField = get(lastChildSection, 'inputFields[0].rowClassName', '');
      if(lastInputField === 'mini-program-row' || lastInputField === 'link-row') {
        schema.standalone.sections[0].childSections[1].childSections[0].childSections.pop();
      }
      return schema;
    }

    onRedirectOptionSelection = (paramOne, formData) => {
      let schema = this.deletePreviousRedirectOptionSelection();
      switch (formData['template-redirect-options-radio']) {
        case URL: {
          schema.standalone.sections[0].childSections[1].childSections[0].childSections.push(this.getURLSchema());
          break;
        }
        case MINI_PROGRAM: {
          schema.standalone.sections[0].childSections[1].childSections[0].childSections.push(this.getMiniProgramSchema());
          break;
        }
      }
      this.setState({schema});
    }
    
    discardValues() {
      // this.setState({ schema: this.state.baseSchema, formData: {}});
      this.resetSchema();
      // this.resetState();
    }
    
    cancelTemplate() {
      const type = this.props.location.query.type;
      this.props.router.push({
        pathname: `/wechat`,
        query: type === 'embedded' ? {type: 'embedded'} : {},
      });
    }
    
    saveFormData(formData) {
      const obj = {};
      let selectedWechatData = {};
      const isEdit = this.state.isEdit;
      const { getFormData } = this.props;
      if (isEdit) {
        obj['_id'] = this.state.editTemplateData._id;
        selectedWechatData = {
          'template_id': this.state.editTemplateData.versions.base.template_id,
          'title': this.state.editTemplateData.versions.base.Title,
          'content': this.state.editTemplateData.versions.base.content,
        };
      } else {
        const selectedWechatTemplateIndex = findIndex(this.props.WeChat.weChatDefaultTemplate, {template_id: formData['wechat-template']});
        selectedWechatData = this.props.WeChat.weChatDefaultTemplate[selectedWechatTemplateIndex];
      }
      obj.name = `${selectedWechatData.title}: ${selectedWechatData.template_id}`;
      obj.type = 'WECHAT';
      obj.versions = {
        base: {},
        history: [],
      };
      obj.versions.base = {
        "template_id": selectedWechatData.template_id,
        "Title": selectedWechatData.title,
        Tag: [],
        TopColor: "#000000",
        data: {},
        preview: '',
        BrandId: (this.props.Templates.selectedWeChatAccount.configs.brand_id ? this.props.Templates.selectedWeChatAccount.configs.brand_id : ''),
        OriginalId: this.props.Templates.selectedWeChatAccount.sourceAccountIdentifier,
        content: selectedWechatData.content,
        isInternalUrl: this.state.formData['is-internal-url'],
      }
      if (this.state.formData['template-redirect-options-radio'] === MINI_PROGRAM) {
        const miniprogram = {};
        miniprogram['appid'] = this.state.formData['template-mini-program-id'] || '';
        miniprogram['pagepath'] = this.state.formData['template-mini-program-page-path'] || '';
        obj.versions.base['miniprogram'] = miniprogram;
        obj.versions.base['url'] = "notset";
      } else if (this.state.formData['template-redirect-options-radio'] === URL) {
        obj.versions.base['url'] = this.state.formData['is-internal-url'] ? this.maskTemplateUrl(this.state.formData['template-link']) : this.state.formData['template-link'];
      }
      forEach(this.state.selectedTemplateTags, (templateTag) => {
        const tagName = templateTag.substr(0, templateTag.indexOf('.'));
        let newTagname = tagName;
        obj.versions.base.Tag.push(tagName);
        if (tagName.match(/first/i)) {
          newTagname = "Header";
        }
        if (tagName.match(/remark/i)) {
          newTagname = "Footer";
        }
        obj.versions.base.data[tagName] = {};
        obj.versions.base.data[tagName] = {
          value: this.state.formData[`template-${newTagname}`],
          color: "#00000",
        }
      });
      
      this.props.actions.createTemplate(obj, (response) => {
        obj._id = response.templateID;
        if(getFormData) {
          setTimeout(() => {
            getFormData(this.getFormData(obj));
          }, 0);
        }
        const timeTaken = GA.timeTracker.stopTimer(isEdit ? TRACK_EDIT_WECHAT : TRACK_CREATE_WECHAT, {
          category: 'Creatives',
          action: isEdit ? TRACK_EDIT_WECHAT : TRACK_CREATE_WECHAT,
          label : 'MapTemplates',
        });
        gtmPush('creativeDetails', {
          id: response.templateId._id || response.templateId,
          name: obj?.versions?.base?.Title,
          channel: `${WECHAT} Maptemplate`,
          timeTaken,
          content: this.state.formData?.base?.['sms-editor'],
          mode: isEdit ? EDIT : CREATE
        });
      });
    }
    
    prepareWeChatPreviewData(wechatData, templateTags) {
      let content = cloneDeep(wechatData.content);
      const {formData} = cloneDeep(this.state);
      forEach(templateTags, (tag) => {
        let tagName = tag.substr(0, tag.indexOf('.'));
        if (tagName.match(/first/i)) {
          tagName = "Header";
        }
        if (tagName.match(/remark/i)) {
          tagName = "Footer";
        }
        if(this.state.formData[`template-${tagName}`] !== undefined && this.state.formData[`template-${tagName}`] !== '') {
          content = content.replace(`{{${tag}}}`, this.state.formData[`template-${tagName}`]);
        }
      })
      formData['sms-preview'] = content;
      // schema.standalone.sections[0].childSections[1].childSections[1].inputFields[0].cols[0].content = content;
      this.setState({formData}, () => {
        this.injectEvents(this.state.schema);
      });
    }
    
    injectEvents(schema) {
      
      if (isEmpty(schema)) {
        return false;
      }
      const temp = schema;
      let newSchema = cloneDeep(schema);
      temp.standalone.sections = this.injectSections(temp.standalone.sections);
      forEach(temp.containers, (container) => {
        let tempContainer = container;
        tempContainer = this.injectContainer(tempContainer);
        return tempContainer;
      });
      newSchema = this.hideSchemaElementsByModule(schema);
      this.setState({schema: newSchema});
      return schema;
    }
    
    hideSchemaElementsByModule(schema) {
      set(schema, 'standalone.sections[0].childSections[1].childSections[0].childSections[0].inputFields[0].labelStyle.display', this.props.location.query.module === 'loyalty' ? 'block' : 'none');
      set(schema, 'standalone.sections[0].childSections[1].childSections[0].childSections[0].inputFields[0].style.display', this.props.location.query.module === 'loyalty' ? 'block' : 'none');
      set(schema, 'standalone.sections[0].childSections[1].childSections[0].childSections[0].inputFields[1].disabled', get(this.props, 'params.id', false) && this.props.location.query.module !== 'loyalty');
      return schema;
    }
    
    injectContainer(container) {
      const temp = container;
      if (temp.type === 'tabs') {
        temp.tabContent.sections = this.injectSections(temp.tabContent.sections);
        temp.tabBarExtraContent.sections = this.injectSections(temp.tabBarExtraContent.sections);
        temp.tabContent.sections = this.injectSections(temp.tabContent.sections);
        temp.injectedEvents = {};
        forEach(temp.supportedEvents, (event) => {
          temp.injectedEvents[event] = this.getMappedEvent(temp.id, event);
        });
        forEach(temp.panes, (pane) => {
          const tempPane = pane;
          tempPane.sections = this.injectSections(tempPane.sections);
        });
      }
      return temp;
    }
    
    injectMultiColSection(section) {
      forEach(section.inputFields, (inputField) => {
        forEach(inputField.cols, (col) => {
          
          let temp = col;
          if (temp.type === 'popover') {
            temp.content.sections = this.injectSections(temp.content.sections);
            temp.value.sections = this.injectSections(temp.value.sections);
            return true;
          }
          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;
          if (temp.type === 'popover') {
            temp.content.sections = this.injectSections(temp.content.sections);
            temp.value.sections = this.injectSections(temp.value.sections);
            return true;
          }
          temp.injectedEvents = {};
          forEach(col.supportedEvents, (event) => {
            temp.injectedEvents[event] = this.getMappedEvent(col.id, event);
          });
          temp = this.injectMessages(temp);
          return true;
        });
      });
      return section;
    }
    
    injectColLabelSection(section) {
      forEach(section.inputFields, (inputField) => {
        let temp = inputField;
        if (temp.type === 'popover') {
          temp.content.sections = this.injectSections(temp.content.sections);
          temp.value.sections = this.injectSections(temp.value.sections);
          return true;
        }
        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;
        if (temp.type === 'popover') {
          temp.content.sections = this.injectSections(temp.content.sections);
          temp.value.sections = this.injectSections(temp.value.sections);
          return true;
        }
        temp.injectedEvents = {};
        forEach(actionField.supportedEvents, (event) => {
          temp.injectedEvents[event] = this.getMappedEvent(actionField.id, event);
        });
        temp = this.injectMessages(temp);
        return true;
      });
      return section;
    }
    
    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;
    }
    
    handleCancelModal = () => {
      this.setState({showModal: false});
    }
    
    injectParentSection(section) {
      forEach(section.childSections, (childSection) => {
        let temp = childSection;
        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.injectParentSection(temp);
        }
      });
      return section;
    }

    setTemplateMode = () => {
      this.setState({activeMode: SELECT_TEMPLATE_MODE});
    }

    renderSelectTemplate() {
      const { WeChat = {} } = this.props;
      const { weChatDefaultTemplate ={} } = WeChat;
      const cardList = map(weChatDefaultTemplate, (template) => {
        return {
          key: `wechat-card-${template.name}`,
          title: <span title={template.title} >{template.title}</span>,
          content: template.content,
          hoverOption: <CapButton onClick={(e) => this.setSelectedTemplateData(template)}>{this.props.intl.formatMessage(messages.select)}</CapButton>,
        };
      });
      return (
        <CapSpin
          spinning={isEmpty(weChatDefaultTemplate)}
          tip={this.props.intl.formatMessage(messages.gettingTemplateData)}
        >
          <CapCustomCardList 
            type="WECHAT"
            cardList={cardList}
          />
        </CapSpin>
      );
    }
    isLoading = () => {
      const isLoading = this.state.isLoading || this.props.fetchingSchema || this.props.WeChat.getTemplateDetailsInProgress;
      if (!isLoading && this.props.setIsLoadingContent) {
        this.props.setIsLoadingContent(isLoading);
      }
      return !!isLoading;
    }
    
    render() {
      const { activeMode, weChatData, isEdit } = this.state;
      const spinning = this.isLoading();
      let tags = this.props.metaEntities && this.props.metaEntities.tags ? this.props.metaEntities.tags.standard : [];
      if (this.props.supportedTags) {
        tags = this.props.supportedTags;
      }
      return (
        <div>
          {!isEdit && <CapHeading type="h1" style={{marginBottom: '32px'}}><FormattedMessage {...messages.newWechat}/></CapHeading>}
          {activeMode === SELECT_TEMPLATE_MODE ? 
            this.renderSelectTemplate() :
            <CapSpin
              tip={this.props.intl.formatMessage(messages.gettingTemplateData)}
              spinning={spinning}>
              <div>
                <CapHeading type="h5"><FormattedMessage {...messages.templateName}/></CapHeading>
                <CapHeading type="h3">{weChatData.title}</CapHeading>
                <CapRow className="wechat-container">
                  <CapColumn>
                    <FormBuilder
                      schema={this.state.schema}
                      onSubmit={this.saveFormData}
                      onChange={this.onFormDataChange}
                      parent={this}
                      modal={this.state.modalContent}
                      showModal={this.state.showModal}
                      iframeParent={parent}
                      formData={cloneDeep(this.state.formData)}
                      onFormValidityChange={this.setFormValidity}
                      location= {this.props.location}
                      tags={tags}
                      tagModule={this.props.getDefaultTags}
                      injectedTags={this.props.injectedTags ? this.props.injectedTags : {}}
                      isEdit={this.state.isEdit}
                      usingTabContainer={false}
                      router={this.props.router}
                      checkValidation={this.state.checkValidation}
                      startValidation={this.state.startValidation}
                      handleCancelModal={this.handleCancelModal}
                      onContextChange={this.handleOnTagsContextChange}
                      stopValidation={() => this.setFormValidity(false)}
                    />
                  </CapColumn>
                </CapRow>
              </div>
            </CapSpin>
          }
       </div>
        );
      }
    }
    
MapTemplates.propTypes = {
  actions: PropTypes.object.isRequired,
  WeChat: PropTypes.object,
  globalActions: PropTypes.object,
  Templates: PropTypes.object,
  location: PropTypes.object,
  router: PropTypes.object,
  params: PropTypes.object,
  metaEntities: PropTypes.object,
  intl: intlShape.isRequired,
  isGetFormData: PropTypes.bool,
  getLibraryFormData: PropTypes.func,
  getDefaultTags: PropTypes.string,
  templateData: PropTypes.object,
  templateActions: PropTypes.object,
  injectedTags: PropTypes.object,
  isFullMode: PropTypes.bool,
  getFormData: PropTypes.func,
  weChatMaptemplateStep: PropTypes.bool,
  setIsLoadingContent: PropTypes.func,
};

const mapStateToProps = createStructuredSelector({
  WeChat: makeSelectWeChat(),
  Templates: makeSelectTemplates(),
  metaEntities: makeSelectMetaEntities(),
  fetchingSchema: makeSelectFetchingSchema(),
  injectedTags: setInjectedTags(),
});

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

const withReducer = injectReducer({ key: 'weChatMapTemplate', reducer: v2WechatMapTemplatesReducer });

export default withCreatives({
  WrappedComponent: MapTemplates,
  mapStateToProps,
  mapDispatchToProps,
  userAuth: true,
  reducers: [withReducer],
});
        
