package com.hzs.member.base.controller.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hzs.common.core.annotation.RepeatSubmitSimple;
import com.hzs.common.core.constant.msg.AreaConstants;
import com.hzs.common.core.enums.EDelFlag;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.member.address.CuMemberReceiving;
import com.hzs.common.domain.system.base.BdArea;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.address.service.ICuMemberReceivingService;
import com.hzs.member.base.param.MemberAddressParam;
import com.hzs.member.base.vo.MemberAddressVO;
import com.hzs.system.base.IAreaServiceApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 会员地址控制器
 */
@Slf4j
@RequestMapping("/api/member-address")
@RestController
public class ApiMemberAddressController extends BaseController {

    @Autowired
    private ICuMemberReceivingService iCuMemberReceivingService;

    @DubboReference
    IAreaServiceApi iAreaServiceApi;

    /**
     * 地址列表
     *
     * @return
     */
    @GetMapping("/list")
    public AjaxResult list() {
        LambdaQueryWrapper<CuMemberReceiving> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMemberReceiving::getPkMember, SecurityUtils.getUserId());
        queryWrapper.orderByDesc(CuMemberReceiving::getIsDefault, CuMemberReceiving::getCreationTime);
        List<CuMemberReceiving> list = iCuMemberReceivingService.list(queryWrapper);

        List<MemberAddressVO> resultList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            // 根据国家获取地区map
            Map<Integer, String> areaMap = iAreaServiceApi.getAreaMap(SecurityUtils.getPkCountry()).getData();

            for (CuMemberReceiving cuMemberReceiving : list) {
                MemberAddressVO memberAddressVO = BeanUtil.copyProperties(cuMemberReceiving, MemberAddressVO.class);

                // 所在地区处理
                String recArea = "";
                String recProvince = areaMap.get(cuMemberReceiving.getRecProvince());
                if (StringUtils.isNotEmpty(recProvince)) {
                    memberAddressVO.setRecProvinceVal(recProvince);
                    recArea += recProvince;
                }
                String recCity = areaMap.get(cuMemberReceiving.getRecCity());
                if (StringUtils.isNotEmpty(recCity)) {
                    memberAddressVO.setRecCityVal(recCity);
                    recArea += recCity;
                }
                String recCounty = areaMap.get(cuMemberReceiving.getRecCounty());
                if (StringUtils.isNotEmpty(recCounty)) {
                    memberAddressVO.setRecCountyVal(recCounty);
                    recArea += recCounty;
                }
                memberAddressVO.setRecArea(recArea);

                resultList.add(memberAddressVO);
            }

        }
        return AjaxResult.success(resultList);
    }

    /**
     * 地址详情
     *
     * @param id
     * @return
     */
    @GetMapping("/detail/{id}")
    public AjaxResult detail(@PathVariable("id") Long id) {
        LambdaQueryWrapper<CuMemberReceiving> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMemberReceiving::getPkId, id);
        queryWrapper.eq(CuMemberReceiving::getPkMember, SecurityUtils.getUserId());
        CuMemberReceiving cuMemberReceiving = iCuMemberReceivingService.getOne(queryWrapper);
        if (null == cuMemberReceiving) {
            return AjaxResult.error("会员地址不存在");
        }
        return AjaxResult.success(BeanUtil.copyProperties(cuMemberReceiving, MemberAddressVO.class));
    }

    /**
     * 地址保存
     *
     * @param param
     * @return
     */
    @RepeatSubmitSimple
    @PostMapping("/save")
    public AjaxResult save(@Valid @RequestBody MemberAddressParam param) {
        if (param.getRecCity().equals(0) || param.getRecCounty().equals(0)) {
            // 区为0 或 市为0，没有选择区或者没有选择市
            // 香港、澳门只有省，台湾有省、市
            BdArea province = iAreaServiceApi.getArea(param.getRecProvince()).getData();
            if (null == province) {
                return AjaxResult.error("选择区域省不存在，请重新选择");
            }
            if (param.getRecCity().equals(0)
                    && !AreaConstants.XIANG_GANG.equals(province.getCode())
                    && !AreaConstants.AO_MEN.equals(province.getCode())) {
                // 市为0，不是香港、港门，则需要提示
                return AjaxResult.error("请选择市");
            }
            if (param.getRecCounty().equals(0)
                    && !AreaConstants.XIANG_GANG.equals(province.getCode())
                    && !AreaConstants.AO_MEN.equals(province.getCode())
                    && !AreaConstants.TAI_WAN.equals(province.getCode())) {
                // 区为0，不是香港、港门、台湾，则需要提示
                return AjaxResult.error("请选择区");
            }
        }
        // 联系方式去一下空格
        param.setRecPhone(param.getRecPhone().replace(" ", ""));

        return toAjax(iCuMemberReceivingService.save(param, SecurityUtils.getUserId(), SecurityUtils.getPkCountry()));
    }

    /**
     * 地址删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {
        Long userId = SecurityUtils.getUserId();

        LambdaUpdateWrapper<CuMemberReceiving> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CuMemberReceiving::getPkId, id);
        updateWrapper.eq(CuMemberReceiving::getPkMember, userId);
        updateWrapper.set(CuMemberReceiving::getDelFlag, EDelFlag.DELETE.getValue());
        updateWrapper.set(CuMemberReceiving::getPkModified, userId);
        updateWrapper.set(CuMemberReceiving::getModifiedTime, new Date());

        return toAjax(iCuMemberReceivingService.update(updateWrapper));
    }

    /**
     * 设为默认
     *
     * @return
     */
    @PutMapping("/default/{id}")
    public AjaxResult setDefault(@PathVariable("id") Long id) {
        Long userId = SecurityUtils.getUserId();

        LambdaQueryWrapper<CuMemberReceiving> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMemberReceiving::getPkId, id);
        queryWrapper.eq(CuMemberReceiving::getPkMember, userId);
        CuMemberReceiving cuMemberReceiving = iCuMemberReceivingService.getOne(queryWrapper);
        if (null == cuMemberReceiving) {
            return AjaxResult.success("会员地址不存在");
        }

        return toAjax(iCuMemberReceivingService.setDefault(id, userId));
    }

}
