/*
 * @Author: abson
 * @Date: 2022-02-16 15:36:47
 * @LastEditTime: 2022-02-28 16:01:07
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \MShopWeApp\packageB\pages\AI-test-skin\success_result\success_result.js
 */
// packageB/pages/AI-test-skin/success_result/success_result.js
const app = getApp();
const request = app.request;
const os = app.globalData;
const setting = os.setting;
const ut = require('../../../../utils/util');
//毛孔
const acne = require('acne/acne');
const blackhead = require('blackhead/blackhead');
const dark = require('dark/dark');
const pore = require('pore/pore');
const speckle = require('speckle/speckle');
const wrinkle = require('wrinkle/wrinkle');
const sensitive = require('sensitive/sensitive')
Page({
    /**
     * 页面的初始数据
     */
    data: {
        // tab: [{ id: 'zong_he', name: '综合肤质' }, { id: 'mao_kong', name: '毛孔' }, { id: 'hei_tou', name: '黑头' }, { id: 'se_ban', name: '色斑' }, { id: 'zhou_wen', name: '皱纹' }, { id: 'hei_yan_quan', name: '黑眼圈' }, { id: 'cuo_chuang', name: '痤疮' }, { id: 'min_gan_du', name: '敏感度' }],
        zhouwen_arr: [{ id: 1, name: '全部皱纹' }, { id: 2, name: '抬头纹' }, { id: 3, name: '川字纹' }, { id: 4, name: '眼周细纹' }, { id: 5, name: '鱼尾纹' }, { id: 6, name: '法令纹' }, { id: 7, name: '口周纹' }],
        cuochuang_arr: [{ id: 1, name: '全部痤疮' }, { id: 2, name: '粉刺 ' }, { id: 3, name: '痘印 ' }, { id: 4, name: '脓包' }, { id: 5, name: '结节' }],
        zhouwen_arr1: [{ id: 1, name: '皱纹/细纹', des: '是指皮肤受到外界环境影响，形成游离自由基，自由基破坏正常细胞膜组织内的胶原蛋白、活性物质，氧化细胞，或缺水而形成的小细纹，继而严重形成皱纹', sign: 'zhou1', sign1: 'zhou2' }, { id: 2, name: '抬头皱纹/抬头细纹', des: '位于额头的皱纹、细纹。形成原因因人而异，后天因素是比较少的。-般多为横纹， 竖纹较少见。', sign: 'zhou3', sign1: 'zhou4' }, { id: 3, name: '眼部皱纹/眼部细纹', des: '眼部皱纹、细纹一般位于下眼睑部位，多见于下脸内1/3处。', sign: 'zhou5', sign1: 'zhou6' }, { id: 4, name: '鱼尾纹', des: '眼部皱纹的一种，是在人两侧外眼角和登角之间出现的皱纹，其纹路与鱼尾巴上的纹路很相似，故被形象地称为鱼尾纹。', sign: 'zhou7', sign1: 'zhou8' }, { id: 5, name: '眉间纹', des: '又叫川字纹，皱眉纹，是面部的一种正常的表情纹，随着年龄的增长，面部的皱纹会逐渐加深，双眉之间逐渐形成了较深的皱折，会使人看起来总是愁眉不展。', sign: 'zhou9', sign1: 'zhou10' }, { id: 6, name: '泪沟', des: '泪沟是指由内眼角开始出现在下眼睑靠鼻侧的两条凹沟，是由于眼眶隔膜下缘的软组织萎缩、下垂而生成的。', sign: 'zhou11', sign1: 'zhou12' }, { id: 7, name: '法令纹', des: '法令纹是位于鼻翼边延伸而下的两道纹路，是典型的皮肤组织老化、造成肌肤表面凹陷的现象。', sign: 'zhou15', sign1: 'zhou16' }, { id: 8, name: '口角纹', des: '口角纹又称木偶纹、括号纹，位于嘴角延伸而下的两道纹路，是表情肌、重力和遗传基因等几方面因素综合形成的。', sign: 'zhou13', sign1: 'zhou14' }],
        cuochuang_arr1: [{ id: 1, name: '痘印，痘坑', des: '痤疮消退后留下的痕迹，- 般包括黑色痘印，红色痘印，凹洞性痘坑，增生性凸疤。', sign: 'cuo1', sign1: 'cuo2' }, { id: 2, name: '粉刺', des: '粉刺也称为白头，是毛囊漏斗部被角质层细胞堆积、堵塞，角化物质和皮脂充塞其中，形成白色丘疹，表面有表皮覆盖，与外界不相通，成为封闭式粉刺。(痤疮I级)', sign: 'cuo3', sign1: 'cuo4' }, { id: 3, name: '丘疹', des: '丘疹性痤疮是由皮损导致炎性弓|起的小米至豌豆大的坚硬的小丘疹，呈淡红色至深红色。丘疹中央可有一个黑头粉刺或顶端未变黑的皮脂栓。(痤疮II级)', sign: 'cuo5', sign1: 'cuo6' }, { id: 4, name: '结节囊肿', des: '表现为蚕豆至指甲大的炎性结节或囊肿，为重度痤疮，严重者可继发化脓感染、破溃流出血脓，后形成窦道及瘢痕。触摸有波动感。若面部相邻长着多个囊肿，可能通过皮下的“窦道"“暗通，可能需要手术解决。(痤疮IV级)', sign: 'cuo7', sign1: 'cuo8' }],
        heitanquan_arr: [{ id: 1, name: '综合情况' }, { id: 2, name: '左眼' }, { id: 3, name: '右眼' }],
        heitanquan_arr1: [{ id: 1, name: '色素性黑眼圈', des: '呈茶褐色，是因眼裂向外眼角的延伸段有色素沉着或因先天或外来刺激导致眼周肤色黯沉。', sign: 'hei1', sign1: 'hei2' }, { id: 2, name: '血管性黑眼圈', des: '呈青紫色，由于眼周血液循环不良，下眼脸处皮肤与皮下脂肪变薄，皮下血管透出颜色形成的。', sign: 'hei3', sign1: 'hei4' }, { id: 3, name: '阴影型黑眼圈', des: '表现为眼袋膨出、泪沟凹陷。由于年龄的增长，眼周皮肤肌肉都会变得松弛，脂肪量变化而引起。', sign: 'hei5', sign1: 'hei6' }],
        currentIndex: 0,
        scroll_index: 0,
        yiwen_index: 0,
        sex: 'female',  //female女 male男
        tab_id: 'zong_he',
        iurl: setting.imghost,
        showDialog: false,
        yanjing: true,  //显示皮肤问题
        img_scale: true, //问题标注放大图片
        heightRecord: [],
        img_scale_icon: true,
        show_problem: 1, //问题标注显示问题
        img_scale: 1, //缩放问题
        sex: '',
        is_esys_show: 0, //是不是显示眼睛
        scroll_id: 1, //初始为1

        wrinkle_num1: 0,  //抬头纹
        wrinkle_num2: 0, //川字纹
        wrinkle_num3: 0, //眼周细纹
        wrinkle_num4: 0, //鱼尾纹
        wrinkle_num5: 0, //法令纹
        wrinkle_num6: 0, //口周纹
        yiwen_type: 0,  //1皱纹 2黑眼圈 3痤疮
        acne_num1: 0, //粉刺
        acne_num2: 0, //痘印
        acne_num3: 0, //脓包
        acne_num4: 0, //结节


        login_set:{show_no:0}
    },

    onReady: function () {
        //用异步的获取比较准一点
        wx.getSystemInfo({
            success(res) {
                console.log(111);
                console.log(res.windowWidth);
                console.log(res.windowHeight);
            }
        })
    },

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

        var th = this;
        //初始化一下，获取商品的价格
        this.init();
        //var face_result=getApp().globalData.face_result;
        //var face_data=face_result.face_list[0];
        var id=options.id;
        var first_leader = options.first_leader;

        if (id == undefined || id == null || id == "") {
            var gid_str = decodeURIComponent(options.scene);
            gid_str = gid_str.split("_");
            id=gid_str[0];
            if (gid_str.length > 1) {
                first_leader = gid_str[1];
            }
        }

        //this.data.id=id;
        this.setData({id:id})
        if (first_leader) {
            console.log("log---".first_leader);
            getApp().globalData.first_leader = first_leader;
            //调用接口判断是不是会员
            getApp().request.promiseGet("/api/weshop/shoppingGuide/get/" + setting.stoid + "/" + first_leader, {}).then(res => {
                if (res.data.code == 0) {
                    getApp().globalData.guide_id = res.data.data.id;
                    getApp().globalData.guide_pick_id= res.data.data.pickup_id
                }
            })
        }

        //用异步的获取比较准一点
        wx.getSystemInfo({
            success(res) {
                //计算图片要显示的大小
                th.data.cWidth = res.windowWidth;
                th.data.cHeight = res.windowHeight;

                console.log(222);
                console.log(res.windowWidth);
                console.log(res.windowHeight);


                th.data.face_height = th.data.cHeight * 0.8 * 0.75;

                var bi1 = (th.data.cHeight * 0.8 * 0.8) / (th.data.cWidth * 0.8);
                th.get_data(function (json, json1, img) {
                    var key_arr=[];
                    //-- 数据先存着 --
                    var face_data = th.data.face_data = json.face_list[0];
                    var face_data1 = th.data.face_data1 = json1.face_list[0];
                    var sex = face_data1.gender.type;
                    //痤疮数
                    var acne_num = face_data.acnespotmole.acne_num;
                    //色斑数
                    var speckle_num = face_data.acnespotmole.speckle_num;
                    //皱纹数
                    var wrinkle_num = face_data.wrinkle.wrinkle_num;
                    //黑头数
                    var blackhead_num = face_data.blackheadpore.blackhead_num;
                    //毛孔数
                    var pore_num = face_data.blackheadpore.pore_num;
                    //黑眼圈的严重程度
                    var dark_type = face_data.eyesattr.dark_circle_left_type.length > 0 ? face_data.eyesattr.dark_circle_left_type[0] : -1;
                    var dark_type1 = face_data.eyesattr.dark_circle_right_type.length > 0 ? face_data.eyesattr.dark_circle_right_type[0] : -1;

                    var dk_type1 = dark_type;
                    var dk_type2 = dark_type1;
                    if (dark_type1 > dark_type) {
                        dark_type = dark_type1;
                    }

                    key_arr.push(35);
                    var skin_sensitive_check = parseInt(face_data.skinquality.skin_sensitive_check[0]);
                    switch(skin_sensitive_check){
                        case 0: key_arr.push(36); break;//耐受
                        case 1: key_arr.push(37); break;//中性
                        case 2: key_arr.push(38); break;//敏感
                    }
                    var skin_dryoil_check = face_data.skinquality.skin_dryoil_check;

                    var location = face_data.location;
                    var bili = th.data.face_height * 0.76 / location.height;

                    //获取眼睛的画图比例
                    var eye_data1 = face_data1.landmark150.eye_left_corner_right;
                    var eye_data2 = face_data1.landmark150.eye_left_corner_left;
                    var eye_data3 = face_data1.landmark150.eye_right_corner_right;

                    var hei1 = Math.abs(eye_data1.x - eye_data2.x);
                    var bili_eye = th.data.face_height * 0.56 / hei1;
                    var eye_top = eye_data1.y - hei1 / 2
                    var eye_left1 = eye_data1.x - hei1 / 6;
                    var eye_left2 = eye_data3.x - hei1 / 6;

                    var skin_dryoil_check_type = 0;//干性
                    var skin_dryoil_check_arr = []
                    for (let i in skin_dryoil_check) {
                        let item = skin_dryoil_check[i];
                        if (item != '1' && skin_dryoil_check_arr.indexOf(item) == -1) {
                            skin_dryoil_check_arr.push(item);
                        }
                    }
                    //皮肤干油性的判断
                    if (skin_dryoil_check_arr.length == 0) skin_dryoil_check_type = 1;
                    else if (skin_dryoil_check_arr.length == 1) skin_dryoil_check_type = parseInt(skin_dryoil_check_arr[0]);
                    else skin_dryoil_check_type = 3;


                    var wrinkle_types = face_data.wrinkle.wrinkle_types;
                    var w_arr = wrinkle_types.filter(function (e) {
                        return e == 1;
                    })
                    th.data.wrinkle_num1 = w_arr.length;

                    //皱纹的数量的统计
                    w_arr = wrinkle_types.filter(function (e) {
                        return e == 2;
                    })
                    th.data.wrinkle_num2 = w_arr.length;
                    w_arr = wrinkle_types.filter(function (e) {
                        return e == 3;
                    })
                    th.data.wrinkle_num3 = w_arr.length;
                    w_arr = wrinkle_types.filter(function (e) {
                        return e == 4;
                    })
                    th.data.wrinkle_num4 = w_arr.length;
                    w_arr = wrinkle_types.filter(function (e) {
                        return e == 5;
                    })
                    th.data.wrinkle_num5 = w_arr.length;
                    w_arr = wrinkle_types.filter(function (e) {
                        return e == 6;
                    })
                    th.data.wrinkle_num6 = w_arr.length;

                    //痘痘的不同的统计
                    var acne_list = face_data.acnespotmole.acne_list;
                    var a_arr = acne_list.filter(function (e) {
                        return e.type == 0;
                    })
                    th.data.acne_num1 = a_arr.length;
                    a_arr = acne_list.filter(function (e) {
                        return e.type == 1;
                    })
                    th.data.acne_num2 = a_arr.length;
                    a_arr = acne_list.filter(function (e) {
                        return e.type == 2;
                    })
                    th.data.acne_num3 = a_arr.length;
                    a_arr = acne_list.filter(function (e) {
                        return e.type == 3;
                    })
                    th.data.acne_num4 = a_arr.length;

                    let tab_arr = [{ id: 'zong_he', name: '综合肤质' }];
                    if (pore_num) {
                        tab_arr.push({ id: 'mao_kong', name: '毛孔' });
                        key_arr.push(30);
                    }
                    if (blackhead_num) {
                        tab_arr.push({ id: 'hei_tou', name: '黑头' });
                        key_arr.push(26);
                    }
                    if (speckle_num) {
                        tab_arr.push({ id: 'se_ban', name: '色斑' });
                        key_arr.push(13);
                    }
                    if (wrinkle_num) {
                        tab_arr.push({ id: 'zhou_wen', name: '皱纹' });
                        key_arr.push(2);
                    }
                    if (dark_type > -1) {
                        tab_arr.push({ id: 'hei_yan_quan', name: '黑眼圈' });
                        key_arr.push(18);

                        switch(dark_type){
                            case 0: key_arr.push(19); break;//黑眼圈-色素型
                            case 1: key_arr.push(20); break;//黑眼圈-阴影型
                            case 2: key_arr.push(21); break;//黑眼圈-血管型
                        }

                    }
                    if (acne_num) {
                        tab_arr.push({ id: 'cuo_chuang', name: '痤疮' });
                        key_arr.push(9);
                    }
                    tab_arr.push({ id: 'min_gan_du', name: '敏感度' });

                    if(th.data.wrinkle_num1){ key_arr.push(3); } //抬头纹
                    if(th.data.wrinkle_num2){ key_arr.push(4); } //川字纹
                    if(th.data.wrinkle_num3){ key_arr.push(5); } //眼周细纹
                    if(th.data.wrinkle_num4){ key_arr.push(6); } //鱼尾纹
                    if(th.data.wrinkle_num5){ key_arr.push(7); } //法令纹
                    if(th.data.wrinkle_num6){ key_arr.push(8); } //口周纹
                    if(th.data.acne_num1) { key_arr.push(10); } //粉刺
                    if(th.data.acne_num2) { key_arr.push(11); } //痘印
                    if(th.data.acne_num3) { key_arr.push(12); } //脓包
                    if(th.data.acne_num4) { key_arr.push(39); } //结节

                    if(!th.data.skin_key){
                        getApp().request.promisePut('/api/weshop/face/storeSkinface/update', {
                            is_json:1,
                            data: {
                                id:th.data.id,
                                skin_key:key_arr.join(","),
                                store_id:setting.stoid
                            },
                        });
                    }

                    th.setData({
                        acne_num: acne_num,
                        speckle_num: speckle_num,
                        wrinkle_num: wrinkle_num,
                        wrinkle_types: wrinkle_types,  //皱纹类型
                        blackhead_num: blackhead_num,
                        pore_num: pore_num,
                        dark_type: dark_type,
                        dark_typ1: dk_type1,
                        dark_type2: dk_type2,
                        skin_sensitive_check: skin_sensitive_check,
                        skin_dryoil_check: skin_dryoil_check,
                        skin_dryoil_check_type: skin_dryoil_check_type,
                        face_img: img,
                        m_top: (location.top - location.height / 3) * bili,
                        m_left: Math.abs(th.data.cWidth * 0.8 - (location.width + location.left * 2) * bili) / 2,
                        bili: bili,
                        bili_eye: bili_eye,
                        sex: sex,
                        tab: tab_arr,
                        skin_dryoil_check_type: skin_dryoil_check_type,
                        eye_top: eye_top * bili_eye,
                        eye_left1: eye_left1 * bili_eye,
                        eye_left2: eye_left2 * bili_eye,

                        wrinkle_num1: th.data.wrinkle_num1,  //抬头纹
                        wrinkle_num2: th.data.wrinkle_num2, //川字纹
                        wrinkle_num3: th.data.wrinkle_num3, //眼周细纹
                        wrinkle_num4: th.data.wrinkle_num4, //鱼尾纹
                        wrinkle_num5: th.data.wrinkle_num5, //法令纹
                        wrinkle_num6: th.data.wrinkle_num6, //口周纹

                        acne_num1: th.data.acne_num1, //粉刺
                        acne_num2: th.data.acne_num2, //痘印
                        acne_num3: th.data.acne_num3, //脓包
                        acne_num4: th.data.acne_num4, //结节
                    })

                    //调用推荐
                    if(getApp().globalData.user_id) th.recommend();


                    // let { heightRecord, tab } = th.data;
                    // tab.forEach(item => {
                    //     console.log(2);
                    //     var query = th.createSelectorQuery();
                    //     let class_name = `.${item['id']}`;
                    //     query.select(class_name).boundingClientRect(function (rect) {
                    //         // let ratio  = 750 / rect.width;
                    //         let height = parseInt(rect.height); //加上导航栏50px
                    //         heightRecord.push(height);
                    //         // item['top'] = top;
                    //     }).exec();
                    // });
                    // heightRecord.sort((a, b) => {
                    //     return a - b;
                    // });
                    // th.setData({
                    //     heightRecord,
                    // })
                    // setTimeout(() => {
                    //     heightRecord.sort((a, b) => {
                    //         return a - b;
                    //     })
                    //     let new_arr = [];
                    //     if (heightRecord.length > 0) {
                    //         heightRecord.reduce((pre, cur) => {
                    //             let sum = pre + cur;
                    //             new_arr.push(sum);
                    //             return sum;
                    //         })
                    //     }
                    //     th.setData({
                    //         heightRecord:new_arr,
                    //     })
                    // },1000)


                })
            }
        })

        //未登陆要显示登陆
        if(!getApp().globalData.user_id){
            wx.showToast({
                title: "您还未登陆，请先登陆",
                icon: 'none',
                duration: 3000
            })
            setTimeout(function () {
                th.setData({show_login:1})
            },1000)

        }

    },


    recommend:function () {
        var th=this;
        var sort = 1;
        //-- 调用毛孔的推荐函数 --
        if (th.data.pore_num > 0)
            pore.get_goods(th, setting.stoid, sort++);
        //-- 调用黑头的推荐函数 --
        if (th.data.blackhead_num > 0)
            blackhead.get_goods(th, setting.stoid, sort++);
        //-- 调用色斑的推荐函数 --
        if (th.data.speckle_num > 0)
            speckle.get_goods(th, setting.stoid, sort++);
        //-- 调用皱纹的推荐函数 --
        if (th.data.wrinkle_num > 0)
            wrinkle.get_goods(th, setting.stoid, sort++);
        //-- 黑眼圈 --
        if (th.data.dark_type > -1)
            dark.get_goods(th, setting.stoid, sort++);
        //-- 黑眼圈 --
        if (th.data.acne_num > -0)
            acne.get_goods(th, setting.stoid, sort++);
        sensitive.get_goods(th, setting.stoid, sort++);
        //-- 获取一下分享要用的图片 --
        th.set_share_img();
        //acne.get_goods(th, setting.stoid);
    },

    //-- 初始等级卡 --
    init: function () {
        var th = this;
        if (!getApp().globalData.user_id) return false;
        getApp().request.get("/api/weshop/users/get/" + setting.stoid + "/" + getApp().globalData.user_id, {
            isShowLoading: false,
            success: function (e) {
                if (e.data.code == 0 && e.data && e.data.data) {
                    getApp().globalData.userInfo = e.data.data;
                    getApp().getConfig2(function (e) {
                        var swithc_list = e.switch_list;
                        var sw_arr = JSON.parse(swithc_list);
                        //---如果后台有开等级卡的开关---
                        if (sw_arr.rank_switch && sw_arr.rank_switch == "2") {
                            th.setData({
                                rank_switch: true
                            });
                            //---回调卡的列表---
                            th.getPlusCardType(function (ob) {
                                th.setData({
                                    card_list: ob.card_list
                                });
                                var ti = setInterval(function () {
                                    var user = getApp().globalData.userInfo;
                                    if (!user) return false;
                                    clearInterval(ti);
                                    if (user.card_field && user['card_expiredate']) {
                                        var str = user['card_expiredate'].replace(/-/g, '/');
                                        var end = new Date(str);
                                        end = Date.parse(end) / 1000;
                                        var now = ut.gettimestamp();
                                        //--- 判断是等级会员，且在有效期范围内 ---
                                        if (user.card_field && now < end) {
                                            var card_name = ob.name_map.get(user.card_field);
                                            if ( card_name && card_name.length > 4) card_name = card_name.substring(0, 8);
                                            th.setData({
                                                card_field: user.card_field,
                                                card_name: card_name,
                                                card_list: ob.card_list
                                            });
                                        }
                                    }
                                }, 500)
                            })
                        }
                    })

                }
            }
        })
    },
    //-- 获取json数据 --
    get_data: function (func) {
        var th=this;
        var url = "/api/weshop/face/storeSkinface/get/" + setting.stoid + "/" + this.data.id;
        getApp().request.promiseGet(url, {}).then(res => {
            if (res.data.code == 0) {
                var json = JSON.parse(res.data.data.resultjson);
                var json1 = JSON.parse(res.data.data.detectjson);
                func(json, json1, res.data.data.img)
                if(res.data.data.skin_key) th.data.skin_key=res.data.data.skin_key;
            } else {
                getApp().showWarning("获取数据失败");
            }
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () { },
    set_share_img() {
        var th = this;
        var path3 = th.data.iurl + "/miniapp/images/skinimg/nan.png";
        if (this.data.sex == 'female')
            path3 = th.data.iurl + "/miniapp/images/skinimg/nv.png";
        // 读取文件成功则OK--
        wx.getImageInfo({
            src: path3,
            success: function (res) {
                //获取到二维码的图片
                th.data.share_head = res.path;
            }
        })

        var path4= th.data.iurl + "/miniapp/images/skinimg/m_logo.png";
        wx.getImageInfo({
            src: path4,
            success: function (res) {
                //获取到二维码的图片
                th.data.share_logo = res.path;
            }
        })



    },
    scroll_view(e) {
        let scrollTop = e.detail.scrollTop;
        let heightRecord = this.data.heightRecord;
        if (heightRecord.length === 0) return;
        let length = this.data.tab.length;
        var index = 0;
        if (scrollTop >= heightRecord[0]) {
            for (let i = 0; i < length; i++) {
                if (scrollTop >= heightRecord[i - 1] && scrollTop < heightRecord[i]) {
                    index = i;
                    break;
                }
            }
        }
        if (index !== this.data.currentIndex) {
            // let tab_id = this.data.tab[index].id;
            console.log(scrollTop);
            this.setData({
                scrollTop,
                // currentIndex: index,
            })
        }

    },

    click_scroll(e) {
        let { index, scroll_id } = e.currentTarget.dataset;
        this.setData({
            scroll_index: index,
            scroll_id,
        })

        //-- 如果是黑眼圈的控制 --
        if (this.data.show_type == 5) {
            switch (scroll_id) {
                case 1:
                    this.setData({ is_esys_show: 0 })
                    break;
                case 2:
                    this.setData({ is_esys_show: 1 })
                    break;
                default:
                    this.setData({ is_esys_show: 2 })
                    break
            }
        }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        getApp().check_can_share();
    },

    clickTab(e) {
        let { index, tab_id } = e.currentTarget.dataset;
        this.setData({
            currentIndex: index,
            tab_id,
        })
    },
    click_yanjing() {
        this.setData({
            yanjing: !this.data.yanjing,
        })
    },
    click_fangda() {
        this.setData({
            img_scale: !this.data.img_scale,
            img_scale_icon: !this.data.yanjing,
            ig_scale: 1, img_top: 0, img_left: 0
        })
    },

    click_yiwen_scroll(e) {
        let { index, yiwen_id } = e.currentTarget.dataset;
        this.setData({
            yiwen_index: index,
            yiwen_id,
        })
    },

    close_yiwen() {
        this.setData({
            question_dialog: false,
            yiwen_index: 0,
            yiwen_id: 'yiwen1'
        })
    },

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

    },

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

    },
    show_dailog(e) {
        var th = this;
        var type = parseInt(e.currentTarget.dataset.type);
        this.setData({
            showDialog: true, show_type: type, is_esys_show: 0, ig_scale: 1, img_top: 0, img_left: 0, scroll_index: 0, scroll_id: 1
        })
        switch (type) {
            case 1: //毛孔
                var pore_list = this.data.face_data.blackheadpore.circles.filter(function (e) {
                    return e.pore
                })
                this.setData({ pore_list: pore_list[0].pore });
                break;
            case 2://色斑
                var speckle_list = this.data.face_data.acnespotmole.speckle_list;
                this.setData({ speckle_list: speckle_list });
                break;
            case 3://皱纹
                var wrinkle_list = this.data.face_data.wrinkle.wrinkle_data;
                for (let i in wrinkle_list) {
                    let item = wrinkle_list[i];
                    item.map(function (e) {
                        e.w_type = th.data.wrinkle_types[i];
                        return e;
                    })
                }
                this.setData({ wrinkle_list: wrinkle_list });
                break;
            case 4://黑头
                var blackhead_list = this.data.face_data.blackheadpore.circles.filter(function (e) {
                    return e.blackhead
                })
                this.setData({ blackhead_list: blackhead_list[0].blackhead });
                break;
            case 5://黑眼圈
                var arr = this.data.face_data.eyesattr.dark_circle_left[0];
                var arr2 = this.data.face_data.eyesattr.dark_circle_right[0];
                var arr3 = [...arr, ...arr2];
                this.setData({ dark_list: arr3 });
                break;
            case 6://痤疮
                var acne_list = this.data.face_data.acnespotmole.acne_list;
                this.setData({ acne_list: acne_list });
                break;
            default:
                break
        }
    },

    close_dialog() {
        this.setData({
            showDialog: false,
            share_flag: false,
            img_scale: true,
        })
    },

    close_mask() {
        this.setData({
            showDialog: false,
            img_scale: true,
        })
    },

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

    },

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

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        getApp().globalData.no_clear=1;
        var url="packageD/pages/AI-test-skin/success_result/success_result?id="+this.data.id+"&first_leader="+getApp().globalData.user_id;

        var ob = {
            title: "测肤报告",
            path: url,
        };

        return ob;
    },

    //商品页面跳转
    go_url: function (e) {
        var url = e.currentTarget.dataset.url;
        getApp().goto(url);
    },

    //--- 获取卡类列表 ---
    getPlusCardType: function (func) {
        var storid = setting.stoid;
        var th = this;
        getApp().request.promiseGet("/api/weshop/plus/vip/mem/bership/list?" + "storeId=" + storid, {}).then(res => {

            if (res.data.code != 0 || !res.data.data) {
                var ob = {
                    "card_list": [],
                    "name_map": ""
                };
                func(ob);
                return false;
            }

            var plusCard = res.data.data;
            var arr = [1219, 2089, 3031];
            var new_arr = new Array();
            var card_name_map = new Map();

            var user = getApp().globalData.userInfo;
            if (plusCard) {
                for (var i = 0; i < plusCard.length; i++) {
                    if ((!user || user.card_field == null || user.card_field == "") && (plusCard[i].IsStopBuy == true)) {
                        continue;
                    }
                    var name = "card" + plusCard[i].CorrPrice.toLowerCase();
                    card_name_map.set(name, plusCard[i].CardName);
                    new_arr.push(plusCard[i]);

                }
            }
            var ob = {
                "card_list": new_arr,
                "name_map": card_name_map
            };
            func(ob);
        })
    },

    click_share() {
        this.setData({
            share_flag: true,
            img_scale: false,
            showDialog: true,
        })
    },

    //图片加载的时候，计算图片的像素大小
    face_img_load: function (e) {
        var th = this;
        var imgwidth = e.detail.width;
        var imgheight = e.detail.height;

        var w = th.data.cWidth * 0.8;
        this.setData({
            iwidth: imgwidth * th.data.bili,
            iheight: imgheight * th.data.bili,
            eye_w: imgwidth * th.data.bili_eye,
            eye_h: imgheight * th.data.bili_eye,
            bili1: w / imgwidth  //图片放大时候的比例
        })
    },

    //-- 图片的拖拽缩放的功能 --
    touchstartCallback: function (e) {
        this.data.tc_end = 0;
        // 单手指缩放开始，也不做任何处理
        if (e.touches.length > 1) {
            // 一开始我并没有这个回调函数，会出现缩小的时候有瞬间被放大过程的bug
            // 当两根手指放上去的时候，就将distance 初始化。
            let xMove = e.touches[1].clientX - e.touches[0].clientX;
            let yMove = e.touches[1].clientY - e.touches[0].clientY;
            let distance = Math.sqrt(xMove * xMove + yMove * yMove);
            this.data.img_distance = distance;
        } else if (e.touches.length == 1) {
            this.data.img_x = e.touches[0].clientX;
            this.data.img_y = e.touches[0].clientY;
        }

    },
    touchmoveCallback: function (e) {
        if (this.data.tc_end) return false;
        // 单手指缩放我们不做任何操作
        if (e.touches.length > 1) {
            let xMove = e.touches[1].clientX - e.touches[0].clientX;
            let yMove = e.touches[1].clientY - e.touches[0].clientY;
            // 新的 ditance
            let distance = Math.sqrt(xMove * xMove + yMove * yMove);
            let distanceDiff = distance - this.data.img_distance;

            let newScale = this.data.ig_scale + 0.005 * distanceDiff
            // 为了防止缩放得太大，所以scale需要限制，同理最小值也是
            if (newScale >= 2) {
                newScale = 2
            }
            if (newScale <= 0.6) {
                newScale = 0.6
            }

            this.data.img_distance = distance;
            // 赋值 新的 => 旧的
            this.setData({
                'ig_scale': newScale,
            })
        } else if (e.touches.length == 1) {
            let xMove = e.touches[0].clientX - this.data.img_x;
            let yMove = e.touches[0].clientY - this.data.img_y;
            this.setData({
                'img_top': yMove * 0.8,
                'img_left': xMove * 0.8,
            });
        }


    },
    touchendCallback: function (e) {
        this.data.tc_end = 1;

    },

    //--定义的保存图片方法，分享团---
    saveImageToPhotosAlbum: function () {
        var th = this;
        var rpx = this.data.cWidth / 750*1.7;  //基础单位，
        //--先判断会员状态--
        // var user_info = getApp().globalData.userInfo;
        // if (user_info == null || user_info.mobile == undefined || user_info.mobile == "" || user_info.mobile == null) {
        //     wx.navigateTo({ url: '/packageE/pages/togoin/togoin', })
        //     return false;
        // }

        if (this.data.share_hidden) {
            this.setData({ share_hidden: false, });
        }


        wx.showLoading({ title: '生成中...', })
        var that = this, th = that;
        //设置画板显示，才能开始绘图
        that.setData({ canvasHidden: false })

        var app = getApp();
        var scene = this.data.id + "";
        var user_id = getApp().globalData.user_id ? getApp().globalData.user_id : 0;
        if (user_id > 0) {
            scene += "_" + user_id;
        }
        ///二微码
        var path3 = setting.url + "/api/wx/open/app/user/getWeAppEwm/" +
            setting.stoid + "?sceneValue=" + scene + "&pageValue=packageD/pages/AI-test-skin/success_result/success_result";
        
        // 读取文件成功则OK--
        wx.getImageInfo({
            src: path3,
            success: function (res) {

                var b = 0.9;
                //获取到二维码的图片
                var vpath = res.path;
                var context = wx.createCanvasContext('share');
                // 先画背景
                context.fillStyle = '#ebf6f8';
                // 灰色实心矩形
                // 1. 语法： x坐标, y坐标, 宽度, 高度
                context.fillRect(0, 0, 750 * rpx, 1093 * rpx);

                context.drawImage(th.data.share_logo, 31 * b * rpx, 20 * b * rpx, 242 * b * rpx, 34 * b * rpx);

                context.setFillStyle("#00d8e9")
                context.setFontSize(12 * rpx)
                context.fillText("官方检测认证", 32 * b * rpx, 90 * b * rpx);

                //两个底部颜色
                context.fillStyle = '#a7ecf5';
                context.fillRect(31 * b * rpx, 130 * b * rpx, 196 * b * rpx, 18 * b * rpx);
                context.fillRect(31 * b * rpx, 174 * b * rpx, 196 * b * rpx, 18 * b * rpx);

                context.setFontSize(31 * b * rpx)
                context.setFillStyle("#070609")
                context.fillText("我的肌底强韧", 32 * b * rpx, 134 * b * rpx);
                context.fillText("肌肤鲜活润泽", 32 * b * rpx, 180 * b * rpx);

                //先画一个圆形
                th.circle(context, 98 * b * rpx, 230 * b * rpx, 140 * b * rpx, "#e7f3f8");
                th.circle(context, 118 * b * rpx, 250 * b * rpx, 120 * b * rpx, "#c8f2fa");
                //绘制人脸
                context.drawImage(th.data.share_head, 122 * b * rpx, 266 * b * rpx, 225 * b * rpx, 225 * b * rpx);

                //左右俩个框并填充文字
                th.darwRoundRect(38 * b * rpx, 290 * b * rpx, 120 * b * rpx, 34 * b * rpx, 17 * b * rpx, context);
                th.darwRoundRect(324 * b * rpx, 290 * b * rpx, 120 * b * rpx, 34 * b * rpx, 17 * b * rpx, context);
                context.setFontSize(18 * b * rpx)
                context.setFillStyle("black")
                context.fillText("黑眼圈 重度", 50 * b * rpx, 313 * b * rpx);
                context.fillText("毛孔 " + th.data.pore_num, 340 * b * rpx, 313 * b * rpx);

                //左右俩个框并填充文字
                th.darwRoundRect(40 * b * rpx, 362 * b * rpx, 90 * b * rpx, 34 * b * rpx, 17 * b * rpx, context);
                th.darwRoundRect(348 * b * rpx, 362 * b * rpx, 100 * b * rpx, 34 * b * rpx, 17 * b * rpx, context);
                context.setFillStyle("black")
                context.fillText("黑头 " + th.data.blackhead_num, 60 * b * rpx, 384 * b * rpx);
                context.fillText("色斑 " + th.data.speckle_num, 362 * b * rpx, 384 * b * rpx);

                //左右俩个框并填充文字
                th.darwRoundRect(50 * b * rpx, 440 * b * rpx, 116 * b * rpx, 34 * b * rpx, 17 * b * rpx, context);
                th.darwRoundRect(318 * b * rpx, 440 * b * rpx, 116 * b * rpx, 34 * b * rpx, 17 * b * rpx, context);
                context.setFillStyle("black")
                context.fillText("皱纹 " + th.data.wrinkle_num, 74 * b * rpx, 462 * b * rpx);
                context.fillText("痤疮 " + th.data.acne_num, 350 * b * rpx, 462 * b * rpx);

                //底部的绘制
                th.darwRoundRect(38 * b * rpx, 532 * b * rpx, 412 * b * rpx, 150 * b * rpx, 10 * b * rpx, context);
                //绘制二维码
                context.drawImage(vpath, 60 * b * rpx, 547 * b * rpx, 116 * b * rpx, 116 * b * rpx);
                context.setFillStyle("black")
                context.setFontSize(27 * b * rpx)
                context.fillText("美肤管家AI测肤", 200 * b * rpx, 600 * b * rpx);
                context.setFontSize(19 * b * rpx)
                context.fillText("科学了解皮肤的真实状态", 200 * b * rpx, 640 * b * rpx);

                //把画板内容绘制成图片，并回调 画板图片路径
                context.draw(false, function () {
                    setTimeout(function () {
                        wx.canvasToTempFilePath({
                            x: 0,
                            y: 0,
                            width: 750,
                            height: 1093,
                            destWidth: 1.2 * 750 * 750/that.data.cWidth,
                            destHeight: 1.2 * 1093 * 750/that.data.cWidth,
                            canvasId: 'share',
                            success: function (res) {
                                that.setData({
                                    shareImgPath: res.tempFilePath,
                                    canvasHidden: true,
                                    share_show: 1
                                })
                                /*--
                                wx.previewImage({
                                   //将图片预览出来
                                   ur--*/

                                wx.hideLoading();
                            }
                        })
                    }, 500)

                });

            },
            fail: function (res) {
                console.log(res);
                wx.hideLoading();
            }
        });
    },


    // 圆形图片
    circle: function (ctx, x, y, r, color) {
        ctx.save()
        ctx.beginPath();
        var cx = x + r;
        var cy = y + r;
        ctx.arc(cx, cy, r, 0, 2 * Math.PI);
        ctx.clip();
        ctx.fillStyle = color;
        ctx.fillRect(x, y, 2 * r, 2 * r);
        ctx.restore()
        ctx.closePath();
    },

    /**
     * 绘制圆角矩形
     * @param {*} x 起始点x坐标
     * @param {*} y 起始点y坐标
     * @param {*} w 矩形宽
     * @param {*} h 矩形高
     * @param {*} r 圆角半径
     * @param {*} ctx 画板上下文
     */
    darwRoundRect(x, y, w, h, r, ctx) {
        ctx.save()
        ctx.beginPath()

        // 左上弧线
        ctx.arc(x + r, y + r, r, 1 * Math.PI, 1.5 * Math.PI)
        // 左直线
        ctx.moveTo(x, y + r)
        ctx.lineTo(x, y + h - r)
        // 左下弧线
        ctx.arc(x + r, y + h - r, r, 0.5 * Math.PI, 1 * Math.PI)
        // 下直线
        ctx.lineTo(x + r, y + h)
        ctx.lineTo(x + w - r, y + h)
        // 右下弧线
        ctx.arc(x + w - r, y + h - r, r, 0 * Math.PI, 0.5 * Math.PI)
        // 右直线
        ctx.lineTo(x + w, y + h - r)
        ctx.lineTo(x + w, y + r)
        // 右上弧线
        ctx.arc(x + w - r, y + r, r, 1.5 * Math.PI, 2 * Math.PI)
        // 上直线
        ctx.lineTo(x + w - r, y)
        ctx.lineTo(x + r, y)

        ctx.setFillStyle('white')
        ctx.fill()
    },
    close_share: function () {
        this.setData({ share_show: 0 })
    },
    // 保存图片到手机
    savePic() {
        var self = this;
        // 获取用户的当前设置，返回值中有小程序已经向用户请求过的权限
        this.getSetting().then((res) => {
            // 判断用户是否授权了保存到相册的权限，如果没有发起授权
            if (!res.authSetting['scope.writePhotosAlbum']) {
                this.authorize().then(() => {
                    // 同意授权后保存下载文件
                    this.saveImage(self.data.shareImgPath)
                        .then(() => {
                            self.setData({
                                share_show: false
                            });
                        });
                })
            } else {
                // 如果已经授权，保存下载文件
                this.saveImage(self.data.shareImgPath)
                    .then(() => {
                        self.setData({
                            share_show: false
                        });
                    });
            }

        })
    },
    // 获取用户已经授予了哪些权限
    getSetting() {
        return new Promise((resolve, reject) => {
            wx.getSetting({
                success: res => {
                    resolve(res)
                }
            })
        })
    },
    // 发起首次授权请求
    authorize() {
        // isFirst 用来记录是否为首次发起授权，
        // 如果首次授权拒绝后，isFirst赋值为1
        let isFirst = wx.getStorageSync('isFirst') || 0;
        return new Promise((resolve, reject) => {
            wx.authorize({
                scope: 'scope.writePhotosAlbum',
                // 同意授权
                success: () => {
                    resolve();
                },
                // 拒绝授权,这里是用户拒绝授权后的回调
                fail: res => {
                    if (isFirst === 0) {
                        wx.setStorageSync('isFirst', 1);
                        wx.showToast({
                            title: '保存失败',
                            icon: 'none',
                            duration: 1000
                        })
                    } else {
                        this.showModal();
                    }
                    console.log('拒绝授权');
                    reject();
                }
            })
        })
    },
    // 保存图片到系统相册
    saveImage(saveUrl) {
        var self = this;
        return new Promise((resolve, reject) => {
            wx.saveImageToPhotosAlbum({
                filePath: saveUrl,
                success: (res) => {
                    wx.showToast({
                        title: '保存成功',
                        duration: 1000,
                    });
                    resolve();
                },
                fail: () => {
                    wx.showToast({
                        title: '保存失败',
                        duration: 1000,
                    });
                }
            })
        })
    },

    show_yiwen_dialog(e) {
        let yiwen_type = e.currentTarget.dataset.yiwen_type;
        this.setData({
            question_dialog: true,
            yiwen_type,
        })
    },

    //-----领取券-----
    get_quan: function (e) {

        var cid = e.currentTarget.dataset.cid;
        var index = e.currentTarget.dataset.ind;
        var q_word = e.currentTarget.dataset.word;
        var item = this.data[q_word][index];

        //--先判断会员状态--
        var user_info = getApp().globalData.userInfo;
        if (user_info == null || user_info.mobile == undefined || user_info.mobile == "" || user_info.mobile == null) {
            wx.navigateTo({
                url: '/packageE/pages/togoin/togoin',
            })
            return false;
        }


        //如果券还在领取中，不能再点
        if (item.linging == 1) {
            getApp().my_warnning('领取中..', 0, this);
            return false;
        }

        //如果领取的次数到了
        if (item.everyone_num > 0 && item.lqnum >= item.everyone_num) {
            getApp().my_warnning('领取失败，您已领完该券', 0, this);
            return false;
        }

        var lq_num = item.lqnum;

        var pdata = {
            'uid': getApp().globalData.user_id,
            'cid': cid,
            'store_id': setting.stoid,
            'type': 5,
            'skinface_id':this.data.id
        };

        //-- 导购ID --
        if (getApp().globalData.guide_id) {
            pdata.guide_id = getApp().globalData.guide_id;
        }

        var app = getApp(), th = this;
        wx.showLoading();
        app.request.post("/api/weshop/couponList/saveCouponList", {
            data: pdata,
            success: function (res) {
                wx.hideLoading();
                if (res.data.code == 0) {
                    app.my_warnning("领取成功", 1, th);

                    //点击量的保存
                    getApp().request.promisePost("/api/weshop/face/skinGoodsBrowse/save",{
                        data:{
                            store_id:setting.stoid,
                            goods_id:cid,
                            user_id:getApp().globalData.user_id,
                            addtime:ut.gettimestamp(),
                            skinface_id:th.data.id,
                            goods_type:2
                        }
                    }).then(res=>{})

                    lq_num++;
                    var text = q_word + "[" + index + "].lqnum";
                    var text2 = q_word + "[" + index + "].linging";
                    var obj = {};
                    obj[text] = lq_num;
                    obj[text2] = 0;
                    th.setData(obj);
                } else {
                    app.confirmBox(res.data.msg);
                    var text2 = q_word + "[" + index + "].linging";
                    var obj = {};
                    obj[text2] = 0;
                    th.setData(obj);
                }
            }
        })
    },


    clos_login:function () {
        this.setData({show_login:0});
        //调用推荐
        if(getApp().globalData.user_id) this.recommend();
    }



})