package com.iamberry.wechat.service.sys;

import com.github.pagehelper.PageHelper;
import com.iamberry.sys.*;
import com.iamberry.wechat.core.entity.page.PageRequest;
import com.iamberry.wechat.core.entity.page.PagedResult;
import com.iamberry.wechat.face.sys.SysService;
import com.iamberry.wechat.service.PageUtil;
import com.iamberry.wechat.service.sys.mapper.SysMapper;
import com.iamberry.wechat.tools.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

/**
 * @author 献
 * @company 深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @tel 18271840547
 * @date 2017/5/12
 */
@Service
public class SysServiceImpl implements SysService {

    @Autowired
    private SysMapper sysMapper;

    @Override
    public String getSaltByLoginName(String loginName) {
        return sysMapper.getSaltByLoginName(loginName);
    }

    @Override
    public Admin get(Admin admin) {
        return sysMapper.get(admin);
    }

    @Override
    public Integer editAdmin(Admin admin) {
        // 不允许修改的内容:身份、使用状态、销售数量、登录账户
        admin.setAdminAccount(null);
        // 如果密码不为空，则表示需要修改密码
        createMD5(admin);
        // 更新
        return sysMapper.updateAdmin(admin);
    }

    @Override
    public PagedResult<Admin> listAdmin(PageRequest<Admin> pageRequest) {
        // 开始分页(页数, 每页数据大小，是否需要总页数，即执行(select count()))
        PageHelper.startPage(pageRequest.getPageNO(), pageRequest.getPageSize(), pageRequest.isPageTotal());
        List<Admin> list = sysMapper.listAdmin(pageRequest.getData());
        return PageUtil.getPage(list);
    }

    @Override
    public Integer saveAdmin(Admin admin) {
        // 如果密码不为空，则表示需要修改密码
        createMD5(admin);
        return sysMapper.addAdmin(admin);
    }

    /**
     * 为对象Admin生产MD5信息
     * @param admin
     */
    private void createMD5(Admin admin) {
        if (admin.getAdminPassword() != null) {
            String salt = UUID.randomUUID().toString().replaceAll("-", "");
            if (salt.length() > 32) {
                salt = salt.substring(0, 31);
            }
            admin.setAdminPassword(MD5Util.MD5Encode(admin.getAdminPassword() + salt, "UTF-8"));
            admin.setAdminSalt(salt);
        }
    }

    @Override
    public List<Menu> listMenuByRule(Integer ruleId) {
        return sysMapper.listMenuByRule(ruleId);
    }

    @Override
    public List<String> listSymbolByRule(Integer ruleId) {
        return sysMapper.listSymbolByRule(ruleId);
    }

    @Override
    public List<SysRule> listRule(Integer supplierId) {
        return sysMapper.listRule(supplierId);
    }

    @Override
    public SysRule getRule(Integer ruleId) {
        return sysMapper.getRule(ruleId);
    }

    @Override
    public List<Menu> listMenu() {
        return sysMapper.listMenu();
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, SQLException.class})
    public int addRule(Integer supplierId, String ruleName, Integer[] subMenuId) {
        if (subMenuId == null || subMenuId.length <= 0) {
            return 0;
        }
        // 添加角色
        SysRule sysRule = new SysRule();
        sysRule.setRuleName(ruleName);
        sysRule.setSupplierId(supplierId);
        sysRule.setRuleState(1);
        if (sysRule.getRuleOrderPermission() == null) {
            sysRule.setRuleOrderPermission(1);
        }
        int res = sysMapper.addRule(sysRule);
        if (res <= 0) {
            return 0;
        }
        // 添加权限
        for (Integer subId : subMenuId) {
            List<MenuPermisssion> subs = sysMapper.listPermisssionBySubId(subId);
            if (subs == null || subs.isEmpty()) {
                continue;
            }
            for (MenuPermisssion perm : subs) {
                AdminPocess pocess = new AdminPocess();
                pocess.setMenuId(perm.getPermMenuId());
                pocess.setPermId(perm.getPermId());
                pocess.setPocessSymbol(perm.getPermSymbol());
                pocess.setRuleId(sysRule.getRuleId());
                pocess.setSubId(subId);
                sysMapper.addPocess(pocess);
            }
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, SQLException.class})
    public int editRule(Integer ruleId, String ruleName, Integer[] subMenuId) {
        // 修改角色信息
        SysRule rule = new SysRule();
        rule.setRuleId(ruleId);
        rule.setRuleName(ruleName);
        sysMapper.editRule(rule);

        // 删除角色拥有的权限
        sysMapper.delPocess(ruleId);

        // 重新录入角色权限
        for (Integer subId : subMenuId) {
            List<MenuPermisssion> subs = sysMapper.listPermisssionBySubId(subId);
            if (subs == null || subs.isEmpty()) {
                continue;
            }
            for (MenuPermisssion perm : subs) {
                AdminPocess pocess = new AdminPocess();
                pocess.setMenuId(perm.getPermMenuId());
                pocess.setPermId(perm.getPermId());
                pocess.setPocessSymbol(perm.getPermSymbol());
                pocess.setRuleId(ruleId);
                pocess.setSubId(subId);
                sysMapper.addPocess(pocess);
            }
        }
        return 1;
    }
}
