package com.ihaoin.hooloo.device.view;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.ihaoin.hooloo.device.HLApplication;
import com.ihaoin.hooloo.device.R;
import com.ihaoin.hooloo.device.component.IntroViewPager;
import com.ihaoin.hooloo.device.config.Base;
import com.ihaoin.hooloo.device.data.vo.Goods;
import com.ihaoin.hooloo.device.data.vo.GoodsRule;
import com.ihaoin.hooloo.device.data.vo.Sku;
import com.ihaoin.hooloo.device.data.vo.SkuRule;
import com.ihaoin.hooloo.device.util.CollectionUtils;
import com.ihaoin.hooloo.device.util.StringUtils;
import com.ihaoin.hooloo.device.util.Utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class GoodsDetailDialog extends Dialog {
    private Goods goods;
    private Sku checkSku;
    private View butnClose;
    private IntroViewPager introPager;
    private RadioGroup introIndicator;
    private TextView txtName;
    private LinearLayout layoutSpecs;
    private LinearLayout layoutImages;
    private TextView txtPrice;
    private TextView icoPirce;
    private TextView txtDiscount;
    private Button butnSubtract;
    private TextView txtCount;
    private Button butnAdd;
    private Button butnBuy;
    private Button butnTrolley;
    private View layoutOperate;
    private View layoutButns;
    private View txtSellout;

    private Integer count = 1;
    private List<View> introViews;

    public GoodsDetailDialog(@NonNull Context context, Goods goods) {
        super(context);
        this.goods = goods;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.view_goods_detail);
        initViews();
    }

    private void initViews() {
        layoutButns = findViewById(R.id.layout_butns);
        layoutOperate = findViewById(R.id.layout_operate);
        txtSellout = findViewById(R.id.txt_sellout);
        butnClose = findViewById(R.id.butn_close);
        introPager = findViewById(R.id.intro_pager);
        introIndicator = findViewById(R.id.intro_indicator);
        txtName = findViewById(R.id.txt_name);
        layoutSpecs = findViewById(R.id.layout_specs);
        layoutImages = findViewById(R.id.layout_images);
        icoPirce = findViewById(R.id.ico_price);
        txtPrice = findViewById(R.id.txt_price);
        txtDiscount = findViewById(R.id.txt_discount);
        butnSubtract = findViewById(R.id.butn_subtract);
        txtCount = findViewById(R.id.txt_count);
        butnAdd = findViewById(R.id.butn_add);
        butnBuy = findViewById(R.id.butn_buy);
        butnTrolley = findViewById(R.id.butn_trolley);

        butnClose.setOnClickListener(x -> dismiss());

        introViews = new ArrayList<>();
        if (goods.getPics() != null && !CollectionUtils.isEmpty(goods.getPics().getIntroImages())) {
//            goods.getPics().getIntroImages().addAll(goods.getPics().getIntroImages()); // TODO TEST

            for (int i = 0; i < goods.getPics().getIntroImages().size(); i++) {
                String url = goods.getPics().getIntroImages().get(i);
                View imgIntro = getIntroImage(url);
                View btnIntro = getIntroButton(i);
                introViews.add(imgIntro);
                introIndicator.addView(btnIntro);
            }
            introPager.setIntroViews(introViews);
            Utils.check(introIndicator, 0);
//            introIndicator.check(0);
            if (introIndicator.getChildCount() > 1) {
                introIndicator.setVisibility(View.VISIBLE);
                startPageThread();
                introPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {
                        Utils.check(introIndicator, position);
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
            }
        }

        txtName.setText(goods.getName());
        txtPrice.setText(Utils.toString(goods.getPrice()));
        txtDiscount.setText(Utils.toString(goods.getDiscount()));
        butnSubtract.setOnClickListener(v -> subtractGoods());
        butnAdd.setOnClickListener(v -> addGoods());

        icoPirce.setPaintFlags(icoPirce.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
        txtPrice.setPaintFlags(txtPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);

        butnBuy.setOnClickListener(v -> buyNow());
        butnTrolley.setOnClickListener(v -> addTrolley());

        ViewGroup layoutItem = findViewById(R.id.layout_item);
        Utils.setTouchDelegate(layoutItem, Arrays.asList(butnAdd, butnSubtract));

        // 处理售罄的SKU和规格选项
        processSpecRules();

        buildSpecs();
        buildDetails();

        Utils.setTouchDelegate(findViewById(R.id.layout_root), Arrays.asList(butnClose));

        setOnDismissListener(dialog -> {
            if (pagerHandler != null) {
                pagerHandler.removeCallbacksAndMessages(null);
                pagerHandler = null;
            }
        });
    }

    private void startPageThread() {
        pagerHandler = new PagerHandler();
        pagerThread = new PagerThread();
        pagerThread.start();
    }

    private PagerThread pagerThread;
    private PagerHandler pagerHandler;

    private class PagerThread extends Thread {
        @Override
        public void run() {
            try {
                while (true) {
                    Thread.sleep(1000 * 2);
                    pagerHandler.sendEmptyMessage(1);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private class PagerHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            int index = introPager.getCurrentItem();
            int count = introPager.getCount();
            if (index + 1 >= count) {
                index = 0;
            } else {
                index++;
            }
            introPager.setCurrentItem(index, true);
        }
    }

    private View getIntroButton(int id) {
        Integer width = Utils.getDimens(getContext(), R.dimen.padding5);
        Integer height = Utils.getDimens(getContext(), R.dimen.padding5);
        RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(width, height);
        layoutParams.rightMargin = Utils.getDimens(getContext(), R.dimen.padding3);

        RadioButton button = new RadioButton(getContext());
        button.setLayoutParams(layoutParams);
        button.setButtonDrawable(null);
        button.setBackgroundResource(R.drawable.sel_intro_indicator);
        button.setText("");
        button.setId(id);
        return button;
    }

    private ImageView getIntroImage(String url) {
        RequestOptions options = new RequestOptions().placeholder(R.drawable.bg_image_placeholder);
        ImageView imgIntro = new ImageView(getContext());
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        imgIntro.setLayoutParams(layoutParams);
        imgIntro.setAdjustViewBounds(true);
        Glide.with(getContext()).setDefaultRequestOptions(options).load(url).into(imgIntro);
        return imgIntro;
    }

    private void buyNow() {
        if (checkSku == null) {
            Toast.makeText(getContext(), R.string.not_found_goods, Toast.LENGTH_SHORT).show();
            return;
        }
        Utils.showConfirmOrder(getContext(), goods, checkSku, count);
        dismiss();
    }

    private void addTrolley() {
        if (checkSku == null) {
            Toast.makeText(getContext(), R.string.not_found_goods, Toast.LENGTH_SHORT).show();
            return;
        }
        Utils.sendAddGoodsBroadcast(getContext(), goods, checkSku, count);
        dismiss();
    }

    private void addGoods() {
        if (count >= HLApplication.getMainData().getCountOfOrder()) {
            Toast.makeText(this.getContext(), getContext().getString(R.string.count_limit, HLApplication.getMainData().getCountOfOrder().toString()), Toast.LENGTH_SHORT).show();
            return;
        }
        count++;
        txtCount.setText(String.valueOf(count));
    }

    private void subtractGoods() {
        if (count <= 1) {
            return;
        }
        count--;
        txtCount.setText(String.valueOf(count));
    }

    private void buildSpecs() {
        if (CollectionUtils.isEmpty(goods.getSpecs())) {
            return;
        }
        goods.getSpecs().forEach(spec -> {
            if (CollectionUtils.isEmpty(spec.getRules())) {
                return;
            }
            View specView = getLayoutInflater().inflate(R.layout.item_spec, null);
            TextView txtName = specView.findViewById(R.id.txt_name);
            LinearLayout layoutRules = specView.findViewById(R.id.layout_rules);

            txtName.setText(spec.getSpecName());
            spec.getRules().forEach(rule -> {
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.rightMargin = Utils.getDimens(getContext(), R.dimen.padding5);

                View ruleView = getLayoutInflater().inflate(R.layout.item_spec_rule, null);
                ruleView.setTag(rule);

                TextView button = ruleView.findViewById(R.id.butn_rule);
                button.setId(rule.getRuleId());
                button.setText(rule.getRuleName());
                if (Base.TRUE.equals(rule.getIsRecommend())) {
                    ruleView.findViewById(R.id.txt_recommend).setVisibility(View.VISIBLE);
                }
                if (!Base.TRUE.equals(rule.getState())) {
                    button.setEnabled(false);
                } else {
                    if (Base.TRUE.equals(rule.getIsDefault())) {
                        button.setSelected(true);
                        ruleView.setSelected(true);
                    }
                    ruleView.setOnClickListener(v -> {
                        clearSelected(layoutRules);
                        ruleView.setSelected(true);
                        button.setSelected(true);
                        changeSkuWithRule();
                    });
                }
                layoutRules.addView(ruleView, layoutParams);
            });
            layoutSpecs.addView(specView);
//            layoutRules.setOnCheckedChangeListener((group, checkedId) -> changeSkuWithRule());
        });
        changeSkuWithRule();
    }

    private void clearSelected(ViewGroup group) {
        if (group.getChildCount() <= 0) {
            return;
        }
        for (int i = 0; i < group.getChildCount(); i++) {
            View v = group.getChildAt(i);
            v.setSelected(false);
            if (v instanceof ViewGroup) {
                clearSelected((ViewGroup) v);
            }
        }
    }

    private void changeSkuWithRule() {
        if (layoutSpecs.getChildCount() <= 0) {
            return;
        }
        List<GoodsRule> rules = new ArrayList<>();
        for (int i = 0; i < layoutSpecs.getChildCount(); i++) {
            View v = layoutSpecs.getChildAt(i);
            LinearLayout layoutRules = v.findViewById(R.id.layout_rules);
            View view = getSelectedView(layoutRules);
            if (view == null) {
                continue;
            }
            rules.add((GoodsRule) view.getTag());
        }
        checkSku = matchSku(rules);
        if (checkSku == null) {
//            Toast.makeText(getContext(), R.string.not_found_goods, Toast.LENGTH_SHORT).show();
            return;
        }
        txtPrice.setText(Utils.toString(checkSku.getPrice()));
        txtDiscount.setText(Utils.toString(checkSku.getDiscount()));
    }

    private View getSelectedView(LinearLayout layoutRules) {
        if (layoutRules.getChildCount() <= 0) {
            return null;
        }
        for (int i = 0; i < layoutRules.getChildCount(); i++) {
            View v = layoutRules.getChildAt(i);
            if (v.isSelected()) {
                return v;
            }
        }
        return null;
    }

    private Sku matchSku(List<GoodsRule> rules) {
        if (CollectionUtils.isEmpty(rules)) {
            return null;
        }
        if (CollectionUtils.isEmpty(goods.getSkus())) {
            return null;
        }
        List<Integer> checkRuleIds = rules.stream().map(GoodsRule::getRuleId).sorted().collect(Collectors.toList());
        for (Sku sku : goods.getSkus()) {
            List<Integer> skuRuleIds = sku.getRules().stream().map(SkuRule::getRuleId).sorted().collect(Collectors.toList());
            if (skuRuleIds.toString().equals(checkRuleIds.toString())) {
                return sku;
            }
        }
        return null;
    }

    private void buildDetails() {
        if (goods.getPics() == null || CollectionUtils.isEmpty(goods.getPics().getDetailImages())) {
            return;
        }
        goods.getPics().getDetailImages().forEach(url -> {
            if (StringUtils.isEmpty(url)) {
                return;
            }
            ImageView imageView = new ImageView(getContext());
            imageView.setAdjustViewBounds(true);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.bottomMargin = Utils.getDimens(getContext(), R.dimen.padding5);
            Glide.with(getContext()).load(url).into(imageView);
            layoutImages.addView(imageView, layoutParams);
        });
    }

    private void processSpecRules() {
        if (goods == null || CollectionUtils.isEmpty(goods.getSpecs()) || CollectionUtils.isEmpty(goods.getSkus())) {
            showSelloutViews();
            return;
        }
        // 将商品所有SKU列表按售罄和未售罄分组
        Map<Integer, List<Sku>> map = goods.getSkus().stream().collect(Collectors.groupingBy(Sku::getState));
        if (CollectionUtils.isEmpty(map)) {
            return;
        }
        // 售罄SKU列表
        List<Sku> sellOuts = map.get(Base.FALSE);
        // 未售罄SKU列表
        List<Sku> sellIns = map.get(Base.TRUE);
        if (CollectionUtils.isEmpty(sellIns)) {
            showSelloutViews();
            return;
        }
        // 售罄SKU列表为空不需要处理
        if (CollectionUtils.isEmpty(sellOuts)) {
            return;
        }
        sellOuts.forEach(sku -> {
            if (CollectionUtils.isEmpty(sku.getRules())) {
                return;
            }
            sku.getRules().forEach(skuRule -> {
                // 检查未售罄的sku里是否有此规格选项，如果有则此选项可选
                Integer ruleState = checkRuleState(skuRule, sellIns);
                setRuleState(skuRule, ruleState);
            });
        });
    }

    /** 检查未售罄的sku里是否有此规格选项，如果有则此选项可选 */
    private Integer checkRuleState(SkuRule skuRule, List<Sku> sellIns) {
        if (CollectionUtils.isEmpty(sellIns)) {
            return Base.FALSE;
        }

        for (Sku sku : sellIns) {
            if (CollectionUtils.isEmpty(sku.getRules())) {
                continue;
            }
            for (SkuRule rule : sku.getRules()) {
                if (rule.getRuleId().equals(skuRule.getRuleId())) {
                    return Base.TRUE;
                }
            }
        }
        return Base.FALSE;
    }

    /** 设备商品规格 选项状态 */
    private void setRuleState(SkuRule skuRule, Integer ruleState) {
        if (goods == null || CollectionUtils.isEmpty(goods.getSpecs())) {
            return;
        }
        goods.getSpecs().forEach(spec -> {
            // 选项为空的规格不处理
            if (CollectionUtils.isEmpty(spec.getRules())) {
                return;
            }
            spec.getRules().forEach(rule -> {
                // 设置匹配的选项
                if (rule.getRuleId().equals(skuRule.getRuleId())) {
                    rule.setState(ruleState);
                }
            });
        });
    }

    private void showSelloutViews() {
        layoutOperate.setVisibility(View.GONE);
        layoutButns.setVisibility(View.GONE);
        txtSellout.setVisibility(View.VISIBLE);
        setAllRuleSellouts(); // 所有规格设置为售罄
    }

    private void setAllRuleSellouts() {
        if (goods == null || CollectionUtils.isEmpty(goods.getSpecs())) {
            return;
        }
        goods.getSpecs().forEach(spec -> {
            if (CollectionUtils.isEmpty(spec.getRules())) {
                return;
            }
            spec.getRules().forEach(rule -> rule.setState(Base.FALSE));
        });
    }
}
