package org.springblade.modules.app.manager;

import com.alibaba.fastjson.JSON;
import com.wn.common.datamodel.ModelConvertUtil;
import com.wn.common.validator.Validator;
import org.springblade.modules.app.common.dto.*;
import org.springblade.modules.app.common.enums.*;
import org.springblade.modules.app.common.query.ApplicationQuery;
import org.springblade.modules.app.common.query.RelationQuery;
import org.springblade.modules.app.common.query.UserQuery;
import org.springblade.modules.app.constant.Constants;
import org.springblade.modules.app.constant.ErrorCode;
import org.springblade.modules.app.service.IApplicationInfoService;
import org.springblade.modules.app.service.ISlaughterBuyerRelationLogService;
import org.springblade.modules.app.service.ISlaughterBuyerRelationService;
import org.springblade.modules.app.service.IAppUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class SlaughterBuyerRelationManager {

    private final String HEAD = this.getClass().getSimpleName() + ":";

    @Autowired
    private ISlaughterBuyerRelationService slaughterBuyerRelationService;
    @Autowired
    private IAppUserService userService;
    @Autowired
    private ISlaughterBuyerRelationLogService slaughterBuyerRelationLogService;
    @Autowired
    private MessageLoggingManager messageLoggingManager;
    @Autowired
    private IApplicationInfoService applicationInfoService;
    @Autowired
    private UserManager userManager;

    public List<SlaughterBuyerRelationDTO> list(Integer state, UserDTO userDTO) {
        RelationQuery query = new RelationQuery();
        query.setState(state);
        if(userDTO.getType() == UserTypeEnum.SLAUGHTER_HOUSE.getCode()){
            query.setSlaughterHouseId(userDTO.getId());
        }else if (userDTO.getType() == UserTypeEnum.SLAUGHTER.getCode()){
            query.setBuyerUserId(userDTO.getId());
        }
        List<SlaughterBuyerRelationDTO> list = slaughterBuyerRelationService.queryList(query);
        List<SlaughterBuyerRelationDTO> returnList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(list)){
            for(SlaughterBuyerRelationDTO dto : list){
                UserDTO buyerUser = userService.getUserByIdAll(dto.getBuyerUserId());
                dto.setBuyerUserName(buyerUser.getUserName());
                dto.setBuyerAddress(buyerUser.getAddress());
                UserDTO houseUser = userService.getUserByIdAll(dto.getSlaughterHouseId());
                //只有代宰户管理端审核启用的，才可以在列表中展示操作
                if(houseUser!=null && houseUser.getState().intValue() == UserStateEnum.PASS.getCode()){
                    dto.setSlaughterHouseName(houseUser.getUserName());
                    dto.setHouseUserAddress(houseUser.getAddress());
                    if (userDTO.getType() != UserTypeEnum.SLAUGHTER.getCode()) {
                        dto.setIfAutoApply(null);
                    }
                    returnList.add(dto);
                }
            }
        }
        return returnList;
    }

    public List<SlaughterBuyerRelationDTO> list(Integer state, String token) {
        UserDTO userDTO = userManager.getUserInfo(token);
        RelationQuery query = new RelationQuery();
        query.setState(state);
        if(userDTO.getType() == UserTypeEnum.SLAUGHTER_HOUSE.getCode()){
            query.setSlaughterHouseId(userDTO.getId());
        }else if (userDTO.getType() == UserTypeEnum.SLAUGHTER.getCode()){
            query.setBuyerUserId(userDTO.getId());
        }
        List<SlaughterBuyerRelationDTO> list = slaughterBuyerRelationService.queryList(query);
        List<SlaughterBuyerRelationDTO> returnList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(list)){
            for(SlaughterBuyerRelationDTO dto : list){
                UserDTO buyerUser = userService.getUserByIdAll(dto.getBuyerUserId());
                dto.setBuyerUserName(buyerUser.getUserName());
                dto.setBuyerAddress(buyerUser.getAddress());
                UserDTO houseUser = userService.getUserByIdAll(dto.getSlaughterHouseId());
                //只有代宰户管理端审核启用的，才可以在列表中展示操作
                if(houseUser!=null && houseUser.getState().intValue() == UserStateEnum.PASS.getCode()){
                    dto.setSlaughterHouseName(houseUser.getUserName());
                    dto.setHouseUserAddress(houseUser.getAddress());
                    if (userDTO.getType() != UserTypeEnum.SLAUGHTER.getCode()) {
                        dto.setIfAutoApply(null);
                    }
                    returnList.add(dto);
                }
            }
        }
        return returnList;
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean bind(String name, UserDTO userDTO){
        Validator.notEmpty(name,ErrorCode.INPUT_PARAMETERS_NULL);
        UserQuery query = new UserQuery();
        query.setName(name);
        query.setType(UserTypeEnum.SLAUGHTER.getCode());
        UserDTO oneUser = userService.getOneUser(query);
        Validator.isTrue(oneUser!=null && oneUser.getState() == UserStateEnum.PASS.getCode(), ErrorCode.SLAUGHTER_IS_NULL);

        SlaughterBuyerRelationDTO slaughterBuyerRelationDTO = slaughterBuyerRelationService.queryByHouseIdAndBuyerId(userDTO.getId(),oneUser.getId());
        if(slaughterBuyerRelationDTO!=null ){
            //校验是否已经有绑定关系
            Validator.isTrue(slaughterBuyerRelationDTO.getState() == RelationStateEnum.REJECT.getCode(), ErrorCode.RELATION_IS_EXISTED);
            //驳回重新绑定
            slaughterBuyerRelationDTO.setState(RelationStateEnum.UNCHECK.getCode());
            Validator.isTrue(slaughterBuyerRelationService.update(slaughterBuyerRelationDTO),ErrorCode.RELATION_UPDATE_FAIL);
        }else{
            SlaughterBuyerRelationDTO dto = new SlaughterBuyerRelationDTO();
            dto.setBuyerUserId(oneUser.getId());
            dto.setSlaughterHouseId(userDTO.getId());
            dto.setInitiator(UserTypeEnum.SLAUGHTER_HOUSE.getCode());
            Validator.notNull(slaughterBuyerRelationService.insert(dto),ErrorCode.RELATION_INSERT_FAIL);
        }

        //增加审核信息
        ApplicationInfoDTO applicationInfoDTO = new ApplicationInfoDTO();
        applicationInfoDTO.setType(ApplicationTypeEnum.SLAUGHTER_HOUSE.getCode());
        applicationInfoDTO.setLinkId(userDTO.getId());
        applicationInfoDTO.setLinkTable(Constants.TB_USER);
        applicationInfoDTO.setSubmitUserId(userDTO.getId());
        applicationInfoDTO.setSubmitPhone(userDTO.getPhone());
        applicationInfoDTO.setSubmitUserName(userDTO.getUserName());
        applicationInfoDTO.setApplyUserId(oneUser.getId());
        applicationInfoService.addApplicationInfo(applicationInfoDTO);
        messageLoggingManager.messageHandling(oneUser.getId(), MessageEnum.BIND_APPLICATION.getCode());
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean unbind(UnbindRelationDTO dto, UserDTO userDTO){
        Validator.notNull(dto,ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(dto.getRelationId(),ErrorCode.INPUT_PARAMETERS_NULL);
        SlaughterBuyerRelationDTO relationDTO = slaughterBuyerRelationService.queryById(dto.getRelationId());
        Validator.notNull(relationDTO,ErrorCode.RELATION_ISNULL);
        //删除绑定关系
        Boolean deleteBo = slaughterBuyerRelationService.deleteById(dto.getRelationId());
        Validator.isTrue(deleteBo,ErrorCode.RELATION_DELETE_FAIL);
        //保存解绑记录
        SlaughterBuyerRelationLogDTO logDTO = ModelConvertUtil.copyTo(relationDTO,SlaughterBuyerRelationLogDTO.class);
        logDTO.setType(RelationTypeEnum.UNBIND.getCode());
        logDTO.setReason(dto.getReason());
        logDTO.setInitiator(userDTO.getType());//设置解绑的发起方
        logDTO.setId(null);
        Long logId = slaughterBuyerRelationLogService.insert(logDTO);
        Validator.notNull(logId,ErrorCode.RELATION_LOG_INSERT_FAIL);
        //删除审核信息
        ApplicationQuery applicationQuery = new ApplicationQuery();
        applicationQuery.setLinkId(relationDTO.getSlaughterHouseId());
        applicationQuery.setType(ApplicationTypeEnum.SLAUGHTER_HOUSE.getCode());
        ApplicationInfoDTO applicationInfo = applicationInfoService.getApplicationInfoByQuery(applicationQuery);
        Validator.isTrue(applicationInfoService.realDeleteById(applicationInfo.getId()),ErrorCode.APPLY_DELETE_FAIL);
        messageLoggingManager.messageHandling(userDTO.getType().equals(UserTypeEnum.SLAUGHTER.getCode()) ? relationDTO.getSlaughterHouseId() : relationDTO.getBuyerUserId(),
                userDTO.getType().equals(UserTypeEnum.SLAUGHTER.getCode()) ? MessageEnum.SLAUGHTER_UNBOUND.getCode() : MessageEnum.SLAUGHTER_HOUSE_UNBOUND.getCode());
        return true;
    }

    public Boolean autoApply(SlaughterBuyerRelationDTO slaughterBuyerRelationDTO, UserDTO userDTO) {
        Validator.notNull(slaughterBuyerRelationDTO,ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(slaughterBuyerRelationDTO.getId(),ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(slaughterBuyerRelationDTO.getIfAutoApply(),ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.isTrue(userDTO.getType().equals(UserTypeEnum.SLAUGHTER.getCode()), ErrorCode.NO_POWER_GET);
        UserDTO serviceUserById = userService.getUserById(userDTO.getId());
        Validator.isTrue(serviceUserById.getState() == UserStateEnum.PASS.getCode(), ErrorCode.NO_POWER_GET);

        log.info(HEAD + "修改自动审批设置, 当前用户id:{}, 请求参数:{}", userDTO.getId(), JSON.toJSONString(slaughterBuyerRelationDTO));

        SlaughterBuyerRelationDTO relationDTO = slaughterBuyerRelationService.queryById(slaughterBuyerRelationDTO.getId());
        Validator.notNull(relationDTO,ErrorCode.RELATION_ISNULL);
        Validator.isTrue(relationDTO.getBuyerUserId().equals(userDTO.getId()), ErrorCode.NO_POWER_GET);
        Validator.isTrue(relationDTO.getState().equals(RelationStateEnum.BIND.getCode()), ErrorCode.RELATION_STATE_IS_ERROR);
        Validator.isTrue(!relationDTO.getIfAutoApply().equals(slaughterBuyerRelationDTO.getIfAutoApply()), ErrorCode.RELATION_UPDATE_FAIL);
        slaughterBuyerRelationService.update(slaughterBuyerRelationDTO);
        return true;
    }
}
