<template>
    <v-container class="home d-flex align-center justify-center" >
        <v-row  >
            <v-col col="3">
                <v-card 
                    min-height="846"
                >
                    <v-card-title class="green darken-1 white--text font-weight-bold" >{{project.name}}</v-card-title>
                    <v-card-text class="mt-3">
                        <v-text-field
                            label="관리자"
                            v-model="project.admin"
                            readonly
                            outlined
                        ></v-text-field>
                        <v-text-field
                            label="작업자"
                            v-model="project.user"
                            readonly
                            outlined
                        ></v-text-field>
                        <v-row> 
                            <v-col cols="6">
                                <v-text-field
                                    label="작업자"
                                    v-model="project.createDate"
                                    readonly
                                    outlined
                                ></v-text-field>
                            </v-col>
                            <v-col cols="6">
                                <v-text-field
                                    label="작업자"
                                    v-model="project.successDate"
                                    readonly
                                    outlined
                                ></v-text-field>
                            </v-col>
                        </v-row>
                        <p>진행 사항</p>
                        <v-row > 
                            <v-col cols="3">
                                <v-text-field
                                    label="진행 횟수"
                                    v-model="total"
                                    readonly
                                    filled
                                ></v-text-field>
                            </v-col>                            
                            <v-col cols="3">
                                <v-text-field
                                    label="성공 횟수"
                                    v-model="success"
                                    readonly
                                    filled
                                ></v-text-field>
                            </v-col>                            
                            <v-col cols="3">
                                <v-text-field
                                    label="실패 횟수"
                                    v-model="fail"
                                    readonly
                                    filled
                                ></v-text-field>
                            </v-col>
                            <v-col cols="3">
                                <v-text-field
                                    label="검수 횟수"
                                    v-model="project.counter"
                                    readonly
                                    filled
                                ></v-text-field>
                            </v-col>
                        </v-row>
                    <Result
                        :step="step"
                        :project="project"
                        :result="result"
                    />
                    </v-card-text>
                </v-card>
            </v-col>
            <v-col cols="9"  >
                <Board
                    :step="step"
                    :learnings="learnings"
                    :project="project"
                    :counter="success"
                    :result="resultRect"
                    :captureImage="captureImage"
                />
            </v-col>

        </v-row>
    </v-container>
</template>

<script>
import managerService from '@/service/manager'
import projectService from '@/service/project'

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

import Board from '@/views/main/Board.vue'
import Result from '@/views/main/Result.vue'


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

            aoi:{},

            total:0, //진행 횟수
            
            success:0, //성공 횟수
            
            fail:0, //실패 횟수

            result:[],

            resultRect:[],

            captureImage:null ,

        }
    },

    props: {
        project: Object,
        learnings: Array,
    },

    components:{
        Board,
        Result,
        // Chart
    },

    created(){
        this.step = 1
    },

    methods: {
        async teachingCheck(){
            try{
                const msg  = new Object()
                msg.cmd = "neuro_start"
                msg.project_num = this.project.uid 
                let response = await managerService.request(msg)

                console.log('neuro_start :',JSON.parse(response.data).state)

                JSON.parse(response.data).state ? this.step = 2 :  EventBus.$emit('openAlert',`AOI 전원을 재부팅 해주세요`, 'error')
                
            }catch(e){
                EventBus.$emit('openAlert',`${e.message}`, 'error')
            }
        },

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

                JSON.parse(response.data).cmd === 'neuro_ready_done' ? this.step = 3 :  EventBus.$emit('openAlert',`AOI 전원을 재부팅 해주세요`, 'error')

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

        async imageCapture(){
            try{
                const msg  = new Object()
                msg.cmd = "neuro_capture"
                let response = await managerService.request(msg)

                let data = JSON.parse(response.data)
                this.captureImage = data.imageBase64
                
                this.step = 4
            }catch(e){
                EventBus.$emit('openAlert',`${e.message}`, 'error')
            }
        },

        async inspection(){
            try{
                
                let teachingInfo = ''
                this.learnings.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 managerService.request(msg)
                let data = JSON.parse(response.data)
                 
                this.resultRect = []

                let order = new Object()
                order.total = this.total
                order.result = data['result']

                data['result'] ===  0 ?  ++ this.fail : ++ this.success  

                this.resultRect = data['check_box']

                this.result.push(order)

                console.log(this.result)

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

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

        async teachingResult(){
            EventBus.$emit('openLoading','Finish...')

            try{

                const msg  = new Object()
                msg.cmd = "neuro_complete"
                let response = await managerService.request(msg)

                if(JSON.parse(response.data).cmd === "complete_done"){
                    this.project.total = this.total 
                    this.project.success = this.success
                    this.project.fail = this.fail
                    this.project.result = true

                    let saveData = {
                        'project':this.project,
                        'learning': this.learnings
                    }

                    let response = await projectService.save(saveData)

                    if(Object.keys(response.project).length !== 0 ){
                        EventBus.$emit('closeLoading')
                        EventBus.$emit('setProject' , response.project )
                    }
                }
            }catch(e){
                EventBus.$emit('openAlert',`${e.message}`, 'error')
            }
        }









        // async replay(){
        //     try{
        //         let msg = new Object()
        //         msg.cmd = "neuro_replay"

        //         let response = await managerService.requestManager(msg)
        //         let data = JSON.parse(response.data)
        //         if(data['btn_num'] === 1){
        //             this.dataInit()
        //             this.step = 2
        //         }else{
        //             this.replay()
        //         }  
        //     }catch(e){
        //         EventBus.$emit('openAlert',`${e.message}`, 'error')
        //     }
        // }
    },

    watch:{
        async step(current) {
            if(current === 1){
                await this.teachingCheck()
            }else if(current === 2){  
                await this.captureReady()
            }else if(current === 3){
                await this.imageCapture()
            }else if(current === 4){  
                ++this.total
                await this.inspection()
            }else if(current === 5){  
                await this.teachingResult()
            }
        }
    },
}
</script>

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