package com.buy507.mall.portal.service.impl;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.buy507.mall.common.api.CommonResult;
import com.buy507.mall.common.util.Constants;
import com.buy507.mall.mapper.UmsAreaMapper;
import com.buy507.mall.mapper.UmsMemberReceiveAddressMapper;
import com.buy507.mall.model.DefaultStatus;
import com.buy507.mall.model.UmsArea;
import com.buy507.mall.model.UmsMember;
import com.buy507.mall.model.UmsMemberReceiveAddress;
import com.buy507.mall.portal.domain.AreaOptions;
import com.buy507.mall.portal.service.RedisService;
import com.buy507.mall.portal.service.UmsMemberReceiveAddressService;
import com.buy507.mall.portal.service.UmsMemberService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * 用户地址管理Service实现类
 */
@Service
public class UmsMemberReceiveAddressServiceImpl implements UmsMemberReceiveAddressService {
	
    @Autowired
    private UmsMemberService memberService;
    
    @Autowired
    private UmsAreaMapper areaMapper;
    
    @Autowired
    private UmsMemberReceiveAddressMapper memberReceiveAddressMapper;
    
    @Autowired
    private RedisService redisService;
    
    @Override
    public CommonResult add(UmsMemberReceiveAddress address) {
    	
    	UmsMember currentMember = memberService.getCurrentMember();
    	
    	String errorMessage = verifyParam(address);
    	if(!StringUtils.isEmpty(errorMessage)) {
    		return CommonResult.failed(errorMessage);
    	}
    	
    	//是否为默认 0->否；1->是
    	UmsMemberReceiveAddress defaultAddress = memberReceiveAddressMapper.selectOneByMemberIdAndDefaultStatus(currentMember.getId(), DefaultStatus.Yes.getValue());
    	if(address.getDefaultStatus() == 1 && defaultAddress != null) {
    		defaultAddress.setDefaultStatus(0);
    		memberReceiveAddressMapper.updateById(defaultAddress);
	    }
    	
        address.setId(null);
        address.setMemberId(currentMember.getId());
        memberReceiveAddressMapper.insert(address);
        return CommonResult.success(null, "添加成功");
    }

    @Override
    public CommonResult delete(Long id) {
        UmsMember currentMember = memberService.getCurrentMember();
        UmsMemberReceiveAddress address = memberReceiveAddressMapper.selectOneById(id);
        if(address != null && address.getMemberId().equals(currentMember.getId())) {
        	memberReceiveAddressMapper.deleteById(id);
        }
        return CommonResult.success(null, "删除成功");
    }

    @Override
    public CommonResult update(Long id, UmsMemberReceiveAddress address) {
    	String errorMessage = verifyParam(address);
    	if(!StringUtils.isEmpty(errorMessage)) {
    		return CommonResult.failed(errorMessage);
    	}
        UmsMember currentMember = memberService.getCurrentMember();
        
        UmsMemberReceiveAddress dbAddress = memberReceiveAddressMapper.selectOneById(id);
        if(dbAddress != null && dbAddress.getMemberId().equals(currentMember.getId())) {
        	
        	//是否为默认 0->否；1->是
        	if(address.getDefaultStatus() == 1) {
            	UmsMemberReceiveAddress defaultAddress = memberReceiveAddressMapper.selectOneByMemberIdAndDefaultStatus(currentMember.getId(), DefaultStatus.Yes.getValue());
            	if(defaultAddress != null) {
            		defaultAddress.setDefaultStatus(0);
            		memberReceiveAddressMapper.updateById(defaultAddress);
        	    }
        	}
        	
        	address.setId(id);
        	address.setMemberId(dbAddress.getMemberId());
        	memberReceiveAddressMapper.updateById(address);
        }
        return CommonResult.success(null, "更新成功");
    }

    @Override
    public List<UmsMemberReceiveAddress> list() {
    	UmsMember currentMember = memberService.getCurrentMember();
    	return memberReceiveAddressMapper.selectByMemberId(currentMember.getId());
    }
    
    @Override
    public UmsMemberReceiveAddress getDefaultReceivingAddress() {
        UmsMember currentMember = memberService.getCurrentMember();
        UmsMemberReceiveAddress defaultReceivingAddress = memberReceiveAddressMapper.selectOneByMemberIdAndDefaultStatus(currentMember.getId(), DefaultStatus.Yes.getValue());
        if(defaultReceivingAddress == null) {
        	List<UmsMemberReceiveAddress> list = memberReceiveAddressMapper.selectByMemberId(currentMember.getId());
        	if(list != null && !list.isEmpty()) {
        		defaultReceivingAddress = list.get(0);
        	}
        }
        return defaultReceivingAddress;
    }
    
    @Override
    public UmsMemberReceiveAddress get(Long id) {
        UmsMember currentMember = memberService.getCurrentMember();
        UmsMemberReceiveAddress address = memberReceiveAddressMapper.selectOneById(id);
        if(address != null && address.getMemberId().equals(currentMember.getId())) {
        	return address;
        }
        return null;
    }

	@Override
	public List<AreaOptions> getAllArea() {
		
		String gsonStr = redisService.get(Constants.AREA_CODE);
		List<AreaOptions> optionList = new ArrayList<>();
		if(true) {
			List<UmsArea> areaList = areaMapper.selectAll();
			for(UmsArea area : areaList) {
	    		//我们这里最大的根节点ID是0，所以找出所有parent id为-1的节点，然后调用我们的递归算法
	    		if(area.getParentId().equals(-1)){
	    			optionList.add(recursionArea(area, areaList));
	    		}
	    	}
		} else {
			Gson gson = new Gson();
			optionList = gson.fromJson(gsonStr, new TypeToken<List<AreaOptions>>() {}.getType());
		}
		return optionList;
	}
	
	private AreaOptions recursionArea(UmsArea area, List<UmsArea> list) {
    	List<AreaOptions> childList = new ArrayList<>();
        // 为每一个父节点增加子树（List形式，没有则为空的list）
    	AreaOptions node = new AreaOptions();
    	node.setId(area.getId());
    	node.setName(area.getAreaName());
    	node.setLevel(area.getLevel());
    	
    	if(area.getParentId().equals(-1)) {
    		node.setPid(0);
    	} else {
    		node.setPid(area.getParentId());
    	}
     	for (UmsArea childArea : list){
            //如果子节点的pid等于父节点的ID，则说明是父子关系
    	    if(childArea.getParentId().equals(area.getId())){
                // 继续调用递归算法，将当前作为父节点，继续找他的子节点，反复执行。
    	    	childList.add(recursionArea(childArea, list));
    	    }
    	}
     	
        // 当遍历完成，返回调用的节点
     	if(!childList.isEmpty()) {
     		node.setChildren(childList);
     	} else {
     		node.setChildren(null);
     	}
    	return node;
    }
	
	private String verifyParam(UmsMemberReceiveAddress address) {
		if(StringUtils.isEmpty(address.getName())) {
    		return "收货人姓名不能为空";
    	}
    	if(StringUtils.isEmpty(address.getPhoneNumber())) {
    		return "手机号码不能为空";
    	}
    	if(address.getDefaultStatus() == null) {
    		return "是否为默认选项不能为空";
    	}
    	if(StringUtils.isEmpty(address.getPostCode())) {
    		return "邮政编码不能为空";
    	}
    	if(StringUtils.isEmpty(address.getProvince())) {
    		return "省份/直辖市不能为空";
    	}
    	if(StringUtils.isEmpty(address.getCity())) {
    		return "城市不能为空";
    	}
    	if(StringUtils.isEmpty(address.getRegion())) {
    		return "区/县不能为空";
    	}
    	if(StringUtils.isEmpty(address.getDetailAddress())) {
    		return "详细地址不能为空";
    	}
    	if(address.getAreaId() == null) {
    		return "未查询到地区信息";
    	}
    	//查询areaId是否在系统中存在，且只能是3级
    	UmsArea area = areaMapper.selectOneById(address.getAreaId());
    	if(area == null || area.getLevel() != 3) {
    		return "未查询到地区信息";
    	}
    	return null;
	}
	
}
