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

import cn.quantgroup.user.enums.BizType;
import cn.quantgroup.xyqb.controller.middleoffice.contact.dto.ContactSaveDto;
import cn.quantgroup.xyqb.controller.middleoffice.contact.dto.ContactUpdateDto;
import cn.quantgroup.xyqb.entity.Contact;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.model.Tuple;
import cn.quantgroup.xyqb.service.user.IContactService;
import cn.quantgroup.xyqb.util.ValidationUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 联系人
 */
@RestController
//@RequestMapping("/middle_office/contacts")
public class ContactController {

    @Resource
    private IContactService contactService;

    /**
     * 获取联系人
     *
     * @param userId  用户 ID
     * @param bizType 业务类型
     * @return
     */
    @GetMapping
    public JsonResult get(Long userId, BizType bizType) {
        List<Contact> contactList = contactService.findByUserIdAndBizType(userId, bizType, true);
        return JsonResult.buildSuccessResult("", contactList);
    }

    /**
     * 更新联系人信息
     *
     * @param contactUpdateDtoList
     * @return
     */
    @PatchMapping
    public JsonResult update(@RequestBody List<ContactUpdateDto> contactUpdateDtoList) {
        contactUpdateDtoList = contactUpdateDtoList.stream()
                                                   .filter(contactUpdateDto -> (
                                                           ValidationUtil.validatePhoneNo(contactUpdateDto.getPhoneNo())
                                                                   && ValidationUtil.validateChinese(contactUpdateDto.getName())))
                                                   .collect(Collectors.toList());
        if (contactUpdateDtoList.isEmpty()) {
            return JsonResult.buildErrorStateResult("数据格式错误", null);
        }
        for (ContactUpdateDto contact : contactUpdateDtoList) {
            contactService.update(contact.getName(), contact.getPhoneNo(), contact.getRelation(), contact.getId());
        }
        return JsonResult.buildSuccessResult();
    }

    /**
     * 新增联系人
     *
     * @return
     */
    @PostMapping
    public JsonResult save(@RequestBody ContactSaveDto contactSaveDto) {
        Long userId = contactSaveDto.getUserId();
        List<Contact> contacts = contactSaveDto.getContacts();
        for (Contact contact : contacts) {
            Tuple<String, Boolean> result = contact.validAndResult();
            //数据校验
            if (!result.getValue()) {
                return JsonResult.buildErrorStateResult(result.getKey(), null);
            }
            contact.setUserId(userId);
            contact.setBizType(contactSaveDto.getBizType());
        }
        contactService.save(contacts);
        return JsonResult.buildSuccessResult();
    }

}
