package cn.quantgroup.xyqb.controller.middleoffice.userext;

import cn.quantgroup.user.enums.BizType;
import cn.quantgroup.user.enums.OccupationEnum;
import cn.quantgroup.xyqb.controller.middleoffice.userext.req.UserExtReq;
import cn.quantgroup.xyqb.entity.Address;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.UserExtInfo;
import cn.quantgroup.xyqb.event.UserExtInfoSaveEvent;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.service.user.IAddressService;
import cn.quantgroup.xyqb.service.user.IContactService;
import cn.quantgroup.xyqb.service.user.IUserDetailService;
import cn.quantgroup.xyqb.service.user.IUserExtInfoService;
import cn.quantgroup.xyqb.service.user.IUserService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户扩展信息
 */
@RestController
@RequestMapping("/middle_office/user/ext")
public class UserExtController {

    @Resource
    private IUserExtInfoService userExtInfoService;

    @Resource
    private IContactService contactService;

    @Resource
    private IUserDetailService userDetailService;

    @Resource
    private IAddressService addressService;

    @Resource
    private IUserService userService;

    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    //todo 保存失败的各种场景。
    @PutMapping("/{userId}")
    public JsonResult ext(@PathVariable Long userId, @RequestBody UserExtReq userExtReq) {
        if (userExtReq.getEmail() != null) {
            userDetailService.updateUserEmail(userId, userExtReq.getEmail());
        }
        if (userExtReq.getQq() != null) {
            userDetailService.updateUserQq(userId, userExtReq.getQq());
        }
        if (CollectionUtils.isNotEmpty(userExtReq.getContacts())) {
            contactService.save(userId, userExtReq.getContacts());
        }
        if (userExtReq.getAddress() != null) {
            Address address = addressService.findByUserId(userId);
            if (address != null) {
                userExtReq.getAddress().setId(address.getId());
            }
            userExtReq.getAddress().setUserId(userId);
            addressService.save(userExtReq.getAddress());
        }
        if (userExtReq.getExtInfo() != null) {
            UserExtInfo extInfo = userExtInfoService.findByUserId(userId);
            if (extInfo != null) {
                Long id = extInfo.getId();
                userExtReq.getExtInfo().setId(id);
            }
            userExtReq.getExtInfo().setUserId(userId);

            if (null != userExtReq.getExtInfo().getOccupationEnum()) {//学生转其他
                if (OccupationEnum.STUDENT == userExtReq.getExtInfo().getOccupationEnum()) {
                    userExtReq.getExtInfo().setOccupationEnum(OccupationEnum.OTHER);
                }
            }
            userExtInfoService.save(userExtReq.getExtInfo());
            applicationEventPublisher.publishEvent(new UserExtInfoSaveEvent(this, userExtReq.getExtInfo()));
        }
        return JsonResult.buildSuccessResult();
    }

    @GetMapping("/userId/{userId}")
    public JsonResult query(@PathVariable Long userId,
                            @RequestParam(defaultValue = "false") Boolean address,
                            @RequestParam(defaultValue = "false") Boolean contacts,
                            @RequestParam(defaultValue = "false") Boolean extInfo) {
        Map<String, Object> result = new HashMap<>();
        if (address) {
            result.put("address", addressService.findByUserId(userId));
        }
        if (contacts) {
            result.put("contacts", contactService.findByUserIdAndBizType(userId, BizType.CASH, true));
        }
        if (extInfo) {
            result.put("extInfo", userExtInfoService.findByUserId(userId));
        }
        return JsonResult.buildSuccessResultGeneric(result);
    }

    @GetMapping("/phoneNo/{phoneNo}")
    public JsonResult query(@PathVariable String phoneNo,
                            @RequestParam(defaultValue = "false") Boolean address,
                            @RequestParam(defaultValue = "false") Boolean contacts,
                            @RequestParam(defaultValue = "false") Boolean extInfo) {
        User user = userService.findByPhoneWithCache(phoneNo);
        if (user == null) {
            return JsonResult.buildSuccessResult();
        }
        Long userId = user.getId();

        //todo duplicated
        Map<String, Object> result = new HashMap<>();
        if (address) {
            result.put("address", addressService.findByUserId(userId));
        }
        if (contacts) {
            result.put("contacts", contactService.findByUserIdAndBizType(userId, BizType.CASH, true));
        }
        if (extInfo) {
            result.put("extInfo", userExtInfoService.findByUserId(userId));
        }

        return JsonResult.buildSuccessResultGeneric(result);
    }

}
