package cn.pluss.platform.service.agent.impl;

import cn.pluss.platform.dto.UserInfoDTO;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.entity.UserInfo;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.service.agent.AgentStaffService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.util.MD5Util;
import cn.pluss.platform.util.StringUtil;
import cn.pluss.platform.vo.AgentStaffVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

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

/**
 * @author DJH
 */
@Service
public class AgentStaffServiceImpl implements AgentStaffService {

    @Setter(onMethod_ = {@Autowired})
    private UserAppService userAppService;
    @Setter(onMethod_ = {@Autowired})
    private UserInfoService userInfoService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdateStaff(UserInfoDTO dto) {
        appStaffPermitCheck(dto.getUserId());
        if (StringUtils.isEmpty(dto.getUserId())) {
            saveStaff(dto);
        } else {
            updateStaff(dto);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveStaff(@Validated(UserInfoDTO.AgentStaffInsert.class) UserInfoDTO dto) {
        UserApp pUserApp = new UserApp().setUserId(Long.parseLong(dto.getPId()));
        pUserApp = userAppService.queryUserApp(pUserApp);
        if (pUserApp == null) {
            throw new MsgException("未找到父id数据");
        }

        if (!"agent".equals(pUserApp.getUserType())) {
            throw new MsgException("拒绝访问");
        }

        UserInfo userInfo = UserInfo.newInstance();
        userInfo.setLoginName(dto.getLoginName());
        UserInfo exist = userInfoService.queryUserInfo(new UserInfo().setLoginName(dto.getLoginName()));
        if (exist != null) {
            throw new MsgException("账号已存在");
        }
        userInfo.setPhone(dto.getPhone());


        userInfo.setTrueName(dto.getUserName());
        userInfo.setPassword(MD5Util.MD5Encode(dto.getPassword(), "utf-8"));
        userInfoService.save(userInfo);

        UserApp userApp = UserApp.newInstance();
        userApp.setLoginName(dto.getLoginName());
        userApp.setUserName(dto.getUserName());
        userApp.setUserType("agent_staff");
        userApp.setLevel(1).setInviteNum(getRandomNum());
        userApp.setUserId(userInfo.getId());
        userApp.setPhone(dto.getPhone());
        userApp.setParentId(Long.parseLong(dto.getPId()));
        userAppService.save(userApp);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateStaff(@Validated(UserInfoDTO.AgentStaffUpdate.class) UserInfoDTO dto) {
        appStaffPermitCheck(dto.getUserId());

        UserInfo userInfo = new UserInfo().setId(Long.parseLong(dto.getUserId()));
        userInfo = userInfoService.queryUserInfo(userInfo);
        if (userInfo == null) {
            throw new MsgException("员工不存在");
        }

        userInfo.setPhone(dto.getPhone());
        userInfo.setLoginName(dto.getLoginName());
        userInfo.setTrueName(dto.getUserName());
        userInfo.setPassword(MD5Util.MD5Encode(dto.getPassword(), "utf-8"));
        userInfoService.updateById(userInfo);

        UserApp userApp = new UserApp().setUserId(Long.parseLong(dto.getUserId()));
        userApp = userAppService.queryUserApp(userApp);
        userApp.setLoginName(dto.getLoginName());
        userApp.setUserType("agent_staff");
        userApp.setUserName(dto.getUserName());
        userApp.setLevel(0);
        userApp.setUserId(userInfo.getId());
        userApp.setPhone(dto.getPhone());
        userApp.setParentId(Long.parseLong(dto.getPId()));
        userAppService.updateById(userApp);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Page<AgentStaffVO> staffPage(Page<AgentStaffVO> page, UserInfoDTO dto) {
        Page<UserApp> page1 = new Page<>();
        page1.setCurrent(page.getCurrent());
        page1.setSize(page.getSize());

        QueryWrapper<UserApp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userType", "agent_staff");
        queryWrapper.eq(dto.getUserId() != null, "userId", dto.getUserId());
        queryWrapper.like(dto.getLoginName() != null, "loginName", dto.getLoginName());
        queryWrapper.like(dto.getPhone() != null, "phone", dto.getPhone());
        queryWrapper.eq(dto.getPId() != null, "parentId", dto.getPId());
        queryWrapper.gt(dto.getStartTime() != null, "createDt", dto.getStartTime());
        queryWrapper.lt(dto.getEndTime() != null, "createDt", dto.getEndTime());
        queryWrapper.orderByDesc("createDt");
        page1 = userAppService.page(page1, queryWrapper);

        List<AgentStaffVO> result = new ArrayList<>();
        for (UserApp userApp : page1.getRecords()) {
            AgentStaffVO agentStaffVO = new AgentStaffVO();
            agentStaffVO.setUserId(userApp.getUserId() + "");
            agentStaffVO.setCreateTime(userApp.getCreateDt());
            agentStaffVO.setLogo(userApp.getLogo());
            agentStaffVO.setPhone(userApp.getPhone());
            agentStaffVO.setUserName(userApp.getUserName());
            agentStaffVO.setLoginName(userApp.getLoginName());

            result.add(agentStaffVO);
        }

        page.setRecords(result);
        page.setTotal(page1.getTotal());

        return page;
    }

    @Override
    public void delStaff(String userId) {
        appStaffPermitCheck(userId);

        UserApp userApp = new UserApp().setUserId(Long.parseLong(userId));
        userApp = userAppService.queryUserApp(userApp);

        userInfoService.removeById(userId);
        userAppService.removeById(userApp.getId());
    }

    @Override
    public AgentStaffVO getStaff(String userId) {
        appStaffPermitCheck(userId);

        UserApp userApp = new UserApp().setUserId(Long.parseLong(userId));
        userApp = userAppService.queryUserApp(userApp);

        AgentStaffVO agentStaffVO = new AgentStaffVO();
        agentStaffVO.setUserId(userId);
        agentStaffVO.setCreateTime(userApp.getCreateDt());
        agentStaffVO.setLogo(userApp.getLogo());
        agentStaffVO.setPhone(userApp.getPhone());
        agentStaffVO.setUserName(userApp.getUserName());
        return agentStaffVO;
    }

    public void appStaffPermitCheck(String userId) {
        UserApp tokenUserApp = userAppService.queryUserAppByToken();
        if (tokenUserApp == null || !"agent".equals(tokenUserApp.getUserType())) {
            throw new MsgException("拒绝访问");
        }

        if (StringUtils.isEmpty(userId)) {
            return;
        }

        UserApp userApp = new UserApp().setUserId(Long.parseLong(userId));
        userApp = userAppService.queryUserApp(userApp);

        if (userApp == null) {
            return;
        }

        if (!tokenUserApp.getUserId().equals(userApp.getParentId())) {
            throw new MsgException("拒绝访问");
        }
    }

    private String getRandomNum() {
        String inviteNum;
        UserApp condition = new UserApp();

        do {
            inviteNum = StringUtil.genRandomNum(5);
            condition.setInviteNum(inviteNum);
            UserApp userApp = userAppService.queryUserApp(condition);
            if (userApp == null) {
                return inviteNum;
            }
        } while (true);
    }
}
