import * as yolo from '../src/yolo';
import * as detect from '../src/detect';
import * as align from '../src/align';
import { genFeedData } from '@paddlejs-mediapipe/data-processor';
import cal from './compare';
import map from './map';
const modelPathPrefix = 'https://paddlejs.cdn.bcebos.com/models/'
// const modelPathPrefix = ''
export async function load() {
    // const yoloRunner = await yolo.load({
    //     path: modelPathPrefix + 'tiny_yolo/model.json',
    //     mean: [117.001 / 255, 114.697 / 255, 97.404 / 255],
    //     // std: [0.229, 0.224, 0.225]
    // });

    console.log('start load ========');
    const detectRunner = async function () {
        await detect.load({
            path: modelPathPrefix + 'detect_face/model.json'
            // path: 'detect_new/model.json'
        });
    };

    const alignRunner = async function () {
        await align.load({
            path: modelPathPrefix + 'align_paddle_slice/model.json',
            // path: modelPathPrefix + 'freeze_align/model.json',
            mean: [0.5, 0.5, 0.5],
            // std: [0.229, 0.224, 0.225]
        });
    };

    return Promise.all([detectRunner(), alignRunner()]);
}

export async function run(input: HTMLElement, callback: Function, index: number, base: number = 80) {
    console.log('input')
    const res = await detect.classify(input) as ImageData;

    if (!res || !res.data || !res.data.length) {
        // return 0;
        callback(0);
        return;
    }

    const outSize = 128;
    const feedData = genFeedData(res, {
        targetShape: [1, 3, outSize, outSize],
        mean: [0.5, 0.5, 0.5]
    });
    const final = await align.predict(feedData);

    console.log(final, 'final1')

    // 计算新框
    let xmin = 0,
        xmax = 0,
        ymin = 0,
        ymax = 0;

    const ctx = detect.getCanvasContext();
    // const canvasDiv = document.createElement('canvas') as HTMLCanvasElement;

    for (let i = 0; i < 72; i++) {
        const [x, y] = final[i];
        ctx.beginPath();
        ctx.arc(x, y, 0.5, 0, 360, false);
        ctx.fillStyle="red";//填充颜色,默认是黑色
        ctx.fill();//画实心圆
        ctx.closePath();

        xmin = Math.min(x, xmin);
        xmax = Math.max(x, xmax);
        ymin = Math.min(y, ymin);
        ymax = Math.max(y, ymax);
    }

    // const twiceData = detect.getFinalPos([xmin, ymin, xmax, ymax], [128, 128], [128, 128], input);

    // const feedData2 = genFeedData(twiceData, {
    //     targetShape: [1, 3, outSize, outSize],
    //     mean: [0.5, 0.5, 0.5]
    // });
    // const final2 = await align.predict(feedData2);

    // console.log(final2, 'final2')

    // 画出点

    console.log('align complete');

    const dataArr = cal(final);
    if (!dataArr || !dataArr.length) {
        // return 0;
        callback(0);
        return;
    }

    const features = map[index];

    console.log(JSON.stringify(features), 'features======');

    // score 从50 -> 100    feature按length占比
    const featureIndexArr = Object.keys(features);
    const featureIndexArrLen = featureIndexArr.length;
    // 几项满足
    let count = 0;


    const text = document.createElement('div');
    text.innerText = `
    左眼: ${!dataArr[0] ? '闭' : '睁'},
    右眼: ${!dataArr[1] ? '闭' : '睁'},
    嘴: ${!dataArr[6] ? '闭' : '张'}
    `;
    // document.getElementById('result').appendChild(text);
    for (let i = 0, len = featureIndexArrLen; i < len; i++) {
        const cur = featureIndexArr[i];
        if (+cur === 0
            && (
                +features[cur] === +dataArr[0]
                || +features[cur] === +dataArr[1]
        )) {
            count++;
            continue;
        }
        else if (+cur === 4 && (+dataArr[4] || +dataArr[5])) {
            count++;
            continue;
        }

        else if (+cur === 7 && (+dataArr[7] === 1 && +dataArr[8] === 1)) {
            count++;
            continue;
        }
        (+features[cur] === +dataArr[cur]) && count++;
    }

    console.log(count, 'right count num======');

    // return 60 + 30 * (count / featureIndexArrLen) + Math.random() * 5;
    let score = 61 + 30 * (count / featureIndexArrLen);

    console.log(base, 'base score line======');
    console.log(score, 'real score======');
    score = score < (base || 80) ? (49 + Math.random() * 30) : (score + Math.random() * 5);
    console.log(score, 'final score======');
    callback(score);
}