package com.cweb.controller.Goods;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.GoodsDeliveryAddress;
import com.hai.entity.GoodsDetail;
import com.hai.entity.GoodsShoppingCart;
import com.hai.entity.GoodsSku;
import com.hai.goods.model.ShoppingCartModel;
import com.hai.goods.service.DeliveryAddressService;
import com.hai.goods.service.GoodsRegionFreightService;
import com.hai.model.HighUserModel;
import com.hai.model.ResponseData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping(value = "/deliveryAddress")
@Api(value = "收货地址")
public class DeliveryAddressController {
    Logger log = LoggerFactory.getLogger(DeliveryAddressController.class);
    @Resource
    private DeliveryAddressService deliveryAddressService;

    @Autowired
    private UserCenter userCenter;

    @Resource
    private GoodsRegionFreightService goodsRegionFreightService;

    @RequestMapping(value = "/getDeliveryAddressList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询收货地址列表")
    public ResponseData getDeliveryAddressList(
            HttpServletRequest request
    ) {
        try {

            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            Map<String, Object> map = new HashMap<>();

            map.put("userId", userInfoModel.getHighUser().getId());

            return ResponseMsgUtil.success(deliveryAddressService.getDeliveryAddressList(map));

        } catch (Exception e) {
            log.error("GoodsDetailController --> getListUser() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value = "/insertDeliveryAddress", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增收货地址")
    public ResponseData insertDeliveryAddress(@RequestBody GoodsDeliveryAddress deliveryAddress, HttpServletRequest request) {
        try {

            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            Map<String, Object> map = new HashMap<>();

            map.put("userId", userInfoModel.getHighUser().getId());
            List<GoodsDeliveryAddress> list = deliveryAddressService.getDeliveryAddressList(map);

            if (list.size() == 0)  {
                deliveryAddress.setWhetherDefault(true);
            }

            if (deliveryAddress == null ||
                    deliveryAddress.getAddress() == null ||
                    deliveryAddress.getWhetherDefault() == null ||
                    deliveryAddress.getConsignee() == null ||
                    deliveryAddress.getPhone() == null ||
                    deliveryAddress.getRegionName() == null ||
                    deliveryAddress.getRegionId() == null
            ) {
                log.error("GoodsDetailController -> insertProduct() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            deliveryAddress.setUserId(userInfoModel.getHighUser().getId());
            deliveryAddress.setCreateTime(new Date());
            deliveryAddress.setUpdateTime(new Date());
            deliveryAddressService.insertDeliveryAddress(deliveryAddress);



            return ResponseMsgUtil.success("新增成功");

        } catch (Exception e) {
            log.error("GoodsDetailController --> insertPrice() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/updateDeliveryAddress", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改收货地址")
    public ResponseData updateDeliveryAddress(@RequestBody GoodsDeliveryAddress deliveryAddress, HttpServletRequest request) {
        try {

            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            if (deliveryAddress == null ||
                    deliveryAddress.getId() == null ||
                    deliveryAddress.getAddress() == null ||
                    deliveryAddress.getWhetherDefault() == null ||
                    deliveryAddress.getConsignee() == null ||
                    deliveryAddress.getPhone() == null ||
                    deliveryAddress.getRegionName() == null ||
                    deliveryAddress.getRegionId() == null
            ) {
                log.error("GoodsDetailController -> insertProduct() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            if (deliveryAddress.getWhetherDefault()) {
                deliveryAddressService.cleanDeliveryAddressDefault(userInfoModel.getHighUser().getId());
            }

            GoodsDeliveryAddress goodsDeliveryAddress = deliveryAddressService.findDeliveryAddressById(deliveryAddress.getId());

            if (goodsDeliveryAddress == null) {
                log.error("GoodsDetailController -> insertProduct() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前收货地址异常！");
            }

            deliveryAddress.setUserId(userInfoModel.getHighUser().getId());
            deliveryAddress.setCreateTime(goodsDeliveryAddress.getCreateTime());
            deliveryAddress.setUpdateTime(new Date());
            deliveryAddressService.updateDeliveryAddress(deliveryAddress);

            return ResponseMsgUtil.success("修改成功");

        } catch (Exception e) {
            log.error("GoodsDetailController --> insertPrice() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/findDeliveryAddressById", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询收货地址详情")
    public ResponseData findDeliveryAddressById(
            @RequestParam(value = "id", required = true) Long id
    ) {
        try {

            GoodsDeliveryAddress deliveryAddress = deliveryAddressService.findDeliveryAddressById(id);

            if (deliveryAddress == null) {
                log.error("GoodsDetailController -> findGoodsDetailById() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到相信息");
            }

            return ResponseMsgUtil.success(deliveryAddress);

        } catch (Exception e) {
            log.error("GoodsDetailController --> findGoodsDetailById() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/deleteDeliveryAddress", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "删除删除收货地址")
    public ResponseData deleteDeliveryAddress(
            @RequestParam(value = "id", required = true) Long id, HttpServletRequest request
    ) {
        try {

            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            GoodsDeliveryAddress deliveryAddress = deliveryAddressService.findDeliveryAddressById(id);

            if (deliveryAddress == null) {
                log.error("GoodsDetailController -> findGoodsDetailById() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到相关信息");
            }

            if (!Objects.equals(userInfoModel.getHighUser().getId(), deliveryAddress.getUserId())) {
                log.error("GoodsDetailController -> findGoodsDetailById() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "用户信息错误");
            }

            deliveryAddressService.deleteDeliveryAddress(id);

            return ResponseMsgUtil.success("删除成功");

        } catch (Exception e) {
            log.error("GoodsDetailController --> findGoodsDetailById() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getAddressPrice", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询收货地址包邮金额和运费金额")
    public ResponseData getAddressPrice( HttpServletRequest request
    ) {
        try {

            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            Map<String, Object> map = new HashMap<>();

            map.put("userId", userInfoModel.getHighUser().getId());
            map.put("whetherDefault", true);
            List<GoodsDeliveryAddress> list = deliveryAddressService.getDeliveryAddressList(map);

            if (list.size() == 0) {
                log.error("GoodsDetailController -> findGoodsDetailById() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到相关信息");
            }

            JSONObject object = goodsRegionFreightService.getRegionFreight(list.get(0).getRegionId());

            object.put("deliveryAddress" , list.get(0));

            return ResponseMsgUtil.success(object);

        } catch (Exception e) {
            log.error("GoodsDetailController --> findGoodsDetailById() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }
}
