package com.yunzhupaas.base.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.ObjectUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.entity.ModuleEntity;
import com.yunzhupaas.base.entity.SystemEntity;
import com.yunzhupaas.base.model.base.SystemCrModel;
import com.yunzhupaas.base.model.base.SystemListVO;
import com.yunzhupaas.base.model.base.SystemPageVO;
import com.yunzhupaas.base.model.base.SystemUpModel;
import com.yunzhupaas.base.model.base.SystemVO;
import com.yunzhupaas.base.model.portalManage.PortalManagePage;
import com.yunzhupaas.base.model.portalManage.PortalManagePageDO;
import com.yunzhupaas.base.service.CommonWordsService;
import com.yunzhupaas.base.service.ModuleService;
import com.yunzhupaas.base.service.PortalManageService;
import com.yunzhupaas.base.service.SystemService;
import com.yunzhupaas.base.vo.ListVO;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.message.util.OnlineUserModel;
import com.yunzhupaas.message.util.OnlineUserProvider;
import com.yunzhupaas.permission.service.AuthorizeService;
import com.yunzhupaas.permission.service.OrganizeAdministratorService;
import com.yunzhupaas.permission.service.UserService;
import com.yunzhupaas.util.JsonUtil;
import com.yunzhupaas.util.StringUtil;
import com.yunzhupaas.util.UserProvider;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统控制器
 *
 * @author ：云筑产品开发平台组
 * @version: V3.1.0
 * @copyright 深圳市乐程软件有限公司
 * @date ：2022/6/21 15:33
 */
@Tag(name = "系统", description = "system")
@RestController
@RequestMapping("/api/system/System")
public class SystemController extends SuperController<SystemService, SystemEntity> {

    @Autowired
    private SystemService systemService;
    @Autowired
    private UserService userApi;
    
    @Autowired
    private CommonWordsService commonWordsService;
    @Autowired
    private OrganizeAdministratorService organizeAdminTratorApi;
    @Autowired
    private AuthorizeService authorizeApi;

    @Autowired
    PortalManageService portalManageService;
    @Autowired
    private ModuleService moduleService;

    /**
     * 获取系统列表
     *
     * @param page 关键字
     * @return ignore
     */
    @Operation(summary = "获取系统列表")
    @SaCheckPermission("system.menu")
    @GetMapping
    public ActionResult<ListVO<SystemListVO>> list(SystemPageVO page) {
        Boolean enabledMark = false;
        if (ObjectUtil.equal(page.getEnabledMark(), "0")) {
            enabledMark = null;
        }
        if (ObjectUtil.equal(page.getEnabledMark(), "1")) {
            enabledMark = true;
        }
        List<SystemEntity> list = systemService.getList(page.getKeyword(), enabledMark, true, page.getSelector(), true, new ArrayList<>());
        List<SystemListVO> jsonToList = JsonUtil.getJsonToList(list, SystemListVO.class);
        return ActionResult.success(new ListVO<>(jsonToList));
    }

    /**
     * 获取系统详情
     *
     * @param id 主键
     * @return ignore
     */
    @Operation(summary = "获取系统详情")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true)
    })
    @SaCheckPermission("system.menu")
    @GetMapping("/{id}")
    public ActionResult<SystemVO> info(@PathVariable("id") String id) {
        SystemEntity entity = systemService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail(MsgCode.FA001.get());
        }
        SystemVO jsonToBean = JsonUtil.getJsonToBean(entity, SystemVO.class);
        return ActionResult.success(jsonToBean);
    }

    /**
     * 新建系统
     *
     * @param systemCrModel 新建模型
     * @return ignore
     */
    @Operation(summary = "新建系统")
    @Parameters({
            @Parameter(name = "systemCrModel", description = "新建模型", required = true)
    })
    @SaCheckPermission("system.menu")
    @PostMapping
    public ActionResult create(@RequestBody SystemCrModel systemCrModel) {
        SystemEntity entity = JsonUtil.getJsonToBean(systemCrModel, SystemEntity.class);
        if (systemService.isExistFullName(entity.getId(), entity.getFullName())) {
            return ActionResult.fail(MsgCode.EXIST001.get());
        }
        if (systemService.isExistEnCode(entity.getId(), entity.getEnCode())) {
            return ActionResult.fail(MsgCode.EXIST002.get());
        }
        systemService.create(entity);
        return ActionResult.success(MsgCode.SU001.get());
    }

    /**
     * 修改系统
     *
     * @param id 主键
     * @param systemUpModel 修改模型
     * @return ignore
     */
    @Operation(summary = "修改系统")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
            @Parameter(name = "systemCrModel", description = "修改模型", required = true)
    })
    @SaCheckPermission("system.menu")
    @PutMapping("/{id}")
    public ActionResult update(@PathVariable("id") String id, @RequestBody SystemUpModel systemUpModel) {
        SystemEntity systemEntity = systemService.getInfo(id);
        if (systemEntity == null) {
            return ActionResult.fail(MsgCode.FA002.get());
        }
        // 主系统不允许禁用
        if (systemEntity.getIsMain() != null && systemEntity.getIsMain() == 1 && systemUpModel.getEnabledMark() == 0) {
            if (systemUpModel.getEnabledMark() == 0) {
                return ActionResult.fail(MsgCode.SYS101.get());
            }
            if (!systemEntity.getEnCode().equals(systemUpModel.getEnCode())) {
                return ActionResult.fail(MsgCode.SYS104.get());
            }
        }
        SystemEntity entity = JsonUtil.getJsonToBean(systemUpModel, SystemEntity.class);
        entity.setIsMain(systemEntity.getIsMain());
        if (systemService.isExistFullName(id, entity.getFullName())) {
            return ActionResult.fail(MsgCode.EXIST001.get());
        }
        if (systemService.isExistEnCode(id, entity.getEnCode())) {
            return ActionResult.fail(MsgCode.EXIST002.get());
        }
        systemService.update(id, entity);
        // 如果禁用了系统，则需要将系统
        if (systemEntity.getEnabledMark() == 1 && entity.getEnabledMark() == 0) {
            sentMessage("应用已被禁用，正为您切换应用", systemEntity);
        }
        return ActionResult.success(MsgCode.SU004.get());
    }

    /**
     * 删除系统
     *
     * @param id 主键
     * @return ignore
     */
    @Operation(summary = "删除系统")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true)
    })
    @SaCheckPermission("system.menu")
    @DeleteMapping("/{id}")
    public ActionResult<String> delete(@PathVariable("id") String id) {
        SystemEntity entity = systemService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail(MsgCode.FA003.get());
        }
        // 查询门户
        PortalManagePage portalManagePage = new PortalManagePage();
        portalManagePage.setSystemId(id);
        List<PortalManagePageDO> portalList = portalManageService.getSelectList(portalManagePage);
        // 查询平台下菜单
        List<ModuleEntity> webData = moduleService.getList(id, "web", null, null, null, null, false);
        List<ModuleEntity> appData = moduleService.getList(id, "app", null, null, null, null, false);
        if((CollectionUtils.isNotEmpty(webData) || CollectionUtils.isNotEmpty(appData) ) && CollectionUtils.isNotEmpty(portalList)){
            return ActionResult.fail(MsgCode.SYS039.get());
        }
        if(CollectionUtils.isNotEmpty(webData) || CollectionUtils.isNotEmpty(appData)){
            return ActionResult.fail(MsgCode.SYS040.get());
        }
        if(CollectionUtils.isNotEmpty(portalList)){
            return ActionResult.fail(MsgCode.SYS041.get());
        }

        if (entity.getIsMain() != null && entity.getIsMain() == 1) {
            return ActionResult.fail(MsgCode.SYS102.get());
        }
        // 系统绑定审批常用语时不允许被删除
        if(commonWordsService.existSystem(id)){
            return ActionResult.fail(MsgCode.SYS103.get());
        }else {
            systemService.delete(id);
            sentMessage("应用已被删除，正为您切换应用", entity);
        }
        return ActionResult.success(MsgCode.SU003.get());
    }

    private void sentMessage(String message, SystemEntity entity) {
        // 如果禁用了系统，则需要将系统
        List<OnlineUserModel> onlineUserList = OnlineUserProvider.getOnlineUserList();
        for (OnlineUserModel item : onlineUserList) {
            String systemId = item.getSystemId();
            if (entity.getId().equals(systemId)) {
                if (item.getWebSocket().isOpen()) {
                    Map<String, String> maps = new HashMap<>(1);
                    maps.put("method", "logout");
                    maps.put("msg", "应用已被禁用或删除");
                    if (StringUtil.isNotEmpty(UserProvider.getUser().getTenantId())) {
                        if (UserProvider.getUser().getTenantId().equals(item.getTenantId())) {
                            item.getWebSocket().getAsyncRemote().sendText(JsonUtil.getObjectToString(maps));
                        }
                    } else {
                        item.getWebSocket().getAsyncRemote().sendText(JsonUtil.getObjectToString(maps));
                    }
                }
            }
        }
    }

}

