package com.draw.painting.line.ui;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

public class DeerVectorDrawView extends View {
    
    // 线条画笔
    private Paint strokePaint;
    private Paint strokePaintThin;
    private Paint strokePaintMedium;
    
    // 填充画笔
    private Paint fillPaint;
    private Paint eyeFillPaint;
    private Paint noseFillPaint;
    private Paint blushPaint;
    
    // 路径列表（按动画顺序）
    private List<PathData> allPaths = new ArrayList<>();
    
    // 动画进度
    private float animationProgress = 0f;
    private boolean isAnimating = false;
    private ValueAnimator mainAnimator;
    
    // 原始 SVG viewBox: 0 0 400 500
    private static final float SVG_WIDTH = 400f;
    private static final float SVG_HEIGHT = 500f;
    
    public DeerVectorDrawView(Context context) {
        super(context);
        init();
    }
    
    public DeerVectorDrawView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    
    public DeerVectorDrawView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    
    private void init() {
        float density = getContext().getResources().getDisplayMetrics().density;
        
        // 主线条画笔 (stroke-width="4" -> 4 * density)
        strokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        strokePaint.setStyle(Paint.Style.STROKE);
        strokePaint.setColor(0xFF3D3028); // #3d3028
        strokePaint.setStrokeWidth(4f * density);
        strokePaint.setStrokeCap(Paint.Cap.ROUND);
        strokePaint.setStrokeJoin(Paint.Join.ROUND);
        
        // 细线条画笔 (stroke-width="2.5")
        strokePaintMedium = new Paint(strokePaint);
        strokePaintMedium.setStrokeWidth(2.5f * density);
        
        // 更细线条画笔 (stroke-width="1.5")
        strokePaintThin = new Paint(strokePaint);
        strokePaintThin.setStrokeWidth(1.5f * density);
        
        // 填充画笔（背景色）
        fillPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        fillPaint.setStyle(Paint.Style.FILL);
        fillPaint.setColor(0xFFFFFEFA); // #fffefa
        
        // 眼睛/鼻子填充
        eyeFillPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        eyeFillPaint.setStyle(Paint.Style.FILL);
        eyeFillPaint.setColor(0xFF3D3028); // #3d3028
        
        noseFillPaint = new Paint(eyeFillPaint);
        
        // 腮红画笔
        blushPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        blushPaint.setStyle(Paint.Style.FILL);
        blushPaint.setColor(0x99F5B5B5); // #f5b5b5 with opacity 0.6
        
        createPaths();
    }
    
    private void createPaths() {
        allPaths.clear();
        
        // ========== 1. 鹿角 (最先画) ==========
        // 左鹿角 - 主幹
        Path leftAntlerMain = new Path();
        leftAntlerMain.moveTo(145, 120);
        leftAntlerMain.quadTo(140, 100, 130, 75);
        leftAntlerMain.quadTo(125, 55, 115, 35);
        allPaths.add(new PathData(leftAntlerMain, strokePaint, PathType.STROKE, 0f));
        
        // 左鹿角 - 分叉1
        Path leftAntlerBranch1 = new Path();
        leftAntlerBranch1.moveTo(130, 75);
        leftAntlerBranch1.quadTo(115, 70, 100, 55);
        allPaths.add(new PathData(leftAntlerBranch1, createStrokePaint(3.5f), PathType.STROKE, 0.05f));
        
        // 左鹿角 - 分叉2
        Path leftAntlerBranch2 = new Path();
        leftAntlerBranch2.moveTo(125, 60);
        leftAntlerBranch2.quadTo(110, 50, 95, 35);
        allPaths.add(new PathData(leftAntlerBranch2, createStrokePaint(3f), PathType.STROKE, 0.08f));
        
        // 左鹿角 - 分叉3
        Path leftAntlerBranch3 = new Path();
        leftAntlerBranch3.moveTo(135, 85);
        leftAntlerBranch3.quadTo(120, 88, 105, 80);
        allPaths.add(new PathData(leftAntlerBranch3, createStrokePaint(3f), PathType.STROKE, 0.1f));
        
        // 右鹿角 - 主幹
        Path rightAntlerMain = new Path();
        rightAntlerMain.moveTo(255, 120);
        rightAntlerMain.quadTo(260, 100, 270, 75);
        rightAntlerMain.quadTo(275, 55, 285, 35);
        allPaths.add(new PathData(rightAntlerMain, strokePaint, PathType.STROKE, 0.12f));
        
        // 右鹿角 - 分叉1
        Path rightAntlerBranch1 = new Path();
        rightAntlerBranch1.moveTo(270, 75);
        rightAntlerBranch1.quadTo(285, 70, 300, 55);
        allPaths.add(new PathData(rightAntlerBranch1, createStrokePaint(3.5f), PathType.STROKE, 0.15f));
        
        // 右鹿角 - 分叉2
        Path rightAntlerBranch2 = new Path();
        rightAntlerBranch2.moveTo(275, 60);
        rightAntlerBranch2.quadTo(290, 50, 305, 35);
        allPaths.add(new PathData(rightAntlerBranch2, createStrokePaint(3f), PathType.STROKE, 0.18f));
        
        // 右鹿角 - 分叉3
        Path rightAntlerBranch3 = new Path();
        rightAntlerBranch3.moveTo(265, 85);
        rightAntlerBranch3.quadTo(280, 88, 295, 80);
        allPaths.add(new PathData(rightAntlerBranch3, createStrokePaint(3f), PathType.STROKE, 0.2f));
        
        // ========== 2. 耳朵 ==========
        // 左耳
        Path leftEar = new Path();
        leftEar.moveTo(135, 130);
        leftEar.quadTo(115, 120, 100, 135);
        leftEar.quadTo(110, 150, 130, 155);
        allPaths.add(new PathData(leftEar, strokePaintMedium, PathType.STROKE, 0.25f));
        
        // 左耳内部
        Path leftEarInner = new Path();
        leftEarInner.moveTo(125, 135);
        leftEarInner.quadTo(115, 135, 112, 142);
        Paint leftEarInnerPaint = createStrokePaint(1.5f);
        leftEarInnerPaint.setAlpha(153); // 0.6 opacity
        allPaths.add(new PathData(leftEarInner, leftEarInnerPaint, PathType.STROKE, 0.28f));
        
        // 右耳
        Path rightEar = new Path();
        rightEar.moveTo(265, 130);
        rightEar.quadTo(285, 120, 300, 135);
        rightEar.quadTo(290, 150, 270, 155);
        allPaths.add(new PathData(rightEar, strokePaintMedium, PathType.STROKE, 0.3f));
        
        // 右耳内部
        Path rightEarInner = new Path();
        rightEarInner.moveTo(275, 135);
        rightEarInner.quadTo(285, 135, 288, 142);
        Paint rightEarInnerPaint = createStrokePaint(1.5f);
        rightEarInnerPaint.setAlpha(153);
        allPaths.add(new PathData(rightEarInner, rightEarInnerPaint, PathType.STROKE, 0.33f));
        
        // ========== 3. 头部轮廓 ==========
        Path head = new Path();
        head.moveTo(130, 155);
        head.quadTo(125, 175, 130, 200);
        head.quadTo(135, 230, 150, 255);
        head.quadTo(165, 280, 175, 300);
        head.quadTo(185, 315, 200, 320);
        head.quadTo(215, 315, 225, 300);
        head.quadTo(235, 280, 250, 255);
        head.quadTo(265, 230, 270, 200);
        head.quadTo(275, 175, 270, 155);
        head.quadTo(260, 135, 240, 125);
        head.quadTo(220, 118, 200, 118);
        head.quadTo(180, 118, 160, 125);
        head.quadTo(140, 135, 130, 155);
        allPaths.add(new PathData(head, strokePaintMedium, PathType.STROKE, 0.35f));
        
        // ========== 4. 脸部细节 ==========
        // 眉毛 - 左
        Path leftBrow = new Path();
        leftBrow.moveTo(155, 172);
        leftBrow.quadTo(165, 168, 175, 172);
        Paint browPaint = createStrokePaint(1.5f);
        browPaint.setAlpha(102); // 0.4 opacity
        allPaths.add(new PathData(leftBrow, browPaint, PathType.STROKE, 0.55f));
        
        // 眉毛 - 右
        Path rightBrow = new Path();
        rightBrow.moveTo(225, 172);
        rightBrow.quadTo(235, 168, 245, 172);
        allPaths.add(new PathData(rightBrow, browPaint, PathType.STROKE, 0.58f));
        
        // 眼睛 - 左 (圆形填充)
        allPaths.add(new PathData(null, eyeFillPaint, PathType.CIRCLE, 0.6f, 165, 185, 5));
        
        // 眼睛 - 右
        allPaths.add(new PathData(null, eyeFillPaint, PathType.CIRCLE, 0.63f, 235, 185, 5));
        
        // 腮红 - 左 (椭圆填充)
        allPaths.add(new PathData(null, blushPaint, PathType.OVAL, 0.7f, 150, 220, 12, 8));
        
        // 腮红 - 右
        allPaths.add(new PathData(null, blushPaint, PathType.OVAL, 0.72f, 250, 220, 12, 8));
        
        // 鼻子 (椭圆填充)
        allPaths.add(new PathData(null, noseFillPaint, PathType.OVAL, 0.75f, 200, 290, 8, 6));
        
        // ========== 5. 脖子 ==========
        // 左边脖子线
        Path leftNeck = new Path();
        leftNeck.moveTo(175, 320);
        leftNeck.quadTo(170, 360, 165, 400);
        leftNeck.quadTo(162, 440, 160, 480);
        allPaths.add(new PathData(leftNeck, strokePaintMedium, PathType.STROKE, 0.8f));
        
        // 右边脖子线
        Path rightNeck = new Path();
        rightNeck.moveTo(225, 320);
        rightNeck.quadTo(230, 360, 235, 400);
        rightNeck.quadTo(238, 440, 240, 480);
        allPaths.add(new PathData(rightNeck, strokePaintMedium, PathType.STROKE, 0.85f));
        
        // 脖子中间线
        Path neckCenter = new Path();
        neckCenter.moveTo(200, 330);
        neckCenter.lineTo(200, 380);
        Paint neckCenterPaint = createStrokePaint(1f);
        neckCenterPaint.setAlpha(77); // 0.3 opacity
        allPaths.add(new PathData(neckCenter, neckCenterPaint, PathType.STROKE, 0.9f));
    }
    
    private Paint createStrokePaint(float strokeWidth) {
        float density = getContext().getResources().getDisplayMetrics().density;
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(0xFF3D3028);
        paint.setStrokeWidth(strokeWidth * density);
        paint.setStrokeCap(Paint.Cap.ROUND);
        paint.setStrokeJoin(Paint.Join.ROUND);
        return paint;
    }
    
    public void startAnimation() {
        if (isAnimating) return;
        isAnimating = true;
        
        mainAnimator = ValueAnimator.ofFloat(0f, 1f);
        mainAnimator.setDuration(2200); // 总时长 2.2 秒
        mainAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        mainAnimator.addUpdateListener(animation -> {
            animationProgress = (float) animation.getAnimatedValue();
            invalidate();
        });
        mainAnimator.start();
    }
    
    public void stopAnimation() {
        if (mainAnimator != null) {
            mainAnimator.cancel();
        }
        isAnimating = false;
    }
    
    public float getAnimationProgress() {
        return animationProgress;
    }
    
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        
        if (getWidth() == 0 || getHeight() == 0) return;
        
        canvas.save();
        
        // 计算缩放比例，让鹿居中且适应View大小
        float scaleX = getWidth() / SVG_WIDTH;
        float scaleY = getHeight() / SVG_HEIGHT;
        float scale = Math.min(scaleX, scaleY) * 0.85f;
        
        float centerX = getWidth() / 2f;
        float centerY = getHeight() / 2f;
        
        canvas.translate(centerX, centerY);
        canvas.scale(scale, scale);
        canvas.translate(-SVG_WIDTH / 2f, -SVG_HEIGHT / 2f);
        
        // 绘制所有路径
        for (PathData pathData : allPaths) {
            drawPathData(canvas, pathData);
        }
        
        canvas.restore();
    }
    
    private void drawPathData(Canvas canvas, PathData pathData) {
        // 计算这个路径的绘制进度
        float pathProgress = calculatePathProgress(pathData.startTime);
        if (pathProgress <= 0) return;
        
        switch (pathData.type) {
            case STROKE:
                if (pathData.path != null) {
                    drawPathWithProgress(canvas, pathData.path, pathData.paint, pathProgress);
                }
                break;
            case CIRCLE:
                if (pathProgress >= 1f) {
                    canvas.drawCircle(pathData.cx, pathData.cy, pathData.rx, pathData.paint);
                } else {
                    // 淡入效果
                    Paint fadePaint = new Paint(pathData.paint);
                    fadePaint.setAlpha((int) (pathData.paint.getAlpha() * pathProgress));
                    canvas.drawCircle(pathData.cx, pathData.cy, pathData.rx * pathProgress, fadePaint);
                }
                break;
            case OVAL:
                RectF oval = new RectF(
                    pathData.cx - pathData.rx,
                    pathData.cy - pathData.ry,
                    pathData.cx + pathData.rx,
                    pathData.cy + pathData.ry
                );
                if (pathProgress >= 1f) {
                    canvas.drawOval(oval, pathData.paint);
                } else {
                    // 淡入效果
                    Paint fadePaint = new Paint(pathData.paint);
                    fadePaint.setAlpha((int) (pathData.paint.getAlpha() * pathProgress));
                    float scaleProgress = 0.5f + 0.5f * pathProgress;
                    RectF scaledOval = new RectF(
                        pathData.cx - pathData.rx * scaleProgress,
                        pathData.cy - pathData.ry * scaleProgress,
                        pathData.cx + pathData.rx * scaleProgress,
                        pathData.cy + pathData.ry * scaleProgress
                    );
                    canvas.drawOval(scaledOval, fadePaint);
                }
                break;
        }
    }
    
    private float calculatePathProgress(float startTime) {
        // 每个路径有 0.15 的绘制时间窗口
        float pathDuration = 0.15f;
        if (animationProgress < startTime) return 0f;
        if (animationProgress >= startTime + pathDuration) return 1f;
        return (animationProgress - startTime) / pathDuration;
    }
    
    private void drawPathWithProgress(Canvas canvas, Path path, Paint paint, float progress) {
        if (progress <= 0 || path == null) return;
        
        PathMeasure pathMeasure = new PathMeasure(path, false);
        float totalLength = 0;
        
        // 计算所有子路径的总长度
        do {
            totalLength += pathMeasure.getLength();
        } while (pathMeasure.nextContour());
        
        // 重置 PathMeasure
        pathMeasure = new PathMeasure(path, false);
        float drawnLength = totalLength * progress;
        float currentLength = 0;
        
        Path drawPath = new Path();
        do {
            float segmentLength = pathMeasure.getLength();
            if (currentLength + segmentLength <= drawnLength) {
                // 完全绘制这个子路径
                Path segment = new Path();
                pathMeasure.getSegment(0, segmentLength, segment, true);
                drawPath.addPath(segment);
            } else if (currentLength < drawnLength) {
                // 部分绘制这个子路径
                float remainingLength = drawnLength - currentLength;
                Path segment = new Path();
                pathMeasure.getSegment(0, remainingLength, segment, true);
                drawPath.addPath(segment);
            }
            currentLength += segmentLength;
        } while (pathMeasure.nextContour() && currentLength < drawnLength);
        
        canvas.drawPath(drawPath, paint);
    }
    
    // 路径类型枚举
    private enum PathType {
        STROKE,  // 描边路径
        CIRCLE,  // 圆形填充
        OVAL     // 椭圆填充
    }
    
    // 路径数据类
    private static class PathData {
        Path path;
        Paint paint;
        PathType type;
        float startTime; // 0-1 之间，表示开始绘制的时间点
        float cx, cy;    // 圆心/椭圆中心
        float rx, ry;    // 半径
        
        // 描边路径构造函数
        PathData(Path path, Paint paint, PathType type, float startTime) {
            this.path = path;
            this.paint = paint;
            this.type = type;
            this.startTime = startTime;
        }
        
        // 圆形构造函数
        PathData(Path path, Paint paint, PathType type, float startTime, float cx, float cy, float r) {
            this(path, paint, type, startTime);
            this.cx = cx;
            this.cy = cy;
            this.rx = r;
            this.ry = r;
        }
        
        // 椭圆构造函数
        PathData(Path path, Paint paint, PathType type, float startTime, float cx, float cy, float rx, float ry) {
            this(path, paint, type, startTime);
            this.cx = cx;
            this.cy = cy;
            this.rx = rx;
            this.ry = ry;
        }
    }
}

