import React, { Component } from 'react'
import { Button } from 'antd';
import { PageContainer } from '@ant-design/pro-components';
import QueenEngine, { kQueenBeautyType, kQueenBeautyParams, kQueenBeautyMakeupType, kQueenBeautyFaceShapeType, kQueenBeautyBlend, } from "../../queensdk"
import styles from './index.less';
import { EMsgid, tracker } from '@/utils/stat';
class CanvasPage extends Component {
  private queenEngine: any;
  private queenEnabled: boolean;
  private timer: any;
  private imageSource: any
  constructor(props: any) {
    super(props)
    this.queenEngine = null;
    this.timer = null;
    this.queenEnabled = true;
    this.imageSource = null;
    this.state = {

    }
  }

  queenInitialize = () => {
    const self = this;
    const startTime = performance.now();
    this.queenEngine = new QueenEngine();
    this.queenEngine.initialize("./", "", function () {
      tracker.queenInitReport({ ms: performance.now() - startTime });
      self.timer = window.setInterval(() => {
        self.renderEffect();
      }, 30);
    }, function (progress: number) {
      self.setState({ loadProgress: progress });
    });
  }

  queenEffect = () => {
    this.testBaseFaceBeauty();
    this.testAdvancedFaceBeauty();
  }

  componentDidMount() {
    tracker.actionReport(EMsgid.PAGELOAD);
    fetch("sample.png")//sample.png
      .then(r => r.blob())
      .then(createImageBitmap)
      .then(img => {
        this.imageSource = img;
        this.queenInitialize();
      });
  }

  componentWillUnmount() {
    this.queenEnabled = false;
    clearInterval(this.timer);
  }

  /**
   * 基础美颜
   */
  testBaseFaceBeauty() {
    this.queenEnabled = true;
    // 打开磨皮锐化功能开关
    this.queenEngine.setQueenBeautyType(kQueenBeautyType.SkinBuffing, true);
    // 设置磨皮系数
    this.queenEngine.setQueenBeautyParams(kQueenBeautyParams.SkinBuffing, 0.9);
    // 设置锐化系数
    this.queenEngine.setQueenBeautyParams(kQueenBeautyParams.Sharpen, 0.5);

    // 打开美白功能开关
    this.queenEngine.setQueenBeautyType(kQueenBeautyType.SkinWhiting, true);

    // 设置美白系数
    this.queenEngine.setQueenBeautyParams(kQueenBeautyParams.Whitening, 0.5);
  }

  /**
   * 高级美颜
   */
  testAdvancedFaceBeauty() {
    this.queenEnabled = true;
    //高级美颜
    this.queenEngine.setQueenBeautyType(kQueenBeautyType.FaceBuffing, true);
    // 设置去眼袋系数
    this.queenEngine.setQueenBeautyParams(kQueenBeautyParams.Pouch, 0.9);
    // 设置去法令纹系数
    this.queenEngine.setQueenBeautyParams(kQueenBeautyParams.NasolabialFolds, 0.9);
    // 设置白牙系数
    this.queenEngine.setQueenBeautyParams(kQueenBeautyParams.WhiteTeeth, 0.9);
    // 设置口红系数
    this.queenEngine.setQueenBeautyParams(kQueenBeautyParams.Lipstick, 0.2);
    // 设置腮红系数
    this.queenEngine.setQueenBeautyParams(kQueenBeautyParams.Blush, 0.1);
    // 设置口红色相系数
    this.queenEngine.setQueenBeautyParams(kQueenBeautyParams.LipstickColorParam, 0.1);
    // 设置口红饱和度系数
    this.queenEngine.setQueenBeautyParams(kQueenBeautyParams.LipstickGlossParam, 0.1);
    // 设置口红明度系数
    this.queenEngine.setQueenBeautyParams(kQueenBeautyParams.LipstickBrightnessParam, 0.1);
    // 设置亮眼系数
    this.queenEngine.setQueenBeautyParams(kQueenBeautyParams.BrightenEye, 0.9);
    // 设置红润系数
    this.queenEngine.setQueenBeautyParams(kQueenBeautyParams.SkinRed, 0.2);
    // 设置去皱纹系数
    this.queenEngine.setQueenBeautyParams(kQueenBeautyParams.Wrinkles, 0.9);
    // 设置去暗沉系数
    this.queenEngine.setQueenBeautyParams(kQueenBeautyParams.BrightenFace, 0.3);
  }

  //美型
  testFaceShape = () => {
    this.queenEnabled = true;
    // 打开美型功能开关
    this.queenEngine.setQueenBeautyType(kQueenBeautyType.FaceShape, true);
    // 设置大眼系数
    this.queenEngine.setFaceShape(kQueenBeautyFaceShapeType.BigEye, 1.0);
    //眼睛高度，值的范围[-1,1]，默认0
    this.queenEngine.setFaceShape(kQueenBeautyFaceShapeType.EyeTDAngle, 1.0);
    // 设置发际线系数
    this.queenEngine.setFaceShape(kQueenBeautyFaceShapeType.HairLine, 1.0);
    // 设置嘴角上扬(微笑)系数
    this.queenEngine.setFaceShape(kQueenBeautyFaceShapeType.Smile, 0.5);
    //削脸，值的范围[0,1]，默认0
    this.queenEngine.setFaceShape(kQueenBeautyFaceShapeType.CutFace, 0.5);
    //瘦脸，值的范围[0,1]，默认0
    this.queenEngine.setFaceShape(kQueenBeautyFaceShapeType.ThinFace, 0.5);
    //瘦鼻，值的范围[0,1]，默认0
    this.queenEngine.setFaceShape(kQueenBeautyFaceShapeType.ThinNose, 0.5);
    //下巴拉长，值的范围[-1,1]，默认0
    this.queenEngine.setFaceShape(kQueenBeautyFaceShapeType.LowerJaw, 1);
    //瘦下巴，值的范围[0,1]，默认0
    this.queenEngine.setFaceShape(kQueenBeautyFaceShapeType.HigherJaw, 1);

  }

  testFaceMakeup = () => {
    this.applyFaceMakeup();
  }

  async applyFaceMakeup() {
    this.queenEnabled = true;
    this.queenEngine.setQueenBeautyType(kQueenBeautyType.Makeup, true);
    // 设置美妆口红效果的透明度，目前female参数的值统一传YES/true，男性妆容还在优化中    
    const mouthMakeupPackageUrl = "queen_res/makeup/mouth_yaochun/shiliuhong.1.2.3.bin";
    await this.queenEngine.setMakeupWithPackage(kQueenBeautyMakeupType.Mouth, mouthMakeupPackageUrl, "1.2.3.png", kQueenBeautyBlend.LabMix);
    this.queenEngine.setMakeupAlphaWithType(kQueenBeautyMakeupType.Mouth, true, 0.3);

    // 设置美妆眉毛效果的透明度，目前female参数的值统一传YES/true，男性妆容还在优化中    
    const eyeBrowMakeupPackageUrl = "queen_res/makeup/eyebrow/biaozhunmei.2.3.bin";
    await this.queenEngine.setMakeupWithPackage(kQueenBeautyMakeupType.EyeBrow, eyeBrowMakeupPackageUrl, "biaozhunmei.2.3.png", kQueenBeautyBlend.Multiply);
    this.queenEngine.setMakeupAlphaWithType(kQueenBeautyMakeupType.EyeBrow, true, 0.3);

    //设置美妆睫毛效果的透明度，目前female参数的值统一传YES/true，男性妆容还在优化中    
    const eyeashMakeupUrl = "queen_res/makeup/eyelash/chenjing.2.3.png";
    await this.queenEngine.setMakeupWithUrl(kQueenBeautyMakeupType.Eyelash, eyeashMakeupUrl, kQueenBeautyBlend.Multiply);
    this.queenEngine.setMakeupAlphaWithType(kQueenBeautyMakeupType.Eyelash, true, 0.6);

    // 设置美妆腮红效果的透明度，目前female参数的值统一传YES/true，男性妆容还在优化中
    const blushMakeupUrl = "queen_res/makeup/blush/blush_wugu.2.3.png";
    await this.queenEngine.setMakeupWithUrl(kQueenBeautyMakeupType.Blush, blushMakeupUrl, kQueenBeautyBlend.LabMix);
    this.queenEngine.setMakeupAlphaWithType(kQueenBeautyMakeupType.Blush, true, 0.2);
  }

  /**
   * 开始美颜
   */
  applyEffect = () => {
    this.queenEffect();
  }

  /**
   * 增加头像贴纸
   */
  async addSticker() {
    this.queenEnabled = true;
    const sticker1 =  "queen_res/sticker/9.bin";
    await this.queenEngine.addMaterialWithUrl(sticker1);

    const sticker2 =  "queen_res/sticker/10.bin";
    await this.queenEngine.addMaterialWithUrl(sticker2);
  }

  /**
   * 设置滤镜效果
   */
  applyFilterEffect = () => {
    const self = this;
    this.queenEnabled = true;
    const filterUrl = "queen_res/lookups/A4.png";
    // 资源配置
    this.queenEngine.setLutImageUrl(filterUrl).then(function () {
      // 打开滤镜功能开关
      self.queenEngine.setQueenBeautyType(kQueenBeautyType.LUT, true);
      // 设置滤镜强度
      self.queenEngine.setQueenBeautyParams(kQueenBeautyParams.LUT, 0.5);
    });
  }

  /**
   * 头像贴纸
   */
  applyStickerEffect = () => {
    this.queenEnabled = true;
    this.addSticker();
  }

  /**
   * 背景虚化
   */
  bokehBackground = () => {
    this.queenEnabled = true;
    this.queenEngine.setSegmentBackgroundUrl("");
    this.queenEngine.enableBokehBackground(true);
  }

  /**
   * 背景抠图
   */
  cutoutBackground = () => {
    this.queenEnabled = true;
    let backgroundPath = "queen_res/background/b4.png";
    this.queenEngine.enableBokehBackground(false);
    this.queenEngine.setSegmentBackgroundUrl(backgroundPath).then(() => {
    });
  }

  /**
   * 美颜效果重置
   */
  resetEffect = () => {
    this.queenEnabled = false;
    this.queenEngine.setQueenBeautyType(kQueenBeautyType.SkinBuffing, false);
    this.queenEngine.setQueenBeautyType(kQueenBeautyType.SkinWhiting, false);
    this.queenEngine.setQueenBeautyType(kQueenBeautyType.FaceBuffing, false);
    this.queenEngine.setQueenBeautyType(kQueenBeautyType.FaceShape, false);
    this.queenEngine.setQueenBeautyType(kQueenBeautyType.Makeup, false);

    this.queenEngine.enableBokehBackground(false);
    this.queenEngine.setSegmentBackgroundUrl("").then(() => {
    });

    const sticker1 = "queen_res/sticker/9.bin";
    this.queenEngine.removeMaterialWithUrl(sticker1);

    const sticker2 = "queen_res/sticker/10.bin";
    this.queenEngine.removeMaterialWithUrl(sticker2);

    this.queenEngine.setLutImageUrl("").then(() => { });
  }

  renderEffect() {
    const canvas = document.getElementById('renderCanvas');
    canvas.width = this.imageSource.width;
    canvas.height =  this.imageSource.height

    if (this.queenEnabled) {
      let startTime = performance.now();
      this.queenEngine.renderWithMediaObject(this.imageSource, this.imageSource.width, this.imageSource.height, function (imageBufferData: any, imageWidth: number, imageHeight: number) {
        tracker.queenRenderReport({ ts: performance.now() - startTime });       
        const ctx = canvas?.getContext("2d");
        const imageBuffer = new Uint8ClampedArray(imageBufferData);
        const imageData = new ImageData(imageBuffer, imageWidth, imageHeight);
        if (ctx) {
          ctx.clearRect(0, 0, imageWidth, imageHeight);
          ctx.putImageData(imageData, 0, 0);
        }
      });
    } else {
      const ctx = canvas?.getContext("2d");
      if (ctx !== null) {
        ctx.drawImage(this.imageSource, 0, 0, this.imageSource.width, this.imageSource.height);
      }
    }
  }

  render() {
    return (
      <>
        <PageContainer>
          <div className=''>
            Image渲染，<a href='https://queen.aliyuncs.com' target='blank'>查看完整Demo</a>
          </div>
          <div className={styles.action}>
            <Button type="default" onClick={this.applyEffect} >美颜</Button>
            <Button type="default" onClick={this.testFaceShape} >美型</Button>
            <Button type="default" onClick={this.testFaceMakeup} >美妆</Button>
            <Button type="default" onClick={this.applyFilterEffect} >滤镜</Button>
            <Button type="default" onClick={this.bokehBackground} >背景虚化</Button>
            <Button type="default" onClick={this.cutoutBackground} >背景抠图</Button>
            <Button type="default" onClick={this.applyStickerEffect} >头像贴纸</Button>
            <Button type="default" onClick={this.resetEffect} >重置</Button>
          </div>
          <div className={styles.container}>
            <canvas id="renderCanvas" />
          </div>
        </PageContainer>
      </>
    );
  };
}
export default CanvasPage;
