<template>
  <div>
    <b-form>
      <div v-if="templateDetails.channelSelect">
        <div v-for="(a, index) in templateDetails.channelSelect" :key="index">
          <div v-if="templateDetails.channelCurrentSelect == 'Email'">
            <div
              v-if="templateDetails.channelSelect[index] == 'Email' && templateDetails.channelSelect.length != 0"
            >
              <div v-b-toggle.email class="vb-body-right-option pointer option-head">E-mail Feature</div>
              <b-collapse id="email" visible>
                <div class="container">
                  <b-form-group id="template-name" label="E-mail Subject" label-for="name">
                    <b-form-input
                      class="brn"
                      id="name"
                      v-model="templateDetails.emailSubject"
                      type="text"
                    ></b-form-input>
                  </b-form-group>
                  <!-- <b-form-group v-if="$route.params.templateid || $route.name == 'spacemessagecompose'">
                                    <span class="attch-box">
                                        <input
                                                type="file"
                                                id="imageUpload"
                                                @change="attachmentfiles($event)"
                                                multiple
                                                >
                                        <label for="imageUpload"> Attachments</label>
                                    </span>
                  </b-form-group>-->
                  <!-- <div v-if="$route.params.templateid || $route.name == 'spacemessagecompose'">
                                    <div v-for="(file, index) in uploadData" :key="index" class="mB-5">
                                        <div v-if="file.upload">
                                            <div class="attachfilebox" v-if="5242890 > file.size" style="background-color:#FFF">
                                                <span v-if="5242890 > file.size">
                                            <b>{{file.name}}</b> ({{Math.round(file.size/1024)}} kb)
                                        </span>
                                                <span class="float-right ti-trash pY-5" v-on:click="delAttachment(index)"></span>
                                            </div>
                                            <div class="attachfilebox" v-else style="background-color:rgba(251, 107, 107, 0.4)">
                                                <span>
                                            <b>{{file.name}}</b> ({{Math.round(file.size/1024)}} kb)
                                        </span>
                                                <span class="float-right ti-trash pY-5" v-on:click="delAttachment(index)"></span>
                                            </div>
                                            <b-progress height="1px" :value="10" style="background-color:#CCC"></b-progress>
                                        </div>
                                        <div v-else>
                                            <div class="attachfilebox" style="background-color:rgba(251, 107, 107, 0.4)">
                                                <span>
                                            <b>{{file.name}}</b> ({{Math.round(file.size/1024)}} kb)
                                        </span>
                                                <span class="float-right ti-trash pY-5" v-on:click="delAttachment(index)"></span>
                                            </div>
                                            <b-progress height="1px" :value="10" style="background-color:#CCC"></b-progress>
                                        </div>

                                    </div>
                  </div>-->
                </div>
              </b-collapse>
            </div>
          </div>
          <div v-if="templateDetails.channelCurrentSelect == 'SMS'">
            <div
              v-if="templateDetails.channelSelect[index] == 'SMS' && templateDetails.channelSelect.length != 0"
            >
              <div v-b-toggle.sms class="vb-body-right-option pointer option-head">SMS Feature</div>
              <b-collapse id="sms" visible>
                <div class="container">
                  <b-form-group>
                    <b-form-checkbox v-model="templateDetails.isreply" switches stacked>Reply</b-form-checkbox>
                  </b-form-group>
                </div>
              </b-collapse>
            </div>
          </div>
        </div>
      </div>
      <div class="p-10" v-if="templateDetails.channelSelect">
        <!-- <p v-if="$route.params.templateid"><b>Template Name: </b>{{templateDetails.name}}</p>
        <p v-if="$route.params.templateid"><b>Description: </b>{{templateDetails.description}}</p>-->
        <b-form-group
          id="template-name"
          label="Template Name"
          label-for="name"
          v-if="$route.name == 'templatecreate' || ($route.name == 'templateedit'  && $route.params.templateid)"
        >
          <b-form-input
            class="brn"
            id="name"
            v-model="templateDetails.name"
            type="text"
            :disabled="templateDetails.composedisable"
          ></b-form-input>
        </b-form-group>

        <b-form-group
          id="input-group-3"
          label="description"
          label-for="textarea"
          v-if="$route.name == 'templatecreate' || ($route.name == 'templateedit'  && $route.params.templateid)"
        >
          <b-form-textarea
            class="brn"
            id="textarea"
            v-model="templateDetails.description"
            rows="3"
            max-rows="4"
            :disabled="templateDetails.composedisable"
          ></b-form-textarea>
        </b-form-group>
        <b-form-group
          id="input-group-3"
          label="To List"
          label-for="conatctsget"
          v-if="templateDetails.channelSelect.length != 0"
        >
          <multiselect
            id="conatctsget"
            v-model="templateDetails.groupMemberList"
            label="name"
            track-by="mri"
            tag-placeholder="External Contacts"
            placeholder="Add Contacts and Groups"
            :multiple="true"
            :taggable="true"
            :options="contacts"
            @tag="addTag"
            :searchable="true"
            @search-change="findContacts"
            :hide-selected="true"
            class="addcontact"
          ></multiselect>
        </b-form-group>
        <b-form-group>
          <b-form-checkbox-group
            v-model="templateDetails.channelSelect"
            :options="templateDetails.channelOption"
            switches
            stacked
          ></b-form-checkbox-group>
        </b-form-group>
      </div>

      <div v-if="templateDetails.channelSelect">
        <div
          class="mx-auto"
          v-if="$route.name == 'templatecreate' || ($route.name == 'templateedit'  && $route.params.templateid)"
          style="padding: 10px"
        >
          <div class="avatar-upload">
            <div class="avatar-edit-box">
              <input
                type="file"
                id="tempimageUpload"
                accept=".png, .jpg, .jpeg"
                @change="onFileSlected($event)"
                :disabled="templateDetails.composedisable"
              />
              <label for="tempimageUpload"></label>
            </div>
            <div v-if="templateDetails.imageData==null">
              <div v-if="templateDetails.url == ''">
                <b-img
                  fluid
                  src="https://s3.ap-southeast-1.amazonaws.com/vemessage-images/1554181778740-download.jpg"
                  alt="Thumbnail"
                  class="avatar-preview-box"
                />
              </div>
              <div v-else>
                <b-img fluid :src="templateDetails.url" alt="Thumbnail" class="avatar-preview-box" />
              </div>
            </div>
            <div v-else>
              <b-img
                fluid
                :src="templateDetails.imageData"
                alt="Thumbnail"
                class="avatar-preview-box"
              />
            </div>
          </div>
        </div>
      </div>
      <!-- live form -->
      <div class="p-10" v-if="$route.name == 'liveformCreate' || $route.params.workflowId">
        <p v-if="$route.params.templateid">
          <b>Template Name:</b>
          {{templateDetails.name}}
        </p>
        <p v-if="$route.params.templateid">
          <b>description:</b>
          {{templateDetails.description}}
        </p>
        <b-form-group id="template-name" label="Template Name" label-for="name">
          <b-form-input
            class="brn"
            id="name"
            v-model="templateDetails.name"
            type="text"
            :disabled="templateDetails.composedisable"
          ></b-form-input>
        </b-form-group>

        <b-form-group id="input-group-3" label="description" label-for="textarea">
          <b-form-textarea
            class="brn"
            id="textarea"
            v-model="templateDetails.description"
            rows="3"
            max-rows="4"
            :disabled="templateDetails.composedisable"
          ></b-form-textarea>
        </b-form-group>
        <b-form-group id="input-group-3" label="description" label-for="textarea">
          <b-form-select
            v-model="templateDetails.live"
            :options="liveoptions"
            size="sm"
            class="mt-3"
          ></b-form-select>
        </b-form-group>
      </div>
      <div v-if="$route.name == 'liveformCreate' || $route.params.workflowId">
        <div class="mx-auto">
          <div class="avatar-upload">
            <div class="avatar-edit-box">
              <input
                type="file"
                id="tempimageUpload"
                accept=".png, .jpg, .jpeg"
                @change="onFileSlected($event)"
                :disabled="templateDetails.composedisable"
              />
              <label for="tempimageUpload"></label>
            </div>
            <div v-if="templateDetails.imageData==null">
              <div v-if="templateDetails.url == ''">
                <b-img
                  fluid
                  src="https://s3.ap-southeast-1.amazonaws.com/vemessage-images/1554181778740-download.jpg"
                  alt="Thumbnail"
                  class="avatar-preview-box"
                />
              </div>
              <div v-else>
                <b-img fluid :src="templateDetails.url" alt="Thumbnail" class="avatar-preview-box" />
              </div>
            </div>
            <div v-else>
              <b-img
                fluid
                :src="templateDetails.imageData"
                alt="Thumbnail"
                class="avatar-preview-box"
              />
            </div>
          </div>
        </div>
      </div>
    </b-form>
  </div>
</template>

<script>
import Multiselect from "vue-multiselect";

export default {
  components: {
    Multiselect
  },
  props: {
    templateDetails: Object
  },
  data() {
    return {
      checksize: false,
      datasize: 0,
      uploadData: [],
      filesUpload: "",
      liveoptions: [
        {
          value: true,
          text: "Live"
        },
        {
          value: false,
          text: "Not Live"
        }
      ],
      selectFile: null,
      contacts: [],
      notificationSystem: {
        options: {
          show: {
            theme: "dark",
            icon: "icon-person",
            position: "topCenter",
            progressBarColor: "rgb(0, 255, 184)"
          },
          success: {
            // position: "bottomRight"
            position: "topRight"
          },
          warning: {
            position: "topRight"
          },
          error: {
            position: "topRight"
          }
        }
      }
    };
  },
  watch: {
    "templateDetails.channelOption": function(val) {
      console.log(val);
      // if(val.length >= 1){

      // }else{
      //     console.log(val)
      // }
    }
  },
  methods: {
    findContacts(query) {
      this.getApi.searchContactsandGroup(query).then(response => {
        if (response.status == 200) {
          this.contacts = response.data;
        } else {
        }
      });
    },
    attachmentfiles(event) {
      this.filesUpload = event.target.files;
      for (var i = 0; i < this.filesUpload.length; i++) {
        this.helper(event.target.files[i]);
      }
    },
    helper(file) {
      var reader = new FileReader();
      reader.onload = e => {
        this.datasize = this.datasize + file.size;
        if (5242890 > this.datasize) {
          this.checksize = true;
        }
        // if()
        this.uploadData.push({
          name: file.name,
          size: file.size,
          type: file.type,
          attachment: e.target.result,
          upload: this.checksize
        });
        this.checksize = false;
      };
      reader.readAsDataURL(file);
    },
    delAttachment(index) {
      this.uploadData.splice(index, 1);
      this.datasize = 0;
      this.uploadData.forEach(elem => {
        this.datasize += elem.size;
        if (5242890 > this.datasize) {
          this.checksize = true;
        }
        elem.upload = this.checksize;
        this.checksize = false;
      });
    },
    onFileSlected(event) {
      if (event.target.files && event.target.files[0]) {
        this.selectFile = event.target.files[0];
        var reader = new FileReader();
        reader.onload = e => {
          this.templateDetails.imageData = e.target.result;
          this.postApi.imageUpload(this.selectFile).then(response => {
            // console.log(response.data[0].files);
            this.templateDetails.url = response.data[0].files;
          });
        };
        reader.readAsDataURL(event.target.files[0]);
      }
    },
    //limit function
    limitText(count) {
      return `${count} more`;
    },
    //create external contacts
    addTag(newTag) {
      var intpakphone = /^\+?([0-9]{2})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
      var localpakphone = /^\(?([0]{1})\)?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
      var standemail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w+)+$/;
      var contactemail = /^\w+([\.-]?\w+)*@contacts.vemessage.com+$/;
      var groupemail = /^\w+([\.-]?\w+)*@groups.dev.vemessage.com+$/;
      if (newTag.match(intpakphone) || newTag.match(localpakphone)) {
        const tag = {
          name: newTag,
          mri: newTag,
          mobile: newTag
        };
        this.templateDetails.groupMemberList.push(tag);
        this.contacts.push(tag);
      } else if (standemail.test(newTag)) {
        const tag = {
          name: newTag,
          mri: newTag,
          email: newTag
        };
        this.templateDetails.groupMemberList.push(tag);
        this.contacts.push(tag);
      } else {
        const arr = newTag.split(",");
        for (var i = 0; i < arr.length; i++) {
          if (arr[i].match(intpakphone) || arr[i].match(localpakphone)) {
            const tag = {
              name: arr[i],
              email: arr[i],
              mri: arr[i]
            };
            this.templateDetails.groupMemberList.push(tag);
            this.contacts.push(tag);
          } else if (standemail.test(arr[i])) {
            const tag = {
              name: arr[i],
              email: arr[i],
              mri: arr[i]
            };
            this.templateDetails.groupMemberList.push(tag);
            this.contacts.push(tag);
          } else {
            this.$toast.warning(
              arr[i] + " this is not Correct E-mail or Phone Number",
              "Alert",
              this.notificationSystem.options.warning
            );
          }
        }
      }
    }
    //find contacts and groups function
  }
};
</script>
