<template>
    <v-container class="home d-flex align-center justify-center" >
        <v-row  >
            <v-col col="2">
                <Stepper
                    :wpo="wpo"
                    :step="step"
                    :infos="infos"
                    :project="project"
                />
            </v-col>
            <v-col cols="7"  >
                <Card
                    :wpo="wpo"
                    :step="step"
                    :infos="infos"
                    :project="project"
                    :counter="counter"
                    :result="resultRect"
                    :captureImage="captureImage"
                />
            </v-col>
            <v-col col="3">
                <Chart
                    :wpo="wpo"
                    :step="step"
                    :infos="infos"
                    :project="project"
                    :counter="counter"
                    :result="result"
                />

                <List
                    :wpo="wpo"
                    :step="step"
                    :infos="infos"
                    :project="project"
                    :result="result"
                />
            </v-col>
        </v-row>
    </v-container>
</template>

<script>
import wpoService from '../service/wpo'
import projectService from '../service/project'
import teachingService from '@/service/teaching'

import { EventBus } from '@/event-bus'

import Stepper from '../views/main/Stepper.vue'
import Chart from '../views/main/Chart.vue'
import Card from '../views/main/Card.vue'
import List from '../views/main/List.vue'

import gql from 'graphql-tag'

export default {
    data () {
      return {
            step:0, 
                
            wpo:'',

            project:{},

            aoi:{},

            infos:[],

            counter:0,

            result:[],

            resultRect:[],

            captureImage:null
        }
    },

    components:{
        Stepper,
        Card,
        List,
        Chart
    },

    mounted(){
        this.step = 1
    },

    methods: {
        dataInit(){
            this.step = 0, 
            this.project = {},
            this.aoi = {},
            this.infos =[],
            this.counter = 0,
            this.result =[]
            this.captureImage = null
        },
        
        async getAoi(){
            try{
                const response = await this.$apollo.query({
                    query: gql`
                        query neuroAoi($name: String!) {
                            neuroAoi(name: $name) {
                                uid
                                name
                                aoi
                                aoiName
                                createDate
                            }
                        }`,
                    variables: { name: this.wpo }
                })

            let aoi = response.data.neuroAoi
            console.log('aoi', aoi)
        

            if (!aoi) return ''

            if (aoi.errors)  throw new Error(aoi.errors[0])
        
            this.aoi = aoi

            return true
            
            }catch (e) { 
                console.log(e)
                throw e 
            }
        },

        async getProject(){
            try{
                const response = await this.$apollo.query({
                    query: gql`
                        query neuroProject($aoiUid:Int!) {
                            neuroProject(aoiUid:$aoiUid) {
                                uid
                                name
                                user
                                admin
                                createDate
                                successDate
                                counter
                                aoiUid
                                state
                            }
                        }`,
                    variables: { aoiUid: this.aoi.uid }
                })

            let project = response.data.neuroProject
            console.log('project', project)

            if (!project) return ''

            if (project.errors)  throw new Error(project.errors[0])
            
            this.project = project

            return true

            }catch (e) { 
                console.log(e)
                throw e 
            }
        },

        async getInfos(){
            try{
                const response = await this.$apollo.query({
                    query: gql`
                        query neuroInfos($projectUid: Int!) {
                            neuroInfos(projectUid: $projectUid) {
                                projectUid
                                order
                                type 
                                startX
                                startY 
                                lastX
                                lastY
                                width
                                height
                                goodImage
                                missingImage
                                goodPath
                                missingPath
                            
                        }
                    }`,
                    variables: { projectUid: this.project.uid }
                })

            let infos = response.data.neuroInfos
            console.log('infos', infos)

            if (!infos) return ''

            if (infos.errors)  throw new Error(infos.errors[0])

            this.infos = infos

            return true

            }catch (e) { 
                console.log(e)
                throw e 
            }
        },

        async getWpoId(){
            try{
                let response = await wpoService.getWpoId()
                if(typeof response === 'undefined') throw new Error('서버와 연결 되지 않았습니다.')
                this.wpo= response.data 
                this.step = 2
            }catch(e){
                EventBus.$emit('openAlert',`${e.message}`, 'error')
            }
        },

        async dataSetting(){
            
            let result1 = await this.getAoi()
            let result2 = await this.getProject()
            let result3 = await this.getInfos()

            let test = await projectService.projectInfo(this.project ,this.infos )

            console.log('받아온 데이터',test)

            if(result1 === true && result2 === true && result3 === true ) this.step = 3 

        },

        async teachingCheck(){
            try{
                const msg  = new Object()
                msg.cmd = "neuro_start"
                msg.project_num = this.project.uid 
                let response = await teachingService.requestManager(msg)

                if(typeof response === 'undefined') throw new Error('서버와 연결 되지 않았습니다.')
                if(response.status !== 200) throw new Error('옳지 않은 응답입니다.')
                this.step = 4
            }catch(e){
                EventBus.$emit('openAlert',`${e.message}`, 'error')
            }
        },

        async captureReady(){
            try{
                const msg  = new Object()
                 msg.cmd = "neuro_ready"
                let response = await teachingService.requestManager(msg)

                if(typeof response === 'undefined') throw new Error('서버와 연결 되지 않았습니다.')
                if(response.status !== 200) throw new Error('옳지 않은 응답입니다.')
                this.imageCapture()
            
            }catch(e){
                EventBus.$emit('openAlert',`${e.message}`, 'error')
            }
        },

        async imageCapture(){
            try{
                const msg  = new Object()
                msg.cmd = "neuro_capture"
                let response = await teachingService.requestManager(msg)
        
                let data = JSON.parse(response.data)
                this.captureImage = data.imageBase64
                
                if(typeof response === 'undefined') throw new Error('서버와 연결 되지 않았습니다.')
                if(response.status !== 200) throw new Error('옳지 않은 응답입니다.')
                this.step = 5
            }catch(e){
                EventBus.$emit('openAlert',`${e.message}`, 'error')
            }
        },

        async inspection(){
            try{
                
                let teachingInfo = ''
                this.infos.forEach((rect) => {
                    let str = `(${Math.ceil(rect.startX * 1.5)},${Math.ceil(rect.startY * 1.5)},${Math.ceil(rect.lastX * 1.5)},${Math.ceil( rect.lastY * 1.5) })`
                    teachingInfo= teachingInfo + "-" + str 
                })

                let msg = new Object()
                msg.cmd = "neuro_check"
                msg.project_num = this.project.uid 
                msg.teaching_info = teachingInfo

                let response = await teachingService.requestManager(msg)
                let data = JSON.parse(response.data)
                 
                 console.log('검수 데이터 ', data)

                this.resultRect = []

                let order = new Object()
                order.counter = this.counter
                order.time = Number(data['proc_time'])                
                order.result = data['result']

                this.resultRect = data['check_box']

                this.result.push(order)

                if(typeof response === 'undefined') throw new Error('서버와 연결 되지 않았습니다.')
                if(response.status !== 200) throw new Error('옳지 않은 응답입니다.')
                
                this.counter === this.project.counter ? this.step = 6 : this.step = 4   

            }catch(e){
                EventBus.$emit('openAlert',`${e.message}`, 'error')
            }
        }
    },

    watch:{
        async step(current) {
            console.log("현재 스텝 :",  current)
            if(current === 1){
                console.log("1번 입니다.")
                this.dataInit() 
                this.wpo === '' ? this.getWpoId() : this.step = 2  
            }else if(current === 2){
                console.log("2번 입니다.")
                this.dataSetting()
            }else if(current === 3){
                console.log("3번 입니다.")
                this.teachingCheck()
            }else if(current === 4){  
                console.log("4번 입니다.")
                this.captureReady()
            }else if(current === 5){
                console.log("5번 입니다.")
                ++this.counter
                console.log(this.counter)
                this.inspection()
            }else if(current === 6){  
                console.log("6번 입니다.")
            }
        }
    },
}
</script>

<style lang="scss">
.home{
    height: 100vh;
}
</style>