package com.kmall.admin.controller.mk;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.common.collect.ImmutableBiMap;
import com.kmall.admin.dto.ExpendDistDto;
import com.kmall.admin.entity.mk.MkDistEntity;
import com.kmall.admin.entity.mk.MkDistHierEntity;
import com.kmall.admin.entity.mk.MkDistHierLvlEntity;
import com.kmall.admin.entity.mk.MkDistSellAllocationEntity;
import com.kmall.admin.fromcomm.entity.SysUserEntity;
import com.kmall.admin.service.mk.MkDistHierService;
import com.kmall.admin.service.mk.MkDistSellAllocationService;
import com.kmall.admin.service.mk.MkDistService;
import com.kmall.admin.utils.ParamUtils;
import com.kmall.admin.utils.ShiroUtils;
import com.kmall.common.utils.*;
import io.swagger.models.auth.In;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


/**
 * 分销层级，树状层级，每个子级只有唯一一个父级，一个父级可以多个子级Controller
 *
 * @author emato
 * @email admin@qhdswl.com
 * @date 2019-04-09 18:04:46
 */
@Controller
@RequestMapping("mkdisthier")
public class MkDistHierController {
    @Autowired
    private MkDistHierService mkDistHierService;
    @Autowired
    private MkDistService mkDistService;
    @Autowired
    private MkDistSellAllocationService mkDistSellAllocationService;


    /**
     * 查看列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("mkdisthier:list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
        String distHierName = (String) params.get("distHierName");
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(distHierName)){
            try{
                distHierName = new String(distHierName.getBytes("iso-8859-1"),"utf-8");
            }catch (Exception e){
                e.printStackTrace();
            }
            params.put("distHierName", distHierName);
        }
        //查询列表数据
        Query query = new Query(params);

        List<MkDistHierEntity> mkDistHierList = mkDistHierService.queryList(query);
        int total = mkDistHierService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(mkDistHierList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{distHierId}")
    @RequiresPermissions("mkdisthier:info")
    @ResponseBody
    public R info(@PathVariable("distHierId") Integer distHierId) {
        MkDistHierEntity mkDistHier = mkDistHierService.queryObject(distHierId);

        return R.ok().put("mkDistHier", mkDistHier);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("mkdisthier:save")
    @ResponseBody
    public R save(@RequestBody MkDistHierEntity mkDistHier) {
        Map<String, Object> valideDate = MapBeanUtil.fromObject(mkDistHier);
        ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
        builder.put("distChnlId", "分销渠道id");
        builder.put("pdistId", "上级分销商id");
        builder.put("distId", "分销商id");
        builder.put("hierLvl", "层级级别");
        builder.put("distHierName", "分销商层级名称");
        builder.put("supplierId", "所属供货商");
        R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        }
        mkDistHierService.save(mkDistHier);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("mkdisthier:update")
    @ResponseBody
    public R update(@RequestBody MkDistHierEntity mkDistHier) {
        Map<String, Object> valideDate = MapBeanUtil.fromObject(mkDistHier);
        ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
        builder.put("distChnlId", "分销渠道id");
        builder.put("pdistId", "上级分销商id");
        builder.put("distId", "分销商id");
        builder.put("hierLvl", "层级级别");
        builder.put("distHierName", "分销商层级名称");
        builder.put("supplierId", "所属供货商");
        R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        }
        mkDistHierService.update(mkDistHier);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("mkdisthier:delete")
    @ResponseBody
    public R delete(@RequestBody Integer[]distHierIds) {
        mkDistHierService.deleteBatch(distHierIds);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {
        ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
        String distHierName = (String) params.get("distHierName");
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(distHierName)){
            try{
                distHierName = new String(distHierName.getBytes("iso-8859-1"),"utf-8");
            }catch (Exception e){
                e.printStackTrace();
            }
            params.put("distHierName", distHierName);
        }
        List<MkDistHierEntity> list = mkDistHierService.queryList(params);
        for (MkDistHierEntity distHierEntity: list) {
//            distHierEntity.setName(distHierEntity.getDistName());
//            distHierEntity.setParentName(distHierEntity.getPdDistName());
            if(distHierEntity.getHierLvl().equalsIgnoreCase("1")){
                distHierEntity.setParentId(0L);
            }
        }
        //添加顶级菜单
//        MkDistHierEntity root = new MkDistHierEntity();
//        root.setDistHierId(0);
//        root.setDistHierName("一级分销");
//        root.setPdistId(-1);
//        root.setOpen(true);
//        list.add(null);


        return R.ok().put("list", list);
    }

    @RequestMapping("/queryAllConfig")
    @ResponseBody
    public R queryAllConfig(@RequestParam Map<String, Object> params) {

        Map configMap = mkDistHierService.querySysConfigByKey();
        String value = MapUtils.getString("value", configMap);
        List<MkDistHierLvlEntity> lvlEntitieyList = new ArrayList<>();
        Integer hierLvl = Integer.parseInt(value);

        for (int i=0;i < hierLvl;i++){
            MkDistHierLvlEntity mkDistHierLvlEntity = new MkDistHierLvlEntity();
            mkDistHierLvlEntity.setHierLvl(String.valueOf(i+1));
            mkDistHierLvlEntity.setHierKey(String.valueOf(i+1));
            lvlEntitieyList.add(mkDistHierLvlEntity);
        }

        return R.ok().put("lvlEntitieyList", lvlEntitieyList);
    }

    /**
     * 查看树
     */
    @RequestMapping("/queryAll/tree")
    @ResponseBody
    public R queryAllByTree(@RequestParam Map<String, Object> params) {
        ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
        String distId = (String) params.get("distId");
        List<MkDistHierEntity> treeList = new ArrayList<>();

        MkDistHierEntity mkDistHierEntity = mkDistHierService.queryObjectByDistMap(params);
        if(mkDistHierEntity != null){
            String lvl = mkDistHierEntity.getHierLvl();
            Integer hierLvl = Integer.parseInt(lvl);

            Map<String, Object> distMap = new HashMap<>();
            distMap.put("distId", distId);
            List<MkDistHierEntity> list = mkDistHierService.queryListByTree(distMap);

            treeList.add(list.get(0));
            Integer pdistId = 0;
            if(list != null && list.size() > 0){
                pdistId = list.get(0).getPdistId();
            }
            for (int i = 0; i< hierLvl-1; i++){
                Map<String, Object> lvlMap = new HashMap<>();
                lvlMap.put("distId", pdistId);
                lvlMap.put("hierLvl", hierLvl-1-i);
                List<MkDistHierEntity> lvlList = mkDistHierService.queryListByTree(lvlMap);
                treeList.add(lvlList.get(0));
                pdistId = lvlList.get(0).getPdistId();
            }
        }
        List<ExpendDistDto> expendDistDtoList = new ArrayList<>();

        String goodsId = (String) params.get("goodsId");
        Integer storeId = (Integer) params.get("storeId");
        Map<String, Object> allocationMap = new HashMap<>();
        allocationMap.put("goodsId", goodsId);
        allocationMap.put("storeId", storeId);
        String expendDistLines = "";
        List<MkDistSellAllocationEntity> allocationEntityList =  mkDistSellAllocationService.queryAllocationByMap(allocationMap);
        if(allocationEntityList.size() == 0){
            SysUserEntity user = ShiroUtils.getUserEntity();
            Map<String, Object> distHierMap = new HashMap<>();
            if(StringUtils.isNotEmpty(user.getMerchSn())) {
                distHierMap.put("merchSn", user.getMerchSn());
            }
            if(StringUtils.isNotEmpty(String.valueOf(storeId))) {
                distHierMap.put("storeId", storeId);
            }
            if(StringUtils.isNotEmpty(user.getThirdPartyMerchCode())) {
                distHierMap.put("thirdPartyMerchCode", user.getThirdPartyMerchCode());
            }
            List<MkDistHierEntity> distHierEntityList = mkDistHierService.queryList(distHierMap);
            for (int i=0; i < distHierEntityList.size(); i++) {
                MkDistHierEntity distHier = distHierEntityList.get(i);
                MkDistEntity mkDistEntity = mkDistService.queryObject(distHier.getDistId());
                ExpendDistDto expendDistDto = new ExpendDistDto();
                expendDistDto.setExpendDistId(distHier.getDistId());
                expendDistDto.setExpendDistName(mkDistEntity.getDistName());
                expendDistDto.setExpendDistLvl(distHier.getHierLvl());
                expendDistDtoList.add(expendDistDto);
            }
        }else{
            expendDistLines = allocationEntityList.get(0).getExpendDistLines();
            String[] lines = null;
            if(StringUtils.isNotEmpty(expendDistLines)){
                lines = expendDistLines.split(",");
            }
            for (int i=0; i < treeList.size(); i++) {
                MkDistHierEntity distHier = treeList.get(i);
                MkDistEntity mkDistEntity = mkDistService.queryObject(distHier.getDistId());
                ExpendDistDto expendDistDto = new ExpendDistDto();
                expendDistDto.setExpendDistId(distHier.getDistId());
                expendDistDto.setExpendDistName(mkDistEntity.getDistName());
                expendDistDto.setExpendDistLvl(distHier.getHierLvl());

                if(treeList.size() == lines.length){
                    expendDistDto.setExpendDistLine(BigDecimal.valueOf(Double.parseDouble(lines[i])));
                }
                expendDistDtoList.add(expendDistDto);
            }
        }
        return R.ok().put("list", expendDistDtoList);
    }

    @RequestMapping("/queryNextLvlByDistId")
    @ResponseBody
    public R queryNextLvlByDistId(@RequestParam Map<String, Object> params) {
        MkDistHierEntity mkDistHierEntity = mkDistHierService.queryObjectByDistMap(params);
        List<MkDistHierLvlEntity> lvlEntitieyList = new ArrayList<>();
        if (mkDistHierEntity != null) {
            String hierLvl = "";
            Integer lvl = Integer.parseInt(mkDistHierEntity.getHierLvl());
            hierLvl = String.valueOf(lvl);
            MkDistHierLvlEntity lvlEntity = new MkDistHierLvlEntity();
            lvlEntity.setHierKey(hierLvl);
            lvlEntity.setHierLvl(hierLvl);
            lvlEntitieyList.add(lvlEntity);
        }
        return R.ok().put("lvlEntitieyList", lvlEntitieyList);
    }
}
