import { defineComponent, onMounted , ref, effect} from "vue";
import { string } from "vue-types";
import { useCompData } from ".";
import { useEditor } from "../../../..";
import { DesignComp } from "../../../../objects/DesignTemp/DesignComp";
import { View } from "../View";
import { CompUI } from "../..";

export const Component = defineComponent({
  props: {
    compId: string().isRequired,
  },
  setup(props) {
    const { helper, controls , store} = useEditor();
    const data = useCompData(props.compId);

    
    onMounted(()=>{
        // draw();
        effect(draw);
    })

    

    const canvasRef =  ref<HTMLCanvasElement>();
    function draw() {
        const canvas = canvasRef.value as HTMLCanvasElement;
        if (!canvas) return;

        const ctx = canvasRef.value?.getContext("2d") as CanvasRenderingContext2D;

        const width = data.layout.size[0];
        const height = data.layout.size[1];
        canvas.width = Math.ceil(Math.max(1, width));
        canvas.height = Math.ceil(Math.max(1, height));
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.lineWidth = data.value.lineWidth;
        ctx.strokeStyle = data.value.lineColor;

        if (data.value.reverseFill) {
          ctx.fillStyle = data.value.fillColor;
          ctx.fillRect(0, 0, canvas.width, canvas.height);
        }

        const padding = Math.max(10, data.value.lineWidth);
        ctx.beginPath();

        ctx.arc(width/2.0, height / 2.0, (Math.min(width,height) - padding)  / 2.0,  Math.PI / 180.0 * data.value.start,  Math.PI / 180.0 * data.value.end)
        if (data.value.isFill) {
            ctx.closePath();
        }
        ctx.stroke();
        if (data.value.isFill)    {
            let bColor = data.value.fillColor;
            if (!bColor) bColor = data.value.lineColor;
            ctx.fillStyle = bColor;
            if (data.value.reverseFill) {
              ctx.clip();
              // 将当前路径指定的区域颜色扣除
              ctx.globalCompositeOperation = "destination-out";
            }
            ctx.fill();
        }
    }

    
    return () => (
      <View compId={props.compId}>
         <canvas ref={canvasRef} style={{width:"100%", height: "100%"}}> </canvas>
      </View>
    );
  },
});
