package com.yihu.jw.base.service.doctor;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.base.dao.doctor.BaseDoctorRoleDictDao;
import com.yihu.jw.base.util.ConstantUtils;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.doctor.dao.BaseDoctorRoleDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorRoleDictDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorRoleInfoDO;
import com.yihu.jw.entity.base.doctor.BaseModuleRoleDO;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class BaseDoctorRoleDictService extends BaseJpaService<BaseDoctorRoleDictDO, BaseDoctorRoleDao> {
    @Autowired
    private BaseDoctorRoleDictDao baseDoctorRoleDictDao;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private BaseModuleRoleService baseModuleRoleService;
    /**
     * 创建角色信息
     *
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject createRoleInfo(String jsonData, JSONObject userAgent) {
        JSONObject result = new JSONObject();
        if (StringUtils.isEmpty(jsonData)) {
            result.put("msg", "parameter jsonData is null");
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        JSONObject role = jsonObject.getJSONObject("role");
        JSONArray module = jsonObject.getJSONArray("module");
        if (null == role || CollectionUtils.isEmpty(module) ) {
            result.put("msg", "parameter role or module of jsonData is null");
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        if(StringUtils.isEmpty(role.getString("name")) || role.getString("name").length() > 50){
            result.put("msg", "角色名称必填，但是请不要超过50个字符！");
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        //组装角色信息
        BaseDoctorRoleDictDO roleInfoDO = null;
        try {
            roleInfoDO = objectMapper.readValue(role.toJSONString(), BaseDoctorRoleDictDO.class);
        } catch (IOException e) {
            result.put("msg", "convert role jsonObject to BaseDoctorRoleInfoDO failed," + e.getCause());
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        roleInfoDO.setCode(randomString(30));
        this.save(roleInfoDO);

        //组装角色与模块的关联关系
        List<BaseModuleRoleDO> moduleRoleDOList = new ArrayList<>();
        BaseModuleRoleDO moduleRoleDO = null;
        for (Object obj : module) {
            try {
                moduleRoleDO = objectMapper.readValue(obj.toString(), BaseModuleRoleDO.class);
                moduleRoleDO.setRoleCode(roleInfoDO.getCode());
                moduleRoleDOList.add(moduleRoleDO);
            } catch (IOException e) {
                result.put("msg", "convert org jsonObject to BaseOrgUserDO failed," + e.getCause());
                result.put("response", ConstantUtils.FAIL);
                return result;
            }
        }
        baseModuleRoleService.batchInsert(moduleRoleDOList);

        result.put("response", ConstantUtils.SUCCESS);
        result.put("msg", moduleRoleDO);
        return result;
    }



    /**
     * 修改角色
     *
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject updateRoleInfo(String jsonData) {
        JSONObject result = new JSONObject();
        if (StringUtils.isEmpty(jsonData)) {
            result.put("msg", "parameter jsonData is null");
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        JSONObject role = jsonObject.getJSONObject("role");
        JSONArray module = jsonObject.getJSONArray("module");
        if (null == role || CollectionUtils.isEmpty(module) ) {
            result.put("msg", "parameter role or module of jsonData is null");
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        //修改角色信息
        BaseDoctorRoleDictDO roleInfoDO = null;
        BaseDoctorRoleDictDO oldRoleInfo = null;
        try {
            roleInfoDO = objectMapper.readValue(role.toJSONString(), BaseDoctorRoleDictDO.class);

        } catch (IOException e) {
            result.put("msg", "convert user jsonObject to UserDO failed," + e.getCause());
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        try {
            oldRoleInfo = baseDoctorRoleDictDao.findOne(roleInfoDO.getId());

        } catch (Exception e) {
            result.put("msg", "not role exist for id:" + roleInfoDO.getId());
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        oldRoleInfo.setCode(roleInfoDO.getCode());
        oldRoleInfo.setName(roleInfoDO.getName());
        this.save(oldRoleInfo);

        //修改角色与模块关联关系
        Set<Object> roleIdList = baseModuleRoleService.findModuleIdList(roleInfoDO.getCode());
        BaseModuleRoleDO moduleRoleDO = null;
        try {
            for (Object obj : module) {
                moduleRoleDO = objectMapper.readValue(obj.toString(), BaseModuleRoleDO.class);
                moduleRoleDO.setRoleCode(roleInfoDO.getCode());
                if (roleIdList.contains(moduleRoleDO.getId())) {
                    roleIdList.remove(moduleRoleDO.getId());
                }
                baseModuleRoleService.save(moduleRoleDO);
            }
        } catch (IOException e) {
            result.put("msg", "convert module jsonObject to BaseModuleRoleDO failed," + e.getCause());
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        // 表示没有删除，只有修改
        if (roleIdList.size() > 0) {
            baseModuleRoleService.delete(roleIdList.toArray());
        }

        result.put("response", ConstantUtils.SUCCESS);
        result.put("msg", roleInfoDO);
        return result;
    }



    /**
     * 获取单个角色信息
     * @param roleId 角色id
     * @return
     */
    public JSONObject getOneRoleInfo(Integer roleId) throws Exception{
        JSONObject result = new JSONObject();
        if(StringUtils.isEmpty(roleId)){
            result.put("msg","parameter roleId is null ");
            result.put("response",ConstantUtils.FAIL);
            return result;
        }

        //角色基本信息
        BaseDoctorRoleDictDO roleInfoDO = baseDoctorRoleDictDao.findOne(roleId.toString());
        if(null == roleInfoDO){
            result.put("msg","Role not exist for id:" + roleId);
            result.put("response",ConstantUtils.FAIL);
            return result;
        }
        List<BaseModuleRoleDO> moduleRoleDOList =  baseModuleRoleService.findModuleListByRoleCode(roleInfoDO.getCode());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("role",roleInfoDO);
        jsonObject.put("module",moduleRoleDOList);
        result.put("response",ConstantUtils.SUCCESS);
        result.put("msg",jsonObject);
        return result;
    }



    /**
     * 生效或失效单个角色
     * @param roleId
     * @param del
     * @return
     */
    public JSONObject enableOrDisable(Integer roleId,String del){
        JSONObject result = new JSONObject();
        if(StringUtils.isEmpty(roleId) || StringUtils.isEmpty(del)){
            result.put("msg","parameter id or del is null");
            result.put("response",ConstantUtils.FAIL);
            return result;
        }
        BaseDoctorRoleDictDO roleInfoDO = baseDoctorRoleDictDao.findOne(roleId.toString());
        if( null == roleInfoDO ){
            result.put("msg","role not exist for id:" + roleId);
            result.put("response",ConstantUtils.FAIL);
            return result;
        }
        roleInfoDO.setDel(del);
        this.save(roleInfoDO);
        result.put("response",ConstantUtils.SUCCESS);
        return result;
    }

    /**
     * 判断某一租户下角色名称是否存在
     * @param saasId
     * @param name
     * @return
     */
    public JSONObject existNameOfSaas(String saasId,String name){
        JSONObject result = new JSONObject();
        if(StringUtils.isEmpty(saasId) || StringUtils.isEmpty(name)){
            result.put("msg","parameter saasId or name is null");
            result.put("response",ConstantUtils.FAIL);
            return result;
        }
        List<BaseDoctorRoleDictDO> roleInfoDO = baseDoctorRoleDictDao.getByname(name);
        result.put("response",ConstantUtils.SUCCESS);
        result.put("msg",null == roleInfoDO);
        return result;
    }

}
