package com.kmall.api.api;

import com.alibaba.fastjson.JSONObject;
import com.kmall.api.annotation.IgnoreAuth;
import com.kmall.api.annotation.LoginUser;
import com.kmall.api.entity.AddressVo;
import com.kmall.api.entity.StoreVo;
import com.kmall.api.entity.UserVo;
import com.kmall.api.service.ApiAddressService;
import com.kmall.api.service.ApiStoreService;
import com.kmall.api.util.ApiBaseAction;
import com.kmall.api.util.CommonUtil;
import com.kmall.common.utils.PhoneFormatCheckUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者: @author Scott <br>
 * 时间: 2017-08-11 08:32<br>
 * 描述: ApiIndexController <br>
 */
@RestController
@RequestMapping("/api/address")
public class ApiAddressController extends ApiBaseAction {
    @Autowired
    private ApiAddressService addressService;
    @Autowired
    private ApiStoreService apiStoreService;

    /**
     * 获取用户的收货地址
     */
    @GetMapping("list")
    public Object list(@LoginUser UserVo loginUser) {
        Map param = new HashMap();
        param.put("user_id", loginUser.getId());
        List<AddressVo> addressEntities = addressService.queryList(param);
        return toResponsSuccess(addressEntities);
    }

    /**
     * 获取收货地址的详情
     */
    @IgnoreAuth
    @GetMapping("detail")
    public Object detail(Long id) {
        AddressVo entity = addressService.queryObject(id);
        return toResponsSuccess(entity);
    }

    /**
     * 添加或更新收货地址
     */
    @PostMapping("save")
    public Object save(@LoginUser UserVo loginUser) {
        JSONObject addressJson = this.getJsonRequest();
        AddressVo entity = new AddressVo();
        if (null != addressJson) {
            if (!PhoneFormatCheckUtils.isPhoneLegal(addressJson.getString("telNumber"))) {
                return toResponsFail("手机号格式有误！");
            }
            entity.setId(addressJson.getLong("id"));
            entity.setUserId(loginUser.getId());
            entity.setUserName(addressJson.getString("userName"));
            entity.setPostalCode(addressJson.getString("postalCode"));
            entity.setProvinceName(addressJson.getString("provinceName"));
            entity.setCityName(addressJson.getString("cityName"));
            entity.setCountyName(addressJson.getString("countyName"));
            entity.setDetailInfo(addressJson.getString("detailInfo"));
            entity.setNationalCode(addressJson.getString("nationalCode"));
            entity.setTelNumber(addressJson.getString("telNumber"));
            entity.setLatitude(addressJson.getBigDecimal("latitude"));
            entity.setLongitude(addressJson.getBigDecimal("longitude"));
            if (null != addressJson.getBoolean("isDefault")
                    && addressJson.getBoolean("isDefault").equals(true)) {
                entity.setIsDefault(1);
            } else {
                entity.setIsDefault(0);
            }
        }
        // 更新默认
        if (entity.getIsDefault() == 1) {
            Map params = new HashMap();
            params.put("user_id", entity.getUserId());
            params.put("is_default", 1);
            List<AddressVo> addressVoList = addressService.queryList(params);
            if (null != addressVoList) {
                for (AddressVo addressVo : addressVoList) {
                    if (null != entity.getId() && addressVo.getId().equals(entity.getId())) {
                        continue;
                    } else {
                        addressVo.setIsDefault(0);
                        addressService.update(addressVo);
                    }
                }
            }
        }
        if (null != entity.getId() && entity.getId() > 0) {
            addressService.update(entity);
            return toResponsSuccess(entity);
        } else {
            addressService.save(entity);
            return toResponsSuccess(entity);
        }
    }

    /**
     * 同步微信小程序的地址
     */
    @PostMapping("syncAddress")
    public Object syncAddress(@LoginUser UserVo loginUser) {
        JSONObject addressJson = this.getJsonRequest();
        AddressVo entity = new AddressVo();
        if (null != addressJson) {
            if (!PhoneFormatCheckUtils.isPhoneLegal(addressJson.getString("telNumber"))) {
                return toResponsFail("手机号格式有误！");
            }
            entity.setUserId(loginUser.getId());
            entity.setUserName(addressJson.getString("userName"));
            entity.setPostalCode(addressJson.getString("postalCode"));
            entity.setProvinceName(addressJson.getString("provinceName"));
            entity.setCityName(addressJson.getString("cityName"));
            entity.setCountyName(addressJson.getString("countyName"));
            entity.setDetailInfo(addressJson.getString("detailInfo"));
            entity.setNationalCode(addressJson.getString("nationalCode"));
            entity.setTelNumber(addressJson.getString("telNumber"));
            entity.setLatitude(addressJson.getBigDecimal("latitude"));
            entity.setLongitude(addressJson.getBigDecimal("longitude"));
            if (null != addressJson.getBoolean("isDefault")
                    && addressJson.getBoolean("isDefault").equals(true)) {
                entity.setIsDefault(1);
            } else {
                entity.setIsDefault(0);
            }
        }
        //
        Map params = new HashMap();
        params.put("user_id", entity.getUserId());
        List<AddressVo> addressVoList = addressService.queryList(params);
        if (null != addressVoList) {
            for (AddressVo addressVo : addressVoList) {
                if (null != entity.getDetailInfo() && addressVo.getDetailInfo().equals(entity.getDetailInfo())) {
                    return toResponsSuccess(addressVo);
                }
            }
        }
        addressService.save(entity);
        return toResponsSuccess(entity);
    }

    /**
     * 删除指定的收货地址
     */
    @IgnoreAuth
    @PostMapping("delete")
    public Object delete() {
        JSONObject jsonParam = this.getJsonRequest();
        addressService.delete(jsonParam.getIntValue("id"));
        return toResponsSuccess("");
    }

    /**
     * 校验选中的地址，门店是否可以配送
     */
    @PostMapping("checkStore")
    public Object checkStore() {
        JSONObject jsonParam = this.getJsonRequest();
        Long storeId = jsonParam.getLong("storeId");
        AddressVo addressVo = jsonParam.getObject("checkedAddress", AddressVo.class);
        if (null == addressVo || null == addressVo.getLatitude() || null == addressVo.getLongitude()) {
            return toResponsFail("当前地址距离门店过远，无法配送，抱歉！");
        }
        StoreVo storeVo = apiStoreService.queryObject(storeId);
        if (null == storeVo || null == storeVo.getLatitude() || null == storeVo.getLongitude()) {
            return toResponsFail("当前门店暂时无法配送，抱歉！");
        }
        double distance = CommonUtil.getDistance(storeVo.getLatitude().doubleValue(), storeVo.getLongitude().doubleValue(),
                addressVo.getLatitude().doubleValue(), addressVo.getLongitude().doubleValue());
        if (storeVo.getCoverRadius().compareTo(new BigDecimal(distance)) < 0) {
            return toResponsFail("当前地址距离门店过远，无法配送，抱歉！");
        }
        //
        storeVo.setDistance(new BigDecimal(distance));
        return toResponsSuccess(storeVo);
    }
}