package com.rongwei.safecommon.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.rongwei.commonservice.service.RedisService;
import com.rongwei.rwadmincommon.system.domain.SysOrganizationDo;
import com.rongwei.rwadmincommon.system.vo.SysOrganizationVo;
import com.rongwei.rwadmincommon.system.vo.SysUserVo;
import com.rongwei.rwcommon.utils.StringUtils;
import com.rongwei.safecommon.utils.SaveConstans;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
@Primary
public class BsMetaObjectHandler implements MetaObjectHandler {

    private static final Logger logger = LoggerFactory.getLogger(BsMetaObjectHandler.class);

    @Autowired
    private RedisService redisService;

    @Override
    public void insertFill(MetaObject metaObject) {
        try{
            System.out.println("insert 拦截...");
            SysUserVo sysUser = null;
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if(attributes == null){
                sysUser = new SysUserVo();
                sysUser.setId("0");
                sysUser.setName("系统操作");
            }else{
                HttpServletRequest request = attributes.getRequest();
                if(request == null){
                    sysUser = new SysUserVo();
                    sysUser.setId("0");
                    sysUser.setName("系统操作");
                }else{
                    String token = request.getHeader("token");
                    logger.info("token.... "+token);
                    if(token == null || "".equals(token)){
                        sysUser = new SysUserVo();
                        sysUser.setId("0");
                        sysUser.setName("系统操作");
                    }else{
                        sysUser = redisService.getLoginUser(token);
                        if(sysUser == null){
                            logger.info("当前token未查到对应的用户信息");
                            sysUser = new SysUserVo();
                        }
                    }
                }
            }

            logger.info("start insert fill ....");
            Object tenantid = this.getFieldValByName("tenantid", metaObject);
            if(null == tenantid && sysUser != null){
                // 所有组织机构
                List<SysOrganizationDo> orgdos = (List<SysOrganizationDo>)redisService.getRedisCatchObj("allOrgs");
                // 获取所属工厂
                List<SysOrganizationVo> organizationDoList = sysUser.getOrganizationDoList();
                if(organizationDoList != null && organizationDoList.size()>0){
                    Set<String> tids = new HashSet<>();
                    for (SysOrganizationVo org : organizationDoList) {
                        // 当前部门即工厂级部门
                        if(SaveConstans.ORGTYPE_FACTORY.equals(org.getOrgtype())){
                            tids.add(org.getId());
                        }
                        // 当前部门所有上级部门查找是否有工厂级部门
                        else{
                            String fullpid = org.getFullpid();
                            if(StringUtils.isNotBlank(fullpid)){
                                String[] fullpids = fullpid.split(",");
                                for (String pid : fullpids) {
                                    for (SysOrganizationDo orgdo : orgdos) {
                                        if(StringUtils.isNotBlank(pid) && pid.equals(orgdo.getId())){
                                            if(SaveConstans.ORGTYPE_FACTORY.equals(orgdo.getOrgtype())){
                                                tids.add(org.getId());
                                            }
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    this.setFieldValByName("tenantid", String.join(",", tids), metaObject);
                }
            }

            Date now = new Date();

            Object createDate = this.getFieldValByName("createdate", metaObject);
            if(null == createDate){
                /**
                 * 设置实体属性setter进去的值，优先级要高于自动填充的值。
                 * 如果实体没有设置该属性，就给默认值，防止entity的setter值被覆盖。
                 */
                this.setFieldValByName("createdate", now, metaObject);
            }
            Object modifyDate = this.getFieldValByName("modifydate", metaObject);
            if(null == modifyDate){
                this.setFieldValByName("modifydate", now, metaObject);
            }
            Object createuserid = this.getFieldValByName("createuserid", metaObject);
            if(null == createuserid && sysUser != null){
                this.setFieldValByName("createuserid", sysUser.getId(), metaObject);
            }
            Object createusername = this.getFieldValByName("createusername", metaObject);
            if(null == createusername && sysUser != null){
                this.setFieldValByName("createusername", sysUser.getName(), metaObject);
            }
            Object modifyuserid = this.getFieldValByName("modifyuserid", metaObject);
            if(null == modifyuserid && sysUser != null){
                this.setFieldValByName("modifyuserid", sysUser.getId(), metaObject);
            }
            Object modifyusername = this.getFieldValByName("modifyusername", metaObject);
            if(null == modifyusername && sysUser != null){
                this.setFieldValByName("modifyusername", sysUser.getName(), metaObject);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try{
            logger.info("start update fill ....");
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if(attributes == null){
                return;
            }
            HttpServletRequest request = attributes.getRequest();
            if(request == null){
                return;
            }
            String token = request.getHeader("token");
            if(token == null || "".equals(token)){
                return;
            }
            SysUserVo sysUser = redisService.getLoginUser(token);

            Date now = new Date();

            Object modifyDate = this.getFieldValByName("modifydate", metaObject);
            if(null == modifyDate){
                this.setUpdateFieldValByName("modifydate", now, metaObject);
            }
            Object modifyuserid = this.getFieldValByName("modifyuserid", metaObject);
            if(null == modifyuserid && sysUser != null){
                this.setUpdateFieldValByName("modifyuserid", sysUser.getId(), metaObject);
            }
            Object modifyusername = this.getFieldValByName("modifyusername", metaObject);
            if(null == modifyusername && sysUser != null){
                this.setUpdateFieldValByName("modifyusername", sysUser.getName(), metaObject);
            }
            //this.setFieldValByName("operator", "Tom", metaObject);
            //this.setUpdateFieldValByName("operator", "Tom", metaObject);//@since 快照：3.0.7.2-SNAPSHOT， @since 正式版暂未发布3.0.7
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
