package modules.address;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.StrKit;
import common.interceptor.LoginInterceptor;
import common.interceptor.empty.EmptyInterface;
import common.model.Address;
import common.model.User;
import common.utils.http.MyController;
import common.utils.http.MyRet;
import modules.user.UserService;

import java.util.List;

@Before(LoginInterceptor.class)
public class AddressController extends MyController {

    @Inject
    private AddressService service;
    @Inject
    private UserService userService;

    public void hello() {
        renderText("Hello, Address!");
    }
    
    public void getDefaultAddress() {
        User user = userService.findUserByMobileNumber(getSessionAttr("mobile_number"));
        Long userId = user.getId();
        Address address = service.findDefaultByUserId(userId);
        if (address == null) {
            renderJson(MyRet.fail("默认地址不存在，请添加").setCode(MyRet.CODE_NO_ADDR));
            return;
        }
        renderJson(MyRet.ok("获取成功").setData(address));
    }

    /**
     * 获取用户的收货地址列表
     */
    public void list() {
        User user = userService.findUserByMobileNumber(getSessionAttr("mobile_number"));
        List<Address> addresses = service.findByUserId(user.getId());
        renderJson(MyRet.ok("获取成功").setData(addresses));
    }

    /**
     * 获取单个收货地址详情
     */
    public void get() {
        User user = userService.findUserByMobileNumber(getSessionAttr("mobile_number"));
        JSONObject requestBodyJson = MyController.getJsonModelByRequestAndType(getRequest(), JSONObject.class);
        Integer addressId;
        try {
            addressId = requestBodyJson.getInteger("id");
        } catch (Exception e) {
            renderJson(MyRet.fail("你传入的 id 有些问题：" + e.getMessage()).setData(requestBodyJson));
            return;
        }
        if (addressId == null) {
            renderJson(MyRet.fail("id 不能为空"));
            return;
        }

        Address address = service.findById(addressId, user.getId());
        if (address == null) {
            renderJson(MyRet.fail("地址不存在"));
            return;
        }
        renderJson(MyRet.ok("获取成功").setData(address));
    }

    /**
     * 新增收货地址
     */
    @EmptyInterface({"recipient_name", "phone_number", "detailed_address"})
    public void save() {
        User user = userService.findUserByMobileNumber(getSessionAttr("mobile_number"));
        JSONObject json = MyController.getJsonModelByRequestAndType(getRequest(), JSONObject.class);

        Address address = new Address();

        // 校验收货人姓名
        String recipientName = json.getString("recipient_name");
        if (StrKit.isBlank(recipientName)) {
            renderJson(MyRet.fail("收货人姓名不能为空"));
            return;
        }
        address.setRecipientName(recipientName);

        // 校验手机号码
        String phoneNumber = json.getString("phone_number");
        if (StrKit.isBlank(phoneNumber)) {
            renderJson(MyRet.fail("手机号码不能为空"));
            return;
        }
        address.setPhoneNumber(phoneNumber);

        // 校验详细地址
        String detailedAddress = json.getString("detailed_address");
        if (StrKit.isBlank(detailedAddress)) {
            renderJson(MyRet.fail("详细地址不能为空"));
            return;
        }
        address.setDetailedAddress(detailedAddress);

        // 处理是否默认地址
        Object isDefaultObj = json.get("is_default");
        if (isDefaultObj != null) {
            try {
                int isDefaultValue = com.alibaba.fastjson.util.TypeUtils.castToInt(isDefaultObj);
                if (isDefaultValue == 0 || isDefaultValue == 1) {
                    address.setIsDefault(isDefaultValue);
                } else {
                    renderJson(MyRet.fail("is_default 字段的值必须是 0 或 1"));
                    return;
                }
            } catch (Exception e) {
                renderJson(MyRet.fail("is_default 字段格式不正确，必须是数字 0 或 1"));
                return;
            }
        }

        address.setUserId(user.getId().intValue());

        try {
            if (service.save(address)) {
                renderJson(MyRet.ok("保存成功").setData(address));
            } else {
                renderJson(MyRet.fail("保存失败"));
            }
        } catch (RuntimeException e) {
            // 捕获地址数量超过上限的异常
            renderJson(MyRet.fail(e.getMessage()));
        }
    }
    
    /**
     * 修改收货地址
     */
    public void update() {
        User user = userService.findUserByMobileNumber(getSessionAttr("mobile_number"));
        JSONObject json = MyController.getJsonModelByRequestAndType(getRequest(), JSONObject.class);

        // 校验地址ID
        Integer id = json.getInteger("id");
        if (id == null) {
            renderJson(MyRet.fail("地址ID不能为空"));
            return;
        }
        
        // 查找并验证地址是否存在
        Address address = service.findById(id, user.getId());
        if (address == null) {
            renderJson(MyRet.fail("地址不存在"));
            return;
        }

        // 更新收货人姓名（如果提供）
        String recipientName = json.getString("recipient_name");
        if (StrKit.notBlank(recipientName)) {
            address.setRecipientName(recipientName);
        }

        // 更新手机号码（如果提供）
        String phoneNumber = json.getString("phone_number");
        if (StrKit.notBlank(phoneNumber)) {
            address.setPhoneNumber(phoneNumber);
        }

        // 更新详细地址（如果提供）
        String detailedAddress = json.getString("detailed_address");
        if (StrKit.notBlank(detailedAddress)) {
            address.setDetailedAddress(detailedAddress);
        }

        // 处理是否默认地址（如果提供）
        Object isDefaultObj = json.get("is_default");
        if (isDefaultObj != null) {
            try {
                int isDefaultValue = com.alibaba.fastjson.util.TypeUtils.castToInt(isDefaultObj);
                if (isDefaultValue == 0 || isDefaultValue == 1) {
                    address.setIsDefault(isDefaultValue);
                } else {
                    renderJson(MyRet.fail("is_default 字段的值必须是 0 或 1"));
                    return;
                }
            } catch (Exception e) {
                renderJson(MyRet.fail("is_default 字段格式不正确，必须是数字 0 或 1"));
                return;
            }
        }

        if (service.update(address)) {
            renderJson(MyRet.ok("更新成功").setData(address));
        } else {
            renderJson(MyRet.fail("更新失败"));
        }
    }

    /**
     * 删除收货地址
     */
    public void delete() {
        User user = userService.findUserByMobileNumber(getSessionAttr("mobile_number"));
        JSONObject requestBodyJson = MyController.getJsonModelByRequestAndType(getRequest(), JSONObject.class);
        Integer addressId;
        try {
            addressId = requestBodyJson.getInteger("id");
        } catch (Exception e) {
            renderJson(MyRet.fail("你传入的 id 有些问题：" + e.getMessage()).setData(requestBodyJson));
            return;
        }
        if (addressId == null) {
            renderJson(MyRet.fail("id 不能为空"));
            return;
        }

        if (service.delete(addressId, user.getId())) {
            renderJson(MyRet.ok("删除成功"));
        } else {
            renderJson(MyRet.fail("删除失败"));
        }
    }

    /**
     * 设置默认地址
     */
    public void setDefault() {
        User user = userService.findUserByMobileNumber(getSessionAttr("mobile_number"));
        JSONObject requestBodyJson = MyController.getJsonModelByRequestAndType(getRequest(), JSONObject.class);
        Integer addressId;
        try {
            addressId = requestBodyJson.getInteger("id");
        } catch (Exception e) {
            renderJson(MyRet.fail("你传入的 id 有些问题：" + e.getMessage()).setData(requestBodyJson));
            return;
        }
        if (addressId == null) {
            renderJson(MyRet.fail("id 不能为空"));
            return;
        }

        if (service.setDefault(addressId, user.getId())) {
            renderJson(MyRet.ok("设置成功"));
        } else {
            renderJson(MyRet.fail("设置失败"));
        }
    }
}