package com.jeesharp.business.mall.controller;

import com.jeesharp.business.modules.mall.application.MallMemberAddressApplicationService;
import com.jeesharp.business.modules.mall.dto.MallMemberAddressSaveDTO;
import com.jeesharp.business.modules.mall.entity.MallMemberAddress;
import com.jeesharp.business.modules.mall.enums.MallMemberAddressDefaultEnum;
import com.jeesharp.business.modules.mall.vo.MallMemberAddressInfoVO;
import com.jeesharp.framework.memberauth.utils.MemberAuthUtils;
import com.jeesharp.framework.memberauth.web.BaseMobileController;
import com.jeesharp.framework.pojo.AjaxResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 小程序商城收货地址（{@code mall_member_address}），与订单接口分离。
 *
 * @author jeesharp
 * @since 2026-05-19
 */
@RestController
@RequestMapping("${jeesharp.web.mobilePath}/address")
@Tag(name = "小程序-商城收货地址")
@AllArgsConstructor
public class MallMemberAddressMobileController extends BaseMobileController {

    private final MallMemberAddressApplicationService mallMemberAddressApplicationService;

    @Operation(summary = "收货地址列表")
    @GetMapping("/list")
    public AjaxResult<List<Map<String, Object>>> addressList() {
        String memberId = MemberAuthUtils.getLoginUserId();
        List<MallMemberAddress> list = mallMemberAddressApplicationService.getMemberAddresses(memberId);
        List<Map<String, Object>> rows = list.stream().map(this::toAddressRow).collect(Collectors.toList());
        return AjaxResult.okData(rows);
    }

    @Operation(summary = "新增收货地址")
    @PostMapping("/create")
    public AjaxResult<Map<String, String>> addressCreate(@RequestBody @Valid MallMemberAddressSaveDTO dto) {
        String memberId = MemberAuthUtils.getLoginUserId();
        dto.setMemberId(memberId);
        String newId = mallMemberAddressApplicationService.saveReturningId(dto);
        return AjaxResult.ok("保存成功", Map.of("id", newId == null ? "" : newId));
    }

    @Operation(summary = "编辑收货地址")
    @PutMapping("/update/{id}")
    public AjaxResult<Void> addressUpdate(@PathVariable("id") String id, @RequestBody @Valid MallMemberAddressSaveDTO dto) {
        String memberId = MemberAuthUtils.getLoginUserId();
        MallMemberAddressInfoVO existing = mallMemberAddressApplicationService.get(id);
        if (existing == null || !memberId.equals(existing.getMemberId())) {
            return AjaxResult.failMsg("地址不存在");
        }
        dto.setId(id);
        dto.setMemberId(memberId);
        mallMemberAddressApplicationService.save(dto);
        return AjaxResult.ok("保存成功");
    }

    @Operation(summary = "删除收货地址")
    @DeleteMapping("/delete/{id}")
    public AjaxResult<Void> addressDelete(@PathVariable("id") String id) {
        String memberId = MemberAuthUtils.getLoginUserId();
        MallMemberAddressInfoVO existing = mallMemberAddressApplicationService.get(id);
        if (existing == null || !memberId.equals(existing.getMemberId())) {
            return AjaxResult.failMsg("地址不存在");
        }
        mallMemberAddressApplicationService.delete(id);
        return AjaxResult.ok("删除成功");
    }

    @Operation(summary = "设为默认地址")
    @PostMapping("/default/{id}")
    public AjaxResult<Void> addressDefault(@PathVariable("id") String id) {
        String memberId = MemberAuthUtils.getLoginUserId();
        mallMemberAddressApplicationService.setDefaultAddress(id, memberId);
        return AjaxResult.ok("设置成功");
    }

    private Map<String, Object> toAddressRow(MallMemberAddress a) {
        Map<String, Object> m = new LinkedHashMap<>();
        m.put("id", a.getId());
        m.put("name", a.getReceiverName());
        m.put("phone", a.getReceiverMobile());
        m.put("province", a.getProvince());
        m.put("provinceCode", a.getProvinceCode());
        m.put("city", a.getCity());
        m.put("cityCode", a.getCityCode());
        m.put("district", a.getDistrict());
        m.put("districtCode", a.getDistrictCode());
        m.put("detail", a.getDetailAddress());
        m.put("isDefault", MallMemberAddressDefaultEnum.YES.getValue().equals(a.getIsDefault()));
        return m;
    }
}
