package com.neusoft.smart.pos.address.controller;

import com.neusoft.smart.pos.address.constants.AddressErrorCode;
import com.neusoft.smart.pos.address.dto.*;
import com.neusoft.smart.pos.address.persistent.domain.UserCargoAddress;
import com.neusoft.smart.pos.address.service.UserCargoAddressService;
import com.neusoft.smart.pos.framework.constants.CommonErrorCode;
import com.neusoft.smart.pos.framework.dto.ResponseData;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.utils.RequestHeaderUtil;
import com.neusoft.smart.pos.utils.UserCacheUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

@RestController
@RequestMapping("/address")
public class UserCargoAddressController {
    @Resource
    private UserCargoAddressService userCargoAddressService;

    @ApiOperation("创建地址")
    @PostMapping("/addAddress")
    @Transactional
    public ResponseData<?> createAddress(@RequestBody PostUserCargoAddressRequest request) {
        //verify userId
        if(request.getUserId() == null) {
            request.setUserId(UserCacheUtils.getUserInfo(RequestHeaderUtil.getUsername()).getId());
        }
        userCargoAddressService.insertUserCargoAddress(request.getUserId(), request.getAddressList());
        return new ResponseData<>();
    }

    @ApiOperation("查询地址")
    @PostMapping("/queryAddress")
    @Transactional
    public ResponseData<GetUserCargoAddressResponse> queryAddress(@RequestBody GetUserCargoAddressRequest request) throws InvocationTargetException, IllegalAccessException {
        //verify userId
        if(request.getUserId() == null) {
            request.setUserId(UserCacheUtils.getUserInfo(RequestHeaderUtil.getUsername()).getId());
        }
        // verify addressType
        Integer addressType;
        if(request.getAddressType() != null && request.getAddressType().equals("all")) {
            addressType = -1;
        } else {
            try {
                addressType = Integer.parseInt(request.getAddressType());
            } catch (Exception e) {
                throw new BusinessCommonException(AddressErrorCode.ADDRESS_TYPE_FORMAT_ERROR);
            }
        }

        // verify priorityList
        List<GetUserCargoAddressRequest.PriorityInfo> prioritySList = request.getPriorityList();
        List<Integer> priorityList = new ArrayList<>();
        for (GetUserCargoAddressRequest.PriorityInfo priorityInfo:prioritySList) {
            Integer priority;
            if(priorityInfo.getPriority().equals("all")) {
                priority = -1;
                priorityList.clear();
                priorityList.add(priority);
                break;
            } else {
                try {
                    priority = Integer.parseInt(priorityInfo.getPriority());
                } catch (Exception e) {
                    throw new BusinessCommonException(AddressErrorCode.PRIORITY_FORMAT_ERROR);
                }
            }
            priorityList.add(priority);
        }
        priorityList = new ArrayList<Integer>(new HashSet<Integer>(priorityList)); //去掉重复项
        Collections.sort(priorityList); // priority从小到大排序

        List<UserCargoAddress> list = new ArrayList<>();
        for (Integer priority:priorityList) {
            list.addAll(userCargoAddressService.getUserCargoAddressByUserId(request.getUserId(),addressType,priority));
        }
        GetUserCargoAddressResponse response = new GetUserCargoAddressResponse();
        response.setUserId(request.getUserId());
        List<GetUserCargoAddressResponse.AddressInfo> addressList = new ArrayList<>();
        for (UserCargoAddress address:list) {
            GetUserCargoAddressResponse.AddressInfo addressInfo = new GetUserCargoAddressResponse.AddressInfo();
            BeanUtils.copyProperties(addressInfo, address);
            addressList.add(addressInfo);
        }
        response.setAddressList(addressList);
        return new ResponseData<>(response);
    }

    @ApiOperation("获取用户指定ID的地址")
    @GetMapping("/getAddress/{addressId}")
    public ResponseData<UserCargoAddress> getAddressById(@PathVariable Integer addressId) {
        UserCargoAddress address = userCargoAddressService.getUserCargoAddressById(addressId);
        if(address != null) {
            return new ResponseData<>(address);
        } else {
            return new ResponseData<>(AddressErrorCode.NOT_YOUR_ADDRESS.getCode(), AddressErrorCode.NOT_YOUR_ADDRESS.getMessage(), null);
        }
    }

    @ApiOperation("更新地址")
    @PostMapping("/updateAddress")
    @Transactional
    public ResponseData<?> updateAddress(@RequestBody PostUpdateUserCargoAddressRequest request) {
        //verify userId
        if(request.getUserId() == null) {
            request.setUserId(UserCacheUtils.getUserInfo(RequestHeaderUtil.getUsername()).getId());
        }
        userCargoAddressService.updateUserAddressById(request);
        return new ResponseData<>();
    }

    @ApiOperation("删除地址")
    @PostMapping("/deleteAddress")
    @Transactional
    public ResponseData<?> deleteAddress(@RequestBody PostDeleteUserCargoAddressRequest request) {
        //verify userId
        if(request.getUserId() == null) {
            request.setUserId(UserCacheUtils.getUserInfo(RequestHeaderUtil.getUsername()).getId());
        }
        if(userCargoAddressService.deleteUserAddressById(request)>0) {
            return new ResponseData<>(CommonErrorCode.SUCCESS.getCode(), CommonErrorCode.SUCCESS.getMessage(), null);
        } else {
            return new ResponseData<>(AddressErrorCode.UNKNOWN.getCode(), AddressErrorCode.UNKNOWN.getMessage(), null);
        }
    }
}
