<template>
    <div class="row">
        <div class="col bg-white padding-40 b-rad-lg">
            <loading-component style="height: 50px; top: 0;" key="1" color="success" v-show="$store.getters.isLoading(section)"></loading-component>
            <div class="row" v-if="question" v-show="!$store.getters.isLoading(section)">
                <div class="col">
                    <div class="row m-b-5 animate__animated animate__fadeInUpBig animate__fast" v-if="error">
                        <div class="col">
                            <small class="bold fs-10 text-danger">{{error}}</small>
                        </div>
                    </div>
                    <div class="row m-b-20">
                        <div class="col">
                            <h3>{{question.question_text}}</h3>
                        </div>
                    </div>
                    <div class="row m-b-10" v-if="question.question_type === 4" >
                        <div class="col" v-for="ans in question.question_answers">
                            <div v-html="ans.display_text"></div>
                        </div>
                    </div>
                    <div class="row m-b-15" v-else-if="question.question_type === 3">
                        <div class="col">
                            <file-input-component :validator="$v.files" v-model="files">
                                <template slot="label">
                                    <div class="font-heading fs-11 all-caps">Photo or File</div>
                                </template>
                                <template slot="tips">
                                    <div class="row"  v-show="false">
                                        <div class="col">
                                            <div class="row m-b-20">
                                                <div class="col">
                                                    <div class="font-heading fs-11 text-warning m-b-10">{{ documentType === 0 ? 'IC': 'SSM registration'}} number shown in the photo should tally with {{ documentType === 0 ? 'IC': 'SSM registration'}} number provided above.</div>
                                                    <div class="font-heading fs-11 muted">Tips on how your photo should look</div>
                                                </div>
                                            </div>

                                        </div>
                                    </div>
                                </template>
                            </file-input-component>
                        </div>
                    </div>
                    <div class="row m-b-10" v-show="question.is_end === 0" v-else-if="question.question_type === 1" >
                        <validation-wrapper-component :validator="$v.answer" class="col">
                            <div class="col" v-for="ans in question.question_answers">
                                <div class="col question.answers">
                                    <div class="btn btn-xs btn-block" :answerValue="ans.value" :answerId=ans.id @click="addClass($event, 'question.answers')">{{ ans.display_text }}</div>
                                </div>
                            </div>
                        </validation-wrapper-component>
                    </div>
                    <div class="row m-b-10" v-show="question.is_end === 0" v-else>
                        <div class="col" >
                            <validation-wrapper-component :validator="$v.answer">
                                <label>Answer</label>
                                <input type="text" class="form-control" v-model="answer" @input="formTouched = true">
                            </validation-wrapper-component>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col p-r-5">
                            <div class="btn btn-sm btn-default bg-master-lightest btn-block b-rad-none" @click=" submitForm('previous')">Previous</div>
                        </div>
                        <div class="col p-r-5">
                            <div class="btn btn-sm btn-default bg-master-lightest btn-block b-rad-none" data-dismiss="modal">Cancel</div>
                        </div>
                        <div class="col p-l-5">
                            <div class="btn btn-sm btn-primary btn-block b-rad-none" :disabled="!$v.$dirty || !$v.$valid" @click="formTouched = true; submitForm('next')">{{ question.is_end === 0 ? 'Next' : 'Finish' }}</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
    import { required } from "vuelidate/lib/validators";
    export default {
        data(){
            return {
                section: 'helpMenuForm',
                showAnswerInput: false,
                showUploadInput: false,
                formTouched: false,
                question: null,
                answer: '',
                answerId: 0,
                direction: 'next',
                documentType: 1,
                files: [],
                error: null
            }
        },
        validations() {
            return {
                answer: {
                    required:  this.formTouched && this.showAnswerInput ? required : false,
                },
                files: {
                    required:  this.formTouched && this.showUploadInput ? required : false,
                }
            };
        },
        computed: {
            pendingQueue () {
                return this.$store.getters.isInCompleteQueue(this.section);
            },
            parametersExist() {
                return Boolean(this.answer);
            }
        },
        watch: {
            pendingQueue(inComplete, oldValue){
                if(inComplete){
                    this.fetchFirstQuestion();
                }
            }
        },
        created(){
            this.$store.dispatch('updateListQueue', {'name': this.section});
        },
        methods: {
            fetchFirstQuestion(){
                this.submit(route('api.helpmenu.first.question', 4), 'get', this.section, false, false);
            },
            successHandler(response){
                this.$store.dispatch('completeList', {'name': this.section, 'data': []});
                this.question = response.payload.data;
                this.reset();
                this.removeClass('question.answers');
                if(this.question.answer != null && this.direction == "previous"){
                    this.answer = this.question.answer.free_text_answer;
                }
            },
            errorHandler(error){
                // this.error = error.message;
                this.error = 'We are sorry, something went wrong. Please contact us via live chat.';
            },
            submitForm(direction) {
                this.parameters = {}
                this.error = null;
                this.direction = direction;
                if(this.question.question_type === 3){
                    this.showAnswerInput = false;
                    this.showUploadInput = true;
                }
                else if(this.question.question_type === 1 || (this.question.question_type === 2)){
                    this.showAnswerInput = true;
                    this.showUploadInput = false;
                }
                if(direction === 'next'){
                    this.parameters.question = this.question;
                    this.parameters.answer = this.answer;
                    this.parameters.answerId = this.answerId;
                    this.parameters.answerObj = this.question.question_answers.find(item => item.id === Number(this.answerId));
                    this.parameters.files = this.files;
                    if(this.question.question_type === 4)
                    {
                        this.closeModal();
                        this.reset();
                        this.fetchFirstQuestion();
                    }
                    else{
                        if(this.question.is_end){
                            if(this.question.question_type === 5){
                                this.submit(this.route('api.helpmenu.next.question'), 'post', this.section, false, false);
                                this.closeModal();
                                this.reset();
                            }
                            else{
                                $crisp.push(["do", "chat:open"]);
                                const result = [
                                    ...this.question.questionnaire_answers.map(item => [item.question_text.replace(/ /g, "_").replace(/\W/g, ''), item.free_text_answer])
                                ];
                                let payload = [];
                                payload.push(result);
                                $crisp.push(["set", "session:data", payload]);
                                $crisp.push(["do", "message:send", ["text", "Hello there!"]]); //cief todo: need to update what message to send from customer to operator
                                this.closeModal();
                                this.reset();
                                this.fetchFirstQuestion();
                            }
                        }
                        else{
                            this.submit(this.route('api.helpmenu.next.question'), 'post', this.section, false, false);
                        }
                    }
                }
                else if(direction === 'previous'){
                    this.formTouched = false;
                    this.parameters.question = this.question;
                    this.parameters.isPrevious = true;
                    this.submit(this.route('api.helpmenu.next.question'), 'post', this.section, false, false);
                }
            },
            reset() {
                this.parameters = null;
                this.answer = '';
                this.answerId = 0;
                this.files = [];
                this.formTouched = false;
                this.showAnswerInput = false;
                this.showUploadInput = false;
                this.error = null;
            },
            addClass(event, cls) {
                const div = event.target;
                this.answer = div.getAttribute('answerValue');
                this.answerId = div.getAttribute('answerId');
                this.removeClass(cls);
                div.classList.add('btn-primary');
            },
            removeClass(cls) {
                document.getElementsByClassName(cls).forEach(el => {
                    const btnPrimaryEl = el.getElementsByClassName('btn-primary')[0];
                    if (btnPrimaryEl) {
                        btnPrimaryEl.classList.remove('btn-primary');
                    }
                });
            }
        },
    }
</script>
