package com.heyu.api.controller.mm;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.heyu.api.alibaba.request.mm.VvProductDetailRequest;
import com.heyu.api.alibaba.request.mm.VvProductRequest;
import com.heyu.api.common.annotation.Describe;
import com.heyu.api.data.dao.vv.*;
import com.heyu.api.data.dto.vv.*;
import com.heyu.api.data.entity.vv.*;
import com.heyu.api.data.utils.CollectionUtils;
import com.heyu.api.data.utils.NumberUtil;
import com.heyu.api.data.utils.R;
import com.heyu.api.data.utils.SanUtils;
import com.heyu.api.utils.ISelect;
import com.heyu.api.utils.PPageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/mm/product")
public class AdminProductController {


    @Autowired
    private VvProductDao vvProductDao;


    @Autowired
    private VvProductDetailDao vvProductDetailDao;


    @Autowired
    private VvSkuDao vvSkuDao;


    @Autowired
    private VvSkuPropertyValueDao vvSkuPropertyValueDao;


    @Autowired
    private VvProductPropertyDao vvProductPropertyDao;


    @Autowired
    private VvProductPropertyValueDao vvProductPropertyValueDao;


    /***
     * 列表
     * http://localhost:8888/mm/product/list
     *
     *
     */
    @Describe("后台商品列表")
    @RequestMapping("/list")
    public R list(@RequestBody VvProductRequest vvProductRequest) {
        PPageUtils pageUtils = PPageUtils.startPage(vvProductRequest.getPageNum(), vvProductRequest.getPageSize())
                .doSelect(new ISelect() {
                    @Override
                    public List doSelect(IPage page) {
                        return vvProductDao.selectVvProductByCondition(page,
                                vvProductRequest.getId(),
                                vvProductRequest.getTitle(),
                                vvProductRequest.getMinShowSalePrice(),
                                vvProductRequest.getMaxShowSalePrice(),
                                vvProductRequest.getMinRealSaleCount(),
                                vvProductRequest.getMaxRealSaleCount(),
                                vvProductRequest.getMinCreateTimestamp(),
                                vvProductRequest.getMaxCreateTimestamp(),
                                vvProductRequest.getMinModifyTimestamp(),
                                vvProductRequest.getMaxModifyTimestamp(),
                                vvProductRequest.getFrontPage(),
                                vvProductRequest.getStatus(),
                                vvProductRequest.getRealSaleCountSort(),
                                vvProductRequest.getCreateTimestampSort(),
                                vvProductRequest.getModifyTimestampSort()

                        );

                    }
                });

        return R.ok().setData(pageUtils);
    }

    @Describe("后台商品详情")
    @RequestMapping("/detail")
    public R detail(@RequestBody VvProductDetailRequest vvProductDetailRequest) {
        VvProductDTO vvProductDTO = new VvProductDTO();

        VvProductEntity vvProduct = vvProductDao.selectVvProductById(vvProductDetailRequest.getProductId());

        BeanUtils.copyProperties(vvProduct, vvProductDTO);

        List<VvProductDetailEntity> productDetailEntities = vvProductDetailDao.selectVvProductDetailByProductId(vvProductDetailRequest.getProductId());

        vvProductDTO.setVvProductDetailList(productDetailEntities);

        List<VvSkuEntity> vvSkuEntities = vvSkuDao.selectVvSkuByProductId(vvProductDetailRequest.getProductId());

        List<VvSkuPropertyValueEntity> vvSkuPropertyValueList = vvSkuPropertyValueDao.selectVvSkuPropertyValueByProductId(vvProduct.getId());

        Map<Long, List<VvSkuPropertyValueEntity>> vvSkuPropertyValueMap = new LinkedHashMap<>();

        for (VvSkuPropertyValueEntity vvSkuPropertyValueEntity : vvSkuPropertyValueList) {
            List<VvSkuPropertyValueEntity> vvSkuPropertyValueEntities = vvSkuPropertyValueMap.get(vvSkuPropertyValueEntity.getSkuId());
            if (vvSkuPropertyValueEntities == null) {
                vvSkuPropertyValueEntities = new ArrayList<>();
            }

            vvSkuPropertyValueEntities.add(vvSkuPropertyValueEntity);

            vvSkuPropertyValueMap.put(vvSkuPropertyValueEntity.getSkuId(), vvSkuPropertyValueEntities);
        }


        List<VvSkuDTO> vvSkuDTOS = new ArrayList<>();
        for (VvSkuEntity vvSkuEntity : vvSkuEntities) {

            VvSkuDTO vvSkuDTO = new VvSkuDTO();

            BeanUtils.copyProperties(vvSkuEntity, vvSkuDTO);

            List<VvSkuPropertyValueEntity> vvSkuPropertyValueEntities = vvSkuPropertyValueMap.get(vvSkuEntity.getId());

            vvSkuDTO.setVvSkuPropertyValueList(vvSkuPropertyValueEntities);

            vvSkuDTOS.add(vvSkuDTO);
        }

        vvProductDTO.setVvSkuList(vvSkuDTOS);

        List<VvProductPropertyEntity> vvProductPropertyEntities = vvProductPropertyDao.selectVvProductPropertyByProductId(vvProductDetailRequest.getProductId());

        List<VvProductPropertyDTO> vvProductPropertyDTOS = new ArrayList<>();

        for (VvProductPropertyEntity vvProductPropertyEntity : vvProductPropertyEntities) {

            VvProductPropertyDTO vvProductPropertyDTO = new VvProductPropertyDTO();

            BeanUtils.copyProperties(vvProductPropertyEntity, vvProductPropertyDTO);

            List<VvProductPropertyValueEntity> productPropertyValues = vvProductPropertyValueDao.selectVvProductPropertyValueByProductIdPropertyId(vvProductPropertyEntity.getId());

            vvProductPropertyDTO.setVvProductPropertyValueList(productPropertyValues);

            vvProductPropertyDTOS.add(vvProductPropertyDTO);
        }
        vvProductDTO.setVvProductPropertyList(vvProductPropertyDTOS);
        return R.ok().setData(vvProductDTO);
    }

    @Describe("后台商品复制")
    @RequestMapping("/copy")
    public R copy(@RequestBody VvCopyProductRequest vvCopyProductRequest) {

        Long productId = vvCopyProductRequest.getProductId();

        VvProductEntity vvProduct = vvProductDao.selectVvProductById(vvCopyProductRequest.getProductId());
        vvProduct.setId(null);

        vvProductDao.insertOrUpdateVvProduct(vvProduct);

        List<VvProductDetailEntity> productDetailEntities = vvProductDetailDao.selectVvProductDetailByProductId(productId);

        for (VvProductDetailEntity productDetailEntity : productDetailEntities) {
            productDetailEntity.setProductId(vvProduct.getId());
            productDetailEntity.setId(null);
            vvProductDetailDao.insertOrUpdateVvProductDetail(productDetailEntity);
        }

        List<VvProductPropertyEntity> vvProductPropertyEntities = vvProductPropertyDao.selectVvProductPropertyByProductId(productId);
        for (VvProductPropertyEntity productPropertyEntity : vvProductPropertyEntities) {
            Long productPropertyId = productPropertyEntity.getId();
            productPropertyEntity.setId(null);
            productPropertyEntity.setProductId(vvProduct.getId());
            vvProductPropertyDao.insertVvProductProperty(productPropertyEntity);
            List<VvProductPropertyValueEntity> productPropertyValues = vvProductPropertyValueDao.selectVvProductPropertyValueByProductIdPropertyId(productPropertyId);
            for (VvProductPropertyValueEntity productPropertyValue : productPropertyValues) {
                productPropertyValue.setProductId(vvProduct.getId());
                productPropertyValue.setId(null);
                productPropertyValue.setProductPropertyId(productPropertyEntity.getId());
                vvProductPropertyValueDao.insertVvProductPropertyValue(productPropertyValue);
            }
        }

        List<VvSkuEntity> vvSkuEntities = vvSkuDao.selectVvSkuByProductId(productId);
        for (VvSkuEntity vvSkuEntity : vvSkuEntities) {
            Long skuId = vvSkuEntity.getId();
            vvSkuEntity.setId(null);
            vvSkuEntity.setProductId(vvProduct.getId());
            vvSkuDao.insertOrUpdateVvSku(vvSkuEntity);
            List<VvSkuPropertyValueEntity> vvSkuPropertyValueEntities = vvSkuPropertyValueDao.selectVvSkuPropertyValueBySkuId(skuId);
            for (VvSkuPropertyValueEntity vvSkuPropertyValueEntity : vvSkuPropertyValueEntities) {
                vvSkuPropertyValueEntity.setId(null);
                vvSkuPropertyValueEntity.setSkuId(vvSkuEntity.getId());
                vvSkuPropertyValueEntity.setProductId(vvProduct.getId());
                vvSkuPropertyValueDao.insertOrUpdateVvSkuPropertyValue(vvSkuPropertyValueEntity);
            }
        }
        return R.ok();
    }

    // /mm/product/onlyUpdateProduct 只更新商品信息
    @Describe("后台仅编辑商品")
    @RequestMapping("/onlyUpdateProduct")
    public R onlyUpdate(@RequestBody VvProductEntity vvProductEntity) {
        vvProductDao.insertOrUpdateVvProduct(vvProductEntity);
        return R.ok();
    }


    //  /mm/product/insertOrUpadate
    @Describe("后台商品保存和插入")
    @RequestMapping("/insertOrUpadate")
    public R insertOrUpadate(@RequestBody VvProductDTO vvProductDTO) {
        if(vvProductDTO.getId() == null){
            vvProductDTO.setCreateTimestamp(System.currentTimeMillis());
        }
        vvProductDTO.setModifyTimestamp(System.currentTimeMillis());
        vvProductDao.insertOrUpdateVvProduct(vvProductDTO);
        Long productId = vvProductDTO.getId();
        List<VvProductDetailEntity> productDetailEntities = vvProductDetailDao.selectVvProductDetailByProductId(productId);


        Map<Long, List<VvProductDetailEntity>> groupbyProductDetail =
                SanUtils.groupByFiled2MapList(vvProductDTO.getVvProductDetailList(), VvProductDetailEntity::getId);

        // 1. 如果传过来的参数存在，则更新 ，如果不存在 ，则直接物理删除掉
        for (VvProductDetailEntity productDetailEntity : productDetailEntities) {
            if (CollectionUtils.notContainsKey(groupbyProductDetail, productDetailEntity.getId())) {
                vvProductDetailDao.deleteVvProductDetailRealById(productDetailEntity.getId());
            }
        }
        /**
         * 传过来的
         */
        for (VvProductDetailEntity vvProductDetailEntity : vvProductDTO.getVvProductDetailList()) {
            vvProductDetailEntity.setProductId(productId);
            vvProductDetailDao.insertOrUpdateVvProductDetail(vvProductDetailEntity);
        }

        List<VvSkuDTO> vvSkuDTOS = vvProductDTO.getVvSkuList();
        List<VvSkuEntity> vvSkuEntities = vvSkuDao.selectVvSkuByProductId(productId);

        Map<Long, List<VvSkuDTO>> groupbySkuDTOs = SanUtils.groupByFiled2MapList(vvSkuDTOS, VvSkuDTO::getId);
        for (VvSkuEntity vvSkuEntity : vvSkuEntities) {
            if (CollectionUtils.notContainsKey(groupbySkuDTOs, vvSkuEntity.getId())) {
                vvSkuPropertyValueDao.deleteVvSkuPropertyValueRealBySkuId(vvSkuEntity.getId());
                vvSkuDao.deleteVvSkuByRealId(vvSkuEntity.getId());
            }
        }

        Long productSkuId = null;

        for (VvSkuDTO vvSkuDTO : vvSkuDTOS) {
            Long skuId = vvSkuDTO.getId();
            vvSkuDTO.setProductId(productId);
            vvSkuDao.insertOrUpdateVvSku(vvSkuDTO);
            if (NumberUtil.equals(vvSkuDTO.getIsDefault(), 1)) {
                vvProductDTO.setSkuId(skuId);
                vvProductDTO.setShowPromotionPrice(vvSkuDTO.getPromotionPrice());
                vvProductDao.insertOrUpdateVvProduct(vvProductDTO);
            }
            /***
             * 更新
             */
            List<VvSkuPropertyValueEntity> vvSkuPropertyValueEntities = vvSkuDTO.getVvSkuPropertyValueList();
            if (skuId != null) {
                // 更新
                Map<Long, List<VvSkuPropertyValueEntity>> groupbySkuPropertyValue =
                        SanUtils.groupByFiled2MapList(vvSkuPropertyValueEntities, VvSkuPropertyValueEntity::getId);
                List<VvSkuPropertyValueEntity> vvSkuPropertyValueDB = vvSkuPropertyValueDao.selectVvSkuPropertyValueBySkuId(vvSkuDTO.getId());
                for (VvSkuPropertyValueEntity vvSkuPropertyValueDb : vvSkuPropertyValueDB) {
                    // 如果不存在 ，则直接删除
                    if (CollectionUtils.notContainsKey(groupbySkuPropertyValue, vvSkuPropertyValueDb.getId())) {
                        vvSkuPropertyValueDao.deleteVvSkuPropertyValueRealById(vvSkuPropertyValueDb.getId());
                    }
                }
            }
            for (VvSkuPropertyValueEntity vvSkuPropertyValueEntity : vvSkuPropertyValueEntities) {
                vvSkuPropertyValueEntity.setSkuId(vvSkuDTO.getId());
                vvSkuPropertyValueEntity.setProductId(productId);
                vvSkuPropertyValueDao.insertOrUpdateVvSkuPropertyValue(vvSkuPropertyValueEntity);
            }
        }

        if (productSkuId == null) {
            productSkuId =  vvSkuDTOS.get(0).getId();
        }

        vvProductDTO.setSkuId(productSkuId);
        vvProductDao.updateVvProductById(vvProductDTO);

        List<VvProductPropertyDTO> vvProductPropertyDTOS = vvProductDTO.getVvProductPropertyList();
        List<VvProductPropertyEntity> vvProductPropertyEntities = vvProductPropertyDao.selectVvProductPropertyByProductId(productId);

        Map<Long, List<VvProductPropertyDTO>> groupbyProductProperty =
                SanUtils.groupByFiled2MapList(vvProductPropertyDTOS, VvProductPropertyDTO::getId);

        for (VvProductPropertyEntity vvProductProperty : vvProductPropertyEntities) {
            // 对他进行编辑
            if (CollectionUtils.notContainsKey(groupbyProductProperty, vvProductProperty.getId())) {
                vvProductPropertyDao.deleteVvProductPropertyRealById(vvProductProperty.getId());
                vvProductPropertyValueDao.deleteVvProductPropertyValueRealByProductPropertyId(vvProductProperty.getId());
            }
        }

        for (VvProductPropertyDTO vvProductPropertyDTO : vvProductPropertyDTOS) {
            Long productPropertyId = vvProductPropertyDTO.getId();
            vvProductPropertyDTO.setProductId(productId);
            vvProductPropertyDao.insertOrUpdateVvProductProperty(vvProductPropertyDTO);

            List<VvProductPropertyValueEntity> vvProductPropertyValueEntities = vvProductPropertyDTO.getVvProductPropertyValueList();
            Map<Long, List<VvProductPropertyValueEntity>> groupbyProductPropertyValue =
                    SanUtils.groupByFiled2MapList(vvProductPropertyValueEntities, VvProductPropertyValueEntity::getId);

            // 对他进行编辑
            if (productPropertyId != null) {
                List<VvProductPropertyValueEntity> productPropertyValueDb = vvProductPropertyValueDao.selectVvProductPropertyValueByProductIdPropertyId(productPropertyId);
                for (VvProductPropertyValueEntity vvProductPropertyValueEntity : productPropertyValueDb) {
                    if (CollectionUtils.notContainsKey(groupbyProductPropertyValue, vvProductPropertyValueEntity.getId())) {
                        vvProductPropertyValueDao.deleteVvProductPropertyValueRealById(vvProductPropertyValueEntity.getId());
                    }
                }
            }
            for (VvProductPropertyValueEntity vvProductPropertyValueEntity : vvProductPropertyValueEntities) {
                vvProductPropertyValueEntity.setProductId(productId);
                vvProductPropertyValueEntity.setProductPropertyId(vvProductPropertyDTO.getId());
                vvProductPropertyValueDao.insertOrUpdateVvProductPropertyValue(vvProductPropertyValueEntity);
            }
        }
        return R.ok();
    }

    @Describe("后台属性排序")
    // // /mm/product/property/sort
    @RequestMapping("/property/sort")
    public R propertySort(@RequestBody VVAdminProductPropertyDTO dto) {
        List<VvProductPropertyEntity> list = vvProductPropertyDao.selectProductPropertyByIds(dto.getProductPropertyIds());
        List<Long> categoryIds = dto.getProductPropertyIds();
        for (VvProductPropertyEntity vvCategoryEntity : list) {
            int index = categoryIds.indexOf(vvCategoryEntity.getId()) + 1;
            vvCategoryEntity.setDefaultSort(index);
            vvProductPropertyDao.insertOrUpdateVvProductProperty(vvCategoryEntity);
        }
        return R.ok("排序成功");
    }

    @Describe("后台属性值排序")
    // /mm/product/property/value/sort
    @RequestMapping("/property/value/sort")
    public R propertyValueSort(@RequestBody VVAdminProductPropertyValueDTO dto) {
        List<VvProductPropertyValueEntity> list = vvProductPropertyValueDao.selectProductPropertyValueByIds(dto.getProductPropertyValueIds());
        List<Long> categoryIds = dto.getProductPropertyValueIds();
        for (VvProductPropertyValueEntity vvCategoryEntity : list) {
            int index = categoryIds.indexOf(vvCategoryEntity.getId()) + 1;
            vvCategoryEntity.setDefaultSort(index);
            vvProductPropertyValueDao.insertOrUpdateVvProductPropertyValue(vvCategoryEntity);
        }

        return R.ok();
    }

    // key:


    public static void main(String[] args) {
        String a[]  = new String[]{"a","c","f"}; // 颜色
        String b[]  = new String[]{"x","z","y"}; // 长度
        String c[]  = new String[]{"m","n"}; // 尺寸
        String d[]  = new String[]{"0","1"}; // 尺寸

        List<String[]> list =new ArrayList<>();

        list.add(a);
        list.add(b);
        list.add(c);
        list.add(d);

        List<Integer> level =  new ArrayList<>();
        for (String[] strings : list) {
            level.add(strings.length);
        }

        System.out.println(JSON.toJSONString(level));
        List<List<Integer>> ccc = can(level);
        System.out.println(JSON.toJSONString(ccc));

        List<List<Integer>> ddd = new ArrayList<>();

        int i = 0 ;
        for (List<Integer> integers : ccc) {
            ddd = digui(integers,ddd,i );
            i ++;
        }

        System.out.println(JSON.toJSONString(ddd));
        System.out.println(ddd.size());


        System.out.println(JSON.toJSONString(list));

        for (List<Integer> integers : ddd) {

            System.out.println(getValue(list,integers));
        }
    }



    public static String getValue( List<String[]> list, List<Integer> index){
        StringBuffer sb = new StringBuffer();
        for (int i = 0 ;i < list.size() ; i++) {
            String[]  strings = list.get(i);
            sb.append(strings[index.get(i)]);
        }
        return sb.toString();
    }

    public static List<List<Integer>>  digui(List<Integer> list, List<List<Integer>> ddd,int flag ){
        List<List<Integer>> newList = new ArrayList<>();
        if(ddd.size()==0){
            for (Integer i : list) {
                List<Integer> item = new ArrayList<>();
                item.add(i);
                newList.add(item);

            }
            return newList;
        }
        for (List<Integer> integers : ddd) {
            for (Integer i : list) {
                List<Integer> listItem = new ArrayList<>();
                listItem.addAll(integers);
                listItem.add(i);
                newList.add(listItem);
            }
        }
        return newList;
    }


    public static List<List<Integer>> can (List<Integer> list ){
        List<List<Integer>> lists = new ArrayList<>();
        for (Integer i : list) {
            List<Integer> xx = aa(i);
            lists.add(xx);
        }
        return lists;
    }


    public static List<Integer> aa (Integer max){
        List<Integer> list = new ArrayList<>();
        for(int i = 0 ;i < max;i ++){
            list.add(i);
        }
        return list;

    }


}
