package com.hai.service.impl;

import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.utils.MD5Util;
import com.hai.dao.HighTyAgentMapper;
import com.hai.entity.HighTyAgent;
import com.hai.entity.HighTyAgentExample;
import com.hai.entity.SecUser;
import com.hai.enum_type.UserObjectTypeEnum;
import com.hai.service.HighTyAgentService;
import com.hai.service.SecUserService;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("highTyAgentService")
public class HighTyAgentServiceImpl implements HighTyAgentService {

    @Resource
    private HighTyAgentMapper tyAgentMapper;

    @Resource
    private SecUserService secUserService;

    @Override
    public void editTyAgent(HighTyAgent tyAgent) {
        if (tyAgent.getId() == null) {
            tyAgent.setStatus(1);
            tyAgent.setCreateTime(new Date());
            tyAgent.setUpdateTime(new Date());
            tyAgentMapper.insert(tyAgent);

            // 生成key
            Long key = 1000000 + tyAgent.getId();
            tyAgent.setAgentKey(key.toString());
            tyAgentMapper.updateByPrimaryKey(tyAgent);

        } else {
            tyAgent.setUpdateTime(new Date());
            tyAgentMapper.updateByPrimaryKey(tyAgent);
        }
    }

    @Override
    @Transactional(rollbackFor=Exception.class,propagation= Propagation.REQUIRES_NEW)
    public void addAgent(HighTyAgent tyAgent) throws Exception {
        if (secUserService.findByPhone(tyAgent.getAgentPhone()) != null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "手机号已存在，请更换");
        }

        editTyAgent(tyAgent);

        SecUser secUser = new SecUser();
        secUser.setUserName(tyAgent.getAgentName());
        secUser.setLoginName(tyAgent.getAgentPhone());
        secUser.setPassword(MD5Util.encode("123456".getBytes()));
        secUser.setAdminFlag(1);
        secUser.setStatus(1);
        secUser.setRoleId(7L);
        secUser.setObjectType(UserObjectTypeEnum.type6.getType());
        secUser.setObjectId(tyAgent.getId());
        secUser.setCreateTime(new Date());
        secUser.setUpdateTime(new Date());
        secUserService.addUser(secUser);
    }

    @Override
    public void updateAgent(HighTyAgent tyAgent) {
        // 查询账户
        SecUser account = secUserService.getMainAccount(UserObjectTypeEnum.type6.getType(), tyAgent.getId());
        if (account == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到账户信息");
        }

        if (!account.getLoginName().equals(tyAgent.getAgentPhone())) {
            if (secUserService.findByPhone(tyAgent.getAgentPhone()) != null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "手机号已存在，请更换");
            }
            account.setLoginName(tyAgent.getAgentPhone());
        }

        editTyAgent(tyAgent);

        account.setUserName(tyAgent.getAgentName());
        secUserService.updateUser(account);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void delAgent(String key) {
        HighTyAgent agent = getDetailByKey(key);
        if (agent == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到代理商");
        }
        agent.setStatus(0);
        editTyAgent(agent);

        // 查询代理商账户
        SecUser account = secUserService.getMainAccount(UserObjectTypeEnum.type6.getType(), agent.getId());
        if (account == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到代理商账户信息");
        }
        account.setStatus(0);
        secUserService.updateUser(account);
    }

    @Override
    public void agentPwdReset(String key) {
        try {
            // 查询代理商
            HighTyAgent tyAgent = getDetailByKey(key);
            if (tyAgent == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到代理商信息");
            }
            // 查询代理商账户
            SecUser account = secUserService.getMainAccount(UserObjectTypeEnum.type6.getType(), tyAgent.getId());
            if (account == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到代理商账户信息");
            }
            account.setPassword(MD5Util.encode("123456".getBytes()));
            account.setUpdateTime(new Date());
            secUserService.updateUser(account);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public HighTyAgent getDetailById(Long agentId) {
        return tyAgentMapper.selectByPrimaryKey(agentId);
    }

    @Override
    public HighTyAgent getDetailByKey(String key) {
        HighTyAgentExample example = new HighTyAgentExample();
        example.createCriteria().andAgentKeyEqualTo(key).andStatusNotEqualTo(0);
        List<HighTyAgent> list = tyAgentMapper.selectByExample(example);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<HighTyAgent> getAgentList(Map<String, Object> param) {
        HighTyAgentExample example = new HighTyAgentExample();
        HighTyAgentExample.Criteria criteria = example.createCriteria().andStatusNotEqualTo(0);

        if (MapUtils.getLong(param, "orgId") != null) {
            criteria.andOrgIdEqualTo(MapUtils.getLong(param, "orgId"));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "agentKey"))) {
            criteria.andAgentKeyLike("%" + MapUtils.getString(param, "agentKey") + "%");
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "agentName"))) {
            criteria.andAgentNameLike("%" + MapUtils.getString(param, "agentName") + "%");
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "agentUser"))) {
            criteria.andAgentUserEqualTo("%" + MapUtils.getString(param, "agentUser") + "%");
        }

        if (StringUtils.isNotBlank(MapUtils.getString(param, "agentPhone"))) {
            criteria.andAgentPhoneLike("%" + MapUtils.getString(param, "agentPhone") + "%");
        }

        example.setOrderByClause("create_time desc");
        return tyAgentMapper.selectByExample(example);
    }
}
