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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hzs.common.core.annotation.RepeatSubmitSimple;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.constant.msg.CommonMsgConstants;
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.security.utils.SecurityUtils;
import com.hzs.common.core.utils.TransactionUtils;
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 java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 会员地址控制器
 * @Author: jiang chao
 * @Time: 2023/1/18 9:52
 * @Classname: ApiMemberAddressController
 * @PackageName: com.hzs.member.base.controller.api
 */
@Slf4j
@RequestMapping("/api/member-address")
@RestController
public class ApiMemberAddressController extends BaseController {

    @Autowired
    private ICuMemberReceivingService iCuMemberReceivingService;
    @DubboReference
    private IAreaServiceApi iAreaServiceApi;

    /**
     * 地址列表
     *
     * @return
     */
    @GetMapping("/list")
    public AjaxResult list() {
        QueryWrapper<CuMemberReceiving> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_MEMBER", SecurityUtils.getUserId());
        queryWrapper.orderByDesc("IS_DEFAULT", SystemFieldConstants.CREATION_TIME);
        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) {
        QueryWrapper<CuMemberReceiving> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SystemFieldConstants.PK_ID, id);
        queryWrapper.eq("PK_MEMBER", 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(@RequestBody MemberAddressParam param) {
        if (StringUtils.isAnyEmpty(param.getRecName(), param.getRecPhone(), param.getRecAddress())
                || ObjectUtil.emptyCount(param.getRecProvince(), param.getRecCity(), param.getIsDefault()) > 0) {
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        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();

        UpdateWrapper<CuMemberReceiving> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq(SystemFieldConstants.PK_ID, id);
        updateWrapper.eq("PK_MEMBER", userId);
        updateWrapper.set(SystemFieldConstants.DEL_FLAG, EDelFlag.DELETE.getValue());
        updateWrapper.set(SystemFieldConstants.PK_MODIFIED, userId);
        updateWrapper.set(SystemFieldConstants.MODIFIED_TIME, new Date());

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

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

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

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

}
