package com.org.hktshop.service.Admin;

import com.org.hktshop.Interface.admin.IHktAdminResourceService;
import com.org.hktshop.Interface.admin.IHktAdminRoleService;
import com.org.hktshop.Interface.admin.IHktAdminService;
import com.org.hktshop.base.BaseResult;
import com.org.hktshop.base.BaseService;
import com.org.hktshop.base.MongoHelper;
import com.org.hktshop.entity.Page;
import com.org.hktshop.entity.admin.HktAdmin;
import com.org.hktshop.entity.admin.HktAdminResource;
import com.org.hktshop.entity.admin.HktAdminRole;
import com.org.hktshop.utils.DateUtil;
import com.org.hktshop.utils.ExecSqlLib;
import com.org.hktshop.utils.Ret;
import com.org.hktshop.utils.StringUtils;
import com.org.hktshop.utils.coder.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;

/****
 * 管理员处理
 * @author tw
 */
@Service
public class HktAdminServicelmpl extends BaseService<HktAdmin> implements IHktAdminService {

    @Autowired
    IHktAdminRoleService roleService;

    @Autowired
    IHktAdminResourceService resourceService;

    @Autowired
    private MongoHelper<HktAdmin> mongoHelper;

    @Override
    public List<HktAdmin> queryList(boolean isDelete) {
        List<HktAdmin> list = new ArrayList<>();
        if (isDelete) mongoHelper.delete(new Query(), HktAdmin.class);
        else list = mongoHelper.find(new HktAdmin(), HktAdmin.class);
        if (list.isEmpty()) {
            list = this.queryList(new HktAdmin());
            /*for (HktAdmin admin : list) {
                mongoHelper.save(admin);
            }*/
            mongoHelper.save(list);
        }
        return list;
    }

    @Override
    public HktAdmin queryAdmin(HktAdmin admin) {
        HktAdmin queyrAdmin = mongoHelper.findOne(admin, HktAdmin.class);
        return queyrAdmin;
    }

    //查询用户角色资源
    @Override
    public List<HktAdminResource> queryResource(HktAdmin admin) {
        HktAdminRole roleUser = new HktAdminRole();
        roleUser.setId(admin.getRoleId());
        List<HktAdminRole> hktAdminRoles = roleService.queryAdminRoles(roleUser);
        Set<String> set = new HashSet<>();
        for(HktAdminRole hr : hktAdminRoles){
            for(String str : hr.getResourceIds().split(",")){
                set.add(str);
            }
        }
        HktAdminRole role = hktAdminRoles.get(0);
        role.setResourceIds(set.toString().replace("[","").replace("]",""));
        return resourceService.queryRoleResource(role);
    }

    private Ret AccountCheck(HktAdmin admin, boolean isAdd) {
        //如何加密
        if (isAdd && StringUtils.isNull(admin.getPassword())) return Ret.create().setFail().set("msg", "输入用户密码不能为空");
        if (!StringUtils.isNull(admin.getPassword())) {
            if (admin.getPassword().length() < 8 || admin.getPassword().length() > 16) {
                return Ret.create().setFail().set("msg", "请输入8-16位密码");
            }
        }

        if (StringUtils.isNull(admin.getRoleId())) return Ret.create().setFail().set("msg", "请选择用户角色");
        if (StringUtils.isNull(admin.getAlias())) return Ret.create().setFail().set("msg", "用户备注不能为空");
        return Ret.create().setOk();
    }

    @Override
    public Ret updateAdmin(HktAdmin admin) {
        Ret ret = Ret.create();
        HktAdmin afind = new HktAdmin();
        afind.setAccount(admin.getAccount());
        HktAdmin oldAdmin = mongoHelper.findOne(afind, HktAdmin.class);
        MongoHelper<HktAdminRole> roleMongoHelper = new MongoHelper<HktAdminRole>();
        /*HktAdminRole role = new HktAdminRole();
        role.setId(admin.getRoleId());
        HktAdminRole rfind = roleMongoHelper.findOne(role, HktAdminRole.class);*/
        Criteria criteria = Criteria.where("_id").in(admin.getRoleId().split(","));
        List<HktAdminRole> hktAdminRoles = roleMongoHelper.find(new Query(criteria), HktAdminRole.class);
        if (hktAdminRoles == null || hktAdminRoles.size() == 0) return ret.setFail().set("msg", "请输入有效的用户角色类型");
        if (StringUtils.isNull(admin.getId())) {
            if (oldAdmin!= null) return ret.setFail().set("msg", "当前账户名存在，请选用其他名字");
            ret = AccountCheck(admin, true);
            if (ret.isFail()) return ret;
            //md5 加密
            admin.setPassword(SecurityUtil.encryptMd5(admin.getPassword()));
            admin.setCreateTime(DateUtil.getDateTime());
            if (this.updateJdbc(admin)) {
                ret.setOk().set("msg", "新增用户成功");
            } else {
                ret.setFail().set("msg", "新增用户失败");
            }
            String sql = ExecSqlLib.GetQuerySql(afind);
            HktAdmin find = this.baseJdbcDao.query(sql, admin);
            mongoHelper.save(find);
        } else {//更新用户信息
            afind = new HktAdmin();
            afind.setId(admin.getId());
            HktAdmin hktAdmin = mongoHelper.findOne(afind, HktAdmin.class);
            if (hktAdmin == null) return ret.setFail().set("msg", "输入异常");

            ret = AccountCheck(admin, false);
            if (ret.isFail()) return ret;

            if (!StringUtils.isNull(admin.getPassword()))   hktAdmin.setPassword(SecurityUtil.encryptMd5(admin.getPassword()));
            if (!StringUtils.isNull(admin.getRoleId()))  hktAdmin.setRoleId(admin.getRoleId());
            if (!StringUtils.isNull(admin.getAlias()))  hktAdmin.setAlias(admin.getAlias());
            if (!StringUtils.isNull(admin.getStatus()))  hktAdmin.setStatus(admin.getStatus());
            hktAdmin.setModifyTime(DateUtil.getDateTime());

            if (this.updateJdbc(hktAdmin)) {
                //缓存 更新怎么操作?
                mongoHelper.removeById(hktAdmin.getId(),HktAdmin.class);
                mongoHelper.save(hktAdmin);
                ret.setOk().set("msg", "修改用户成功");
            } else {
                ret.setFail().set("msg", "修改用户失败");
            }
        }
        return ret;
    }

    /***
     * 删除管理员
     * @param admin
     * @return
     */
    @Override
    public void deleteAdmin(HktAdmin opUser, HktAdmin admin) {

        HktAdmin hktAdmin = mongoHelper.findOne(admin, HktAdmin.class);
        if (hktAdmin == null)   throw new RuntimeException("当前用户不存在");
        if ("1".equals(hktAdmin.getRoleId()))   throw new RuntimeException("当前用户不允许删除");//系统管理员

        if (this.deleteById(hktAdmin.getId(), admin)) {
            mongoHelper.removeById(admin.getId(), HktAdmin.class);
        } else {
            throw new RuntimeException("删除失败");//系统管理员
        }
    }

    @Override
    public Page<HktAdmin> queryPage(HktAdmin admin) {

        Page<HktAdmin> page = mongoHelper.findPage(admin, HktAdmin.class);
        List<HktAdminRole> roleList = roleService.queryLists(false);

        for (HktAdmin admin1 : page.getRecords()) {
            String name = "";
            for (HktAdminRole role : roleList) {
                String[] split = admin1.getRoleId().split(",");
                if(Arrays.asList(split).contains(role.getId())){
                    if(StringUtils.isNull(name)){
                        name = role.getName()+",";
                    }else {
                        name += role.getName()+",";
                    }
                }
            }
            admin1.setRoleName(name.substring(0,name.lastIndexOf(",")));
        }
        return page;
    }
}
