package com.blueland.sys.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blueland.annotation.ApiVersion;
import com.blueland.bo.*;
import com.blueland.constant.Constant;
import com.blueland.core.util.UserUtils;
import com.blueland.enums.Version;
import com.blueland.model.*;
import com.blueland.result.R;
import com.blueland.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @auther xcy
 * @create 2022-06-16 14:26
 */
@RestController
@RequestMapping("/dataOps")
@Api(value = "数据维护控制器", tags = "数据维护控制器")
public class DataOpsController {

    @Autowired
    private ITucOrgService tucOrgService;

    @Autowired
    private ITucStaffService tucStaffService;

    @Autowired
    private IParameterService iParameterService;

    @Autowired
    private SysRedisService sysRedisService;

    @Autowired
    private IRole2userService iRole2userService;

    @Autowired
    private IRoleService iRoleService;

    @Autowired
    private IMenuService iMenuService;

    @Autowired
    private IAuthService authService;

    @Autowired
    private IDictService dictService;

    @ApiVersion(groups = Version.SIX)
    @ApiOperation("初始化部门数据 inAppId:数据来源租户")
    @GetMapping("/initOrg/{toAppId}")
    public R initOrg(@RequestParam("inAppId") String inAppId, @PathVariable("toAppId") String toAppId) {
        // 查询当前租户是否配置了部门对应关系
        String value = iParameterService.getValueByKey(Constant.ORG_APP);
        if (ObjectUtil.isEmpty(value)) {
            throw new RuntimeException("租户：" + toAppId + "，没有配置对应的租户");
        }
        handleOrg(value, inAppId, toAppId);
        return R.ok();
    }

    /**
     * 处理部门数据
     *
     * @param value
     * @param inAppId
     * @param toAppId
     */
    private void handleOrg(String value, String inAppId, String toAppId) {
        // 删除指定租户的数据
        tucOrgService.deleteOrgByAppId(toAppId);
        // 查询指定租户数据
        Org bo = new Org();
        bo.setAppId(ObjectUtil.isNotEmpty(inAppId) ? inAppId : "BIO");
        bo.setOrgStatus("QY");
        bo.setLikeDeptId(value);
        List<Org> list = tucOrgService.findList(bo);
        if (ObjectUtil.isNotEmpty(list)) {
            List<TUcOrg> addList = new ArrayList<>();
            for (Org org : list) {
                TUcOrg o = new TUcOrg();
                BeanUtil.copyProperties(org, o);
//                o.setOrgId(org.getOrgId() + toAppId);
//                if (!Objects.equals(o.getOrgParentId(), "0")) {
//                    o.setOrgParentId(org.getOrgParentId() + toAppId);
//                }
                o.setOrgCreateTime(new Date());
                o.setOrgUpdateTime(new Date());
                o.setAppId(toAppId);
                o.setId(null);
                addList.add(o);
            }
            // 保存
            tucOrgService.saveBatch(addList);
            // 刷新redis
            sysRedisService.initDept();
        }
    }


    @ApiVersion(groups = Version.SIX)
    @ApiOperation("初始化员工数据 inAppId:数据来源租户")
    @GetMapping("/initStaff/{toAppId}")
    public R initStaff(@RequestParam("inAppId") String inAppId, @PathVariable("toAppId") String toAppId) {
        // 查询当前租户是否配置了部门对应关系
        String value = iParameterService.getValueByKey(Constant.ORG_APP);
        if (ObjectUtil.isEmpty(value)) {
            throw new RuntimeException("租户：" + toAppId + "，没有配置对应的租户");
        }
        handleStaff(value, inAppId, toAppId);
        return R.ok();
    }

    /**
     * 处理员工数据
     *
     * @param value
     * @param inAppId
     * @param toAppId
     */
    private void handleStaff(String value, String inAppId, String toAppId) {
        // 删除数据
        tucStaffService.deleteStaffByAppId(toAppId);
        // 查询指定范围数据
        TucStaffEntity bo = new TucStaffEntity();
        bo.setAppId(ObjectUtil.isNotEmpty(inAppId) ? inAppId : "BIO");
        bo.setStaffStatus("QY");
        bo.setLikeDeptId(value);
        List<TucStaffEntity> list = tucStaffService.findList(bo);
        if (ObjectUtil.isNotEmpty(list)) {
            List<TUcStaff> addList = new ArrayList<>();
            for (TucStaffEntity staff : list) {
                TUcStaff p = new TUcStaff();
                BeanUtil.copyProperties(staff, p);
                p.setStaffCreateTime(new Date());
                p.setStaffLastupdateTime(new Date());
                p.setStaffId(staff.getStaffId() + toAppId);
                p.setAppId(toAppId);
                p.setStaffCreator("admin");
//                if (!Objects.equals(staff.getOrgId(), "0")) {
//                    p.setOrgId(staff.getOrgId() + toAppId);
//                }
                addList.add(p);
            }
            Boolean result = tucStaffService.saveBatch(addList);
        }
    }

    @ApiVersion(groups = Version.SIX)
    @ApiOperation("初始化数据 inAppId:数据来源租户")
    @GetMapping("/initData/{toAppId}")
    public R initData(@RequestParam("inAppId") String inAppId, @PathVariable("toAppId") String toAppId) {
        // 查询当前租户是否配置了部门对应关系
        String value = iParameterService.getValueByKey(Constant.ORG_APP);
        if (ObjectUtil.isEmpty(value)) {
            throw new RuntimeException("租户：" + toAppId + "，没有配置对应的租户");
        }
        // 初始化部门数据
        handleOrg(value, inAppId, toAppId);
        // 初始化员工数据
        handleStaff(value, inAppId, toAppId);
        // 初始化菜单数据
        handleMenu(value, inAppId, toAppId);
        // 初始化角色数据
        handleRole(inAppId, toAppId);
        // 初始化角色用户数据
        handleRoleUser(inAppId, toAppId);
        // 初始化字典数据
        handleDict(inAppId, toAppId);
        // 初始化权限数据
        handleAuth(inAppId, toAppId);
        return R.ok();
    }

    @ApiVersion(groups = Version.SIX)
    @ApiOperation("初始化菜单数据 inAppId:数据来源租户")
    @GetMapping("/initMenu/{toAppId}")
    public R initMenu(@RequestParam("inAppId") String inAppId, @PathVariable("toAppId") String toAppId) {
        // 查询当前租户是否配置了部门对应关系
        String value = iParameterService.getValueByKey(Constant.ORG_APP);
        if (ObjectUtil.isEmpty(value)) {
            throw new RuntimeException("租户：" + toAppId + "，没有配置对应的租户");
        }
        handleMenu(value, inAppId, toAppId);
        return R.ok();
    }
    /**
     * 处理部门数据
     *
     * @param value
     * @param inAppId
     * @param toAppId
     */
    private void handleMenu(String value, String inAppId, String toAppId) {
        // 删除数据
        iMenuService.deleteMenuByAppId(toAppId);
        // 查询数据
        List<MenuEntity> list = iMenuService.getMenListByAppId(ObjectUtil.isNotEmpty(inAppId) ? inAppId : "BIO");
        if (ObjectUtil.isNotEmpty(list)) {
            List<TPfMenu> addList = new ArrayList<>();
            for (MenuEntity menu : list) {
                TPfMenu m = new TPfMenu();
                BeanUtil.copyProperties(menu, m);
                m.setMenuId(menu.getMenuId() + toAppId);
                m.setAppId(toAppId);
                if (ObjectUtil.isNotEmpty(menu.getMenuParentId())) {
                    m.setMenuParentId(menu.getMenuParentId() + toAppId);
                }
                m.setCreateDate(new Date());
                m.setUpdateDate(new Date());
                addList.add(m);
            }
            iMenuService.saveBatch(addList);
            // 刷新redis
            sysRedisService.initMenu();
        }
    }

    @ApiVersion(groups = Version.SIX)
    @ApiOperation("初始化角色数据 inAppId:数据来源租户")
    @GetMapping("/initRole/{toAppId}")
    public R initRole(@RequestParam("inAppId") String inAppId, @PathVariable("toAppId") String toAppId) {
        // 查询当前租户是否配置了部门对应关系
        String value = iParameterService.getValueByKey(Constant.ORG_APP);
        if (ObjectUtil.isEmpty(value)) {
            throw new RuntimeException("租户：" + toAppId + "，没有配置对应的租户");
        }
        handleRole(inAppId, toAppId);
        return R.ok();
    }

    /**
     * 处理角色数据
     * @param inAppId
     * @param toAppId
     */
    private void handleRole(String inAppId, String toAppId) {
        // 删除角色
        iRoleService.deleteByAppId(toAppId);
        // 查询数据
        List<RoleEntity> list = iRoleService.findListByAppId(ObjectUtil.isNotEmpty(inAppId) ? inAppId : "BIO");
        if (ObjectUtil.isNotEmpty(list)) {
            List<TPfRole> addList = new ArrayList<>();
            for (RoleEntity entity : list) {
                // 新增管理员角色
                TPfRole role = new TPfRole();
                BeanUtil.copyProperties(entity, role);
//                if (ObjectUtil.isNotEmpty(role.getOrgId()) && !Objects.equals(role.getOrgId(), "0")) {
//                    role.setOrgId(role.getOrgId() + toAppId);
//                }
                role.setCreateDate(new Date());
                role.setUpdateDate(new Date());
                role.setCreatorId("admin");
                role.setAppId(toAppId);
                addList.add(role);
            }
            // 保存数据
            iRoleService.saveBatch(addList);
            // 刷新缓存
            sysRedisService.initRole();
        }
    }

    @ApiVersion(groups = Version.SIX)
    @ApiOperation("初始化角色用户数据 inAppId:数据来源租户")
    @GetMapping("/initRoleUser/{toAppId}")
    public R initRoleUser(@RequestParam("inAppId") String inAppId, @PathVariable("toAppId") String toAppId) {
        // 查询当前租户是否配置了部门对应关系
        String value = iParameterService.getValueByKey(Constant.ORG_APP);
        if (ObjectUtil.isEmpty(value)) {
            throw new RuntimeException("租户：" + toAppId + "，没有配置对应的租户");
        }
        handleRoleUser(inAppId, toAppId);
        return R.ok();
    }

    /**
     * 处理角色用户数据
     * @param inAppId
     * @param toAppId
     */
    private void handleRoleUser(String inAppId, String toAppId) {
        // 新增管理员
        iRole2userService.deleteByAppId(toAppId);
        // 查询数据
        List<TPfRole2user> list = iRole2userService.selectListByAppId(ObjectUtil.isNotEmpty(inAppId) ? inAppId : "BIO");
        if (ObjectUtil.isNotEmpty(list)) {
            for (TPfRole2user role2user : list) {
//                if (ObjectUtil.isNotEmpty(role2user.getOrgId()) && !Objects.equals(role2user.getOrgId(), "0")) {
//                    role2user.setOrgId(role2user.getOrgId() + toAppId);
//                }
                if (ObjectUtil.isEmpty(role2user.getStaffPostCode())) {
                    role2user.setStaffPostCode(role2user.getUserId());
                }
                role2user.setCreateDate(new Date());
                role2user.setCreatorId("admin");
                role2user.setAppId(toAppId);
                role2user.setUpdateDate(new Date());
            }
        }
        // 新增数据
        iRole2userService.saveBatch(list);
        // 刷新缓存
        sysRedisService.initRole();
    }

    @ApiVersion(groups = Version.SIX)
    @ApiOperation("初始化字典数据 inAppId:数据来源租户")
    @GetMapping("/initDict/{toAppId}")
    public R initDict(@RequestParam("inAppId") String inAppId, @PathVariable("toAppId") String toAppId) {
        // 查询当前租户是否配置了部门对应关系
        String value = iParameterService.getValueByKey(Constant.ORG_APP);
        if (ObjectUtil.isEmpty(value)) {
            throw new RuntimeException("租户：" + toAppId + "，没有配置对应的租户");
        }
        handleDict(inAppId, toAppId);
        return R.ok();
    }

    /**
     * 处理字典数据
     * @param inAppId
     * @param toAppId
     */
    private void handleDict(String inAppId, String toAppId) {
        //删除数据
        dictService.deleteDictByAppId(toAppId);
        List<DictEntity> list = dictService.getListByAppId(ObjectUtil.isNotEmpty(inAppId) ? inAppId : "BIO");
        if (ObjectUtil.isNotEmpty(list)) {
            List<TPfDict> dictList = new ArrayList<>();
            for (DictEntity entity : list) {
                TPfDict d = new TPfDict();
                BeanUtil.copyProperties(entity, d);
                d.setId(null);
                d.setCreateDate(new Date());
                d.setUpdateDate(new Date());
                d.setAppId(toAppId);
                dictList.add(d);
            }
            // 保存数据
            dictService.saveBatch(dictList);
            // 刷新缓存
            sysRedisService.initDict();
        }
    }

    @ApiVersion(groups = Version.SIX)
    @ApiOperation("初始化权限数据 inAppId:数据来源租户")
    @GetMapping("/initAuth/{toAppId}")
    public R initAuth(@RequestParam("inAppId") String inAppId, @PathVariable("toAppId") String toAppId) {
        // 查询当前租户是否配置了部门对应关系
        String value = iParameterService.getValueByKey(Constant.ORG_APP);
        if (ObjectUtil.isEmpty(value)) {
            throw new RuntimeException("租户：" + toAppId + "，没有配置对应的租户");
        }
        handleAuth(inAppId, toAppId);
        return R.ok();
    }

    /**
     * 处理权限数据
     * @param inAppId
     * @param toAppId
     */
    private void handleAuth(String inAppId, String toAppId) {
        // 删除数据
        authService.deleteAuthByAppId(toAppId);
        // 查询数据
        List<AuthEntity> list = authService.findListByAppId(ObjectUtil.isNotEmpty(inAppId) ? inAppId : "BIO");
        if (ObjectUtil.isNotEmpty(list)) {
            List<TPfAuth> addList = new ArrayList<>();
            for (AuthEntity auth : list) {
                TPfAuth a = new TPfAuth();
                BeanUtil.copyProperties(auth, a);
                a.setAppId(toAppId);
                a.setCreateDate(new Date());
                a.setUpdateDate(new Date());
                a.setAuthId(a.getAuthId() + toAppId);
                if (ObjectUtil.isNotEmpty(a.getMenuId())) {
                    a.setMenuId(a.getMenuId() + toAppId);
                }
                addList.add(a);
            }
            // 保存数据
            authService.saveBatch(addList);
        }
    }
}
