var WxParse = require('../../wxParse/wxParse.js');
const app = getApp();
var that;
var Interval;
var wechat;
var id;
var intt;
const baseUrl = getApp();
const api = require('../../config/api.js');
const util = require('../../config/util.js');
Page({
    startX: 0,
    startY: 0,
    isClear: false,

    /**
     * 页面的初始数据
     */
    data: {
        reexam: 0, //是否反复作答 0不是，1是
        index: 0,
        hour: 0,
        minute: 0,
        second: 0,
        millisecond: 0,
        timecount: '00:00:00',
        cost: 0,
        flag: 1,
        endtime: "",
        baseurl: baseUrl.globalData.baseimgurl,
        time: 1 * 60 * 60 * 1000, //初始时间
        paystatus: 1, //1未开始时间开始状态，2开始
        collection: 1, //1不收藏，2已收藏
        singdouble: 1, //1单选，2多选
        paiduanactive: 1,//1不是判断，2是判断题
        zstime: 1, //1正计，0倒计
        typeid: 1, //0练习1正式
        activeopen: true,
        coursetypefour_id: 1,
        itemdatacurrent: [], //当前数据
        itemdataall: [], //全部数据
        itemdata: [],  //选项数据
        content: "",//富文本数据
        showModalStatus: false,
        pen: 3,
        color: '#FFFFFF',
        currentTab: 0,
        now: 1, //当前页码
        all: 15, //总页码
        height: 0,
        Timer_state: 1,
        Answer_card: false,
        Draft_paper: false,
        false_analysis: false,
        stem_height: 150,
        jiexi: false,
        field: {
            analysis_text: "",
        },
        img: [],
        scroll: "scroll",
        drag_line: false,
        showvide: false,
        showexampop: false, //查看交卷,
        examlistdata: [],
        examlist: [],
    },
    showPopup() {
        this.getids(); //先初始答题卡数据
        this.setData({ showexampop: true });
        this.getexamright();
    },

    onCloseexam() {
        this.setData({ showexampop: false });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

        baseUrl.islogin();
        console.log(options)
        if (options.index) {
            this.setData({
                index: options.index,
                reexam: 1
            });
        }

        if (options.now) {
            this.setData({
                now: options.now
            });
        }
        this.setData({
            coursetypefour_id: options.examid
        });

        this.start();
    },

    /**getcoursetypefourexam
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

        console.log("================");
        console.log(this.data.index);
        this.getcoursetypefourexam(this.data.coursetypefour_id, this.data.index);
        this.initadddata(this.data.itemdataall, this.data.coursetypefour_id, wx.getStorageSync('wxuserid'));
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    start: function () {

        let zstime = this.data.zstime;
        if (zstime == 0) {
            const countDown = this.selectComponent('.control-count-down');
            countDown.start();

        } else {

            this.zsstart();
        }
        this.setData({
            paystatus: 2
        })

    },
    pause() {
        let zstime = this.data.zstime;
        if (zstime == 0) {
            const countDown = this.selectComponent('.control-count-down');
            countDown.pause();

        } else {
            //   this.zsstop();
            this.zsstop();

            this.setData({
                showvide: true
            });

        }
        this.setData({
            paystatus: 1
        })

    },
    finished() {
        console.log("交卷")
    },
    collectionselect: function (e) {
        console.log(e);
        this.getcollectionclick(e.currentTarget.id, wx.getStorageSync('wxuserid'));
    },
    getcollectionclick: function (collection_id, user_id) {
        const that = this;
        let url = baseUrl.globalData.baseUrl + '/exam/examcollection';
        var param = {
            id: collection_id,
            user_id: user_id
        };
        //此处为使用封装的post请求
        util.get(url, param).then((res) => {
            console.log(res);
            that.setData({
                collection: res.data
            })

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },

    //-----------------------------
    //	手机触摸开始
    //-----------------------------
    touchStart: function (e) {
        //得到触摸点的坐标
        this.startX = e.changedTouches[0].x
        this.startY = e.changedTouches[0].y
        this.context = wx.createContext()
        this.context.setStrokeStyle(this.data.color)
        this.context.setLineWidth(this.data.pen)
        this.context.setLineCap('round') // 让线条圆润
        this.context.beginPath()

    },
    //-----------------------------
    //	触摸后移动
    //-----------------------------
    touchMove: function (e) {

        var startX1 = e.changedTouches[0].x
        var startY1 = e.changedTouches[0].y
        this.context.moveTo(this.startX, this.startY)
        this.context.lineTo(startX1, startY1)
        this.context.stroke()
        this.startX = startX1;
        this.startY = startY1;
        wx.drawCanvas({
            canvasId: 'myCanvas',
            reserve: true,
            actions: this.context.getActions()
        })
    },
    penSelect: function (e) {
        this.setData({
            pen: parseInt(e.currentTarget.dataset.param)
        });
        this.isClear = false;
    },
    colorSelect: function (e) {
        this.setData({
            color: e.currentTarget.dataset.param
        });
        this.isClear = false;
    },
    cleardraw: function (e) {
        this.setData({
            showModalStatus: false
        });
        this.setData({
            showModalStatus: true
        });
    },
    caogaoclick: function () {

        this.setData({
            showModalStatus: true,
        })
    },
    //-----------------------------
    //	草稿纸
    //-----------------------------
    shows: function () {
        const that = this;
        console.log(that.data.Draft_paper);
        that.data.Draft_paper = !that.data.Draft_paper;
        if (that.data.Draft_paper == false) {
            that.setData({
                Draft_paper: true,
            })
            this.util('open');
        } else {
            that.setData({
                Draft_paper: false,
                showModalStatus: false
            })
        }
    },
    util: function (currentStatu) {
        var animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 5,
        });
        this.animation = animation;
        animation.opacity(0).rotateX(-100).step();
        this.setData({
            animationData: animation.export()
        })
        setTimeout(function () {
            animation.opacity(1).rotateX(0).step();
            this.setData({
                animationData: animation
            })
            if (currentStatu == "close") {
                this.setData({
                    showModalStatus: false
                });
            }
        }.bind(this), 200)
        // 显示  
        if (currentStatu == "open") {
            this.setData({
                showModalStatus: true
            });
        }
    }, //-----------------------------
    //	究极的过度效果
    //-----------------------------
    guodu: function () {
        var animation = wx.createAnimation({
            timingFunction: "ease-in-out",
            delay: 15,
        });
        this.animation = animation;
        animation.opacity(0).translateY(-50).scale(0).step(150);
        this.setData({
            animationData: animation.export()
        })
        setTimeout(function () {
            animation.opacity(1).translateY(0).scale(1).step(100);
            this.setData({
                animationData: animation
            })
        }.bind(this), 150);
    },
    next: function (e) {

        const that = this;
        that.getids(); //增加没有选项数据
        that.guodu();
        const index = that.data.index - 0 + 1;
        console.log('------------');
        console.log(index);
        const all = that.data.all;
        if (index < all) {
            that.setData({
                index: index,
                now: index + 1,
                itemdata: that.data.itemdataall[index].examitem,
                itemdatacurrent: that.data.itemdataall[index],
                content: that.data.itemdataall[index].name.replace(/\<img/gi, '<img style="width:80%;height:auto"'),
                singdouble: that.data.itemdataall[index].examtype,
                paiduanactive: that.data.itemdataall[index].examtype,
                zstime: that.data.itemdataall[index].reverset,
                typeid: that.data.itemdataall[index].typeid
            });
            that.getcollectionclick(that.data.itemdatacurrent['id'], wx.getStorageSync('wxuserid'));


        } else {
            let examtype = this.data.singdouble;
            let typeid = this.data.typeid;
            let id = this.data.coursetypefour_id;
            let grouppaper_id = this.data.itemdatacurrent.grouppaper_id;
            console.log(typeid + ',=========');
            // wx.navigateTo({
            //     url: '/pages/daitika/daitika?id=' + id + '&grouppaper_id=' + grouppaper_id + '&typeid=' + typeid,
            // })
            this.setData({
                showexampop: true
            });
            this.getexamright();
            //   if(typeid==1){
            //     wx.navigateTo({
            //       url: '/pages/exampaper/exampaper?id='+id+'&grouppaper_id='+grouppaper_id,
            //     })
            //   }else{
            //     wx.navigateTo({
            //       url: '/pages/exampaper2/exampaper2?id='+id+'&grouppaper_id='+grouppaper_id,
            //     })
            //   }
        }
    },
    //-----------------------------
    //	上一个
    //-----------------------------
    prev: function (e) {

        let that = this;
        that.getids();
        that.guodu();
        var index = that.data.index - 1;

        if (index < 0) {
            return false;
        }

        that.setData({
            index: index,
            now: index + 1,
            itemdata: that.data.itemdataall[index].examitem,
            itemdatacurrent: that.data.itemdataall[index],
            content: that.data.itemdataall[index].name.replace(/\<img/gi, '<img style="width:80%;height:auto"'),
            singdouble: that.data.itemdataall[index].examtype,
            paiduanactive: that.data.itemdataall[index].examtype,
            zstime: that.data.itemdataall[index].reverset,
            typeid: that.data.itemdataall[index].typeid
        });
        that.getcollectionclick(that.data.itemdatacurrent['id'], wx.getStorageSync('wxuserid'));

    },
    //多选
    bindList(e) {
        this.getids();
        let index = e.currentTarget.dataset.id;
        console.log(index);
        let arr = this.data.itemdata.map(item => {
            if (item.id == index && item.selectvalue == "1") {
                item.selectvalue = "2";
            } else if (item.id == index) {
                item.selectvalue = "1";
            }
            return item
        })
        console.log(arr);
        this.setData({
            itemdata: arr
        });

    }, //获取id
    getids() {
        let ids = this.data.itemdata.filter(item => item.selectvalue == '2').map(item => item.charmu);
        let dx = this.data.itemdata.filter(item => item.selectvalue == '2').map(item => item.charmu);
        console.log(ids);
        console.log(dx);
        console.log('多选Id：' + ids)
        console.log('单选Id：' + dx);
        console.log(this.data.itemdatacurrent);
        let itemcurrent = this.data.itemdatacurrent;
        let user_id = wx.getStorageSync('wxuserid') == '' ? 3 : wx.getStorageSync('wxuserid');
        let examanswer = 1;
        if (itemcurrent.examtype == 1) {
            examanswer = dx + '';
        } else {
            examanswer = ids + '';
        }
        this.addexamdata(this.data.coursetypefour_id, itemcurrent.examtype, itemcurrent.typeid, itemcurrent.id, itemcurrent.itemname, examanswer, itemcurrent.answer, user_id, itemcurrent.grouppaper_id, this.data.index, this.data.now);

    },
    initadddata: function (params, coursetypefour_id, user_id) {
        //初始化答题卡数据 (1)

        console.log("===========----=============");
        console.log(params);
        let arr = params;
        arr.forEach((element, index) => {
            console.log(element);
            let itemcurrent = element;
            console.log(coursetypefour_id);
            console.log(index);
            console.log(arr.length);
            this.addexamdata(coursetypefour_id, itemcurrent.examtype, itemcurrent.typeid, itemcurrent.id, itemcurrent.itemname, '', itemcurrent.answer, user_id, itemcurrent.grouppaper_id, index, arr.length);
        });
        console.log("===========----=============");
    },
    bindActive: function (e) {

        let arr = this.data.itemdata.map(item => {
            if (item.id === e.currentTarget.dataset.id) {
                item.selectvalue = 2
            } else {
                item.selectvalue = 1
            }
            return item
        })
        this.setData({
            itemdata: arr
        });
        //  this.getids();
        this.next(this.data.now);
    },
    openactive: function (e) {
        console.log(e);
        let opendata = this.data.openactive;
        opendata = !opendata;
        console.log(opendata);
        this.setData({
            activeopen: opendata,
            openactive: opendata
        })

    },
    //开始
    zsstart: function () {
        var that = this;
        //停止（暂停）
        clearInterval(intt);
        //时间重置
        that.setData({
            hour: that.data.hour,
            minute: that.data.minute,
            second: that.data.second,
            millisecond: that.data.millisecond,
            paystatus: 2
        })
        intt = setInterval(function () { that.zstimer() }, 50);


    },
    //暂停
    zsstop: function () {
        clearInterval(intt);
    },
    //停止
    zsReset: function () {
        var that = this
        clearInterval(intt);
        that.setData({
            hour: 0,
            minute: 0,
            second: 0,
            millisecond: 0,
            timecount: '00:00:00',
        })
    },
    zstimer: function () {
        var that = this;
        // console.log(that.data.millisecond)
        that.setData({
            millisecond: that.data.millisecond + 5
        })
        if (that.data.millisecond >= 100) {
            that.setData({
                millisecond: 0,
                second: that.data.second + 1
            })
        }
        if (that.data.second >= 60) {
            that.setData({
                second: 0,
                minute: that.data.minute + 1
            })
        }

        if (that.data.minute >= 60) {
            that.setData({
                minute: 0,
                hour: that.data.hour + 1
            })
        }
        that.setData({
            timecount: that.data.hour + ":" + that.data.minute + ":" + that.data.second
        })
    },
    getcoursetypefourexam: function (params, index) {

        //得到练习题目
        const that = this;
        let url = baseUrl.globalData.baseUrl + '/exam/paperexamitemas';
        var param = {
            coursetypefour_id: params,
            user_id: wx.getStorageSync('wxuserid')
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {

            //  that.initadddata(res.data.item, params, wx.getStorageSync('wxuserid'));
            that.setData({
                itemdataall: res.data.item,
                itemdata: res.data.item[index].examitem,
                all: res.data.item.length,
                itemdatacurrent: res.data.item[index],
                content: res.data.item[index].name.replace(/\<img/gi, '<img style="width:80%;height:auto"'),
                singdouble: res.data.item[index].examtype,
                paiduanactive: res.data.item[index].examtype,
                zstime: res.data.reverset,
                typeid: res.data.typeid
            });
        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    addexamdata: function (coursetypefour_id, examtype, typeid, exam_id, itemname, answer, rightanswer, user_id, grouppaper_id, index, now) {

        //得到练习题目
        const that = this;
        let url = baseUrl.globalData.baseUrl + '/exam/examaddas';
        var param = {
            coursetypefour_id: coursetypefour_id,
            examtype: examtype,
            typeid: typeid,
            exam_id: exam_id,
            itemname: itemname,
            answer: answer,
            rightanswer: rightanswer,
            user_id: user_id,
            grouppaper_id: grouppaper_id,
            index: index,
            now: now
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {
            console.log(res);

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    subitexam: function () {
        let examtype = this.data.singdouble;
        let id = this.data.coursetypefour_id;
        let typeid = this.data.typeid;
        let grouppaper_id = this.data.itemdatacurrent.grouppaper_id;
        console.log(id);
        this.getids();
        // if (typeid == 1) {
        //     wx.navigateTo({
        //         url: '/pages/daitika/daitika?id=' + id + '&grouppaper_id=' + grouppaper_id,
        //     })
        // } else {
        //     wx.navigateTo({
        //         url: '/pages/exampaper2/exampaper2?id=' + id + '&grouppaper_id=' + grouppaper_id,
        //     })
        // }
        wx.redirectTo({
            url: '/pages/daitika/daitika?id=' + id + '&grouppaper_id=' + grouppaper_id + '&typeid=' + typeid,
        })

    },
    getexamright: function () {

        //弹出答题卡
        //得到练习题目
        const that = this;
        let url = baseUrl.globalData.baseUrl + '/exam/examuseransweras';
        let user_id = wx.getStorageSync('wxuserid') == '' ? 3 : wx.getStorageSync('wxuserid');
        var param = {
            coursetypefour_id: that.data.coursetypefour_id,
            user_id: user_id
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {
            console.log(res.data);
            that.setData({
                examlist: res.data.itemdata,
                examlistdata: res.data
            });

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    jumpitem: function (e) {

        console.log(e.currentTarget.dataset.id);
        const id = e.currentTarget.dataset.id;

        //得到练习题目
        const that = this;
        let url = baseUrl.globalData.baseUrl + '/exam/getexamasitem';
        var param = {
            id: id
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {
            console.log("aaaaaaaaaaaaaaaaaaaaaaaaaaa")
            console.log(res.data);
            // wx.navigateTo({
            //   url: '/pages/examing/examing?examid='+res.data.coursetypefour_id+'&index='+res.data.index+'&now='+res.data.now,
            // })
            that.setData({
                index: res.data.index,
                now: res.data.index - 0 + 1
            });

            that.getcoursetypefourexam(res.data.coursetypefour_id, res.data.index);

        }).catch((errMsg) => {
            console.log(errMsg);
        });
    },
    viewallexplain: function (params) {

        let typeid = this.data.typeid;
        let coursetypefour_id = this.data.coursetypefour_id;

        let currentdata=this.data.itemdatacurrent;
        console.log('currentdata========================');
        console.log(currentdata);
  
        let grouppaper_id = currentdata.grouppaper_id;

        console.log('grouppaper_id========================');
        console.log(grouppaper_id);
        console.log(this.data.examlist);
        let arr = [];
        arr = this.data.examlist;
        const arrstr = [];
        arr.forEach(element => {
            arrstr.push(element.id);
        });
        console.log(arrstr);
        let jsonstr = JSON.stringify(arr);
        this.examaddinnerdata(jsonstr);

        if (typeid == 1) {
            wx.navigateTo({
                url: '/pages/exampaper/exampaper?id=' + coursetypefour_id + '&grouppaper_id=' + grouppaper_id,
            })
        } else {
            wx.navigateTo({
                url: '/pages/exampaper2/exampaper2?id=' + coursetypefour_id + '&grouppaper_id=' + grouppaper_id,
            })
        }
    }, examaddinnerdata: function (listdata) {
        //传送数组参数，批量添加数据
        //得到练习题目
        const that = this;
        let url = baseUrl.globalData.baseUrl + '/exam/foreachexaminner';
        var param = {
            listdata: listdata
        };
        //此处为使用封装的post请求
        util.post(url, param).then((res) => {
            console.log(res.data);
        }).catch((errMsg) => {
            console.log(errMsg);
        });
    }


})