package com.artfess.portal.controller;

import com.artfess.base.controller.BaseController;
import com.artfess.base.model.CommonResult;
import com.artfess.base.query.Direction;
import com.artfess.base.query.FieldSort;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.HttpUtil;
import com.artfess.base.util.StringUtil;
import com.artfess.base.util.ThreadMsgUtil;
import com.artfess.base.util.time.DateFormatUtil;
import com.artfess.sysConfig.persistence.manager.AppTagsRelationManager;
import com.artfess.sysConfig.persistence.manager.SysAppManager;
import com.artfess.sysConfig.persistence.model.AppTagsRelation;
import com.artfess.sysConfig.persistence.model.SysApp;
import com.artfess.uc.api.impl.util.ContextUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * 描述：应用信息 控制器类
 * 构建组：x7
 * 作者:qiuxd
 * 邮箱:qiuxd@jee-soft.cn
 * 日期:2020-08-20 15:23:19
 * 版权：广州宏天软件股份有限公司
 * </pre>
 */
@RestController
@RequestMapping(value = "/portal/sysApp/v1")
@Api(tags = "sysAppController")
public class SysAppController extends BaseController<SysAppManager, SysApp> {
    @Resource
    SysAppManager sysAppManager;
    @Resource
    AppTagsRelationManager appTagsRelationManager;

    @Override
    @PostMapping(value = "/query", produces = {"application/json; charset=utf-8"})
    @ApiOperation("分页查询结果")
    public PageList<SysApp> query(@ApiParam(name = "queryFilter", value = "分页查询信息") @RequestBody QueryFilter<SysApp> queryFilter) {
        List<FieldSort> sorter = queryFilter.getSorter();
        sorter.add(new FieldSort("ID_", Direction.DESC));
        queryFilter.setSorter(sorter);
        return baseService.query(queryFilter);
    }

    @PostMapping("/authList")
    @ApiOperation(value = "获取已授权的应用", httpMethod = "POST", notes = "获取已授权的应用")
    public List<SysApp> authList(@ApiParam(name = "queryFilter", value = "查询对象") @RequestBody SysApp sysApp) throws Exception {
        return sysAppManager.queryByAuth(sysApp);
    }

    @PostMapping("/queryByFilter")
    @ApiOperation(value = "查询已授权的应用", httpMethod = "POST", notes = "查询已授权的应用")
    public List<SysApp> queryByFilter(@ApiParam(name = "queryFilter", value = "通用查询对象") @RequestBody QueryFilter<SysApp> queryFilter) throws Exception {
        return sysAppManager.queryByFilter(queryFilter);
    }

    @PostMapping("/queryByTagIds/{menuId}")
    @ApiOperation(value = "通过标签ID查询获取已授权的应用", httpMethod = "POST", notes = "通过标签ID查询获取已授权应用")
    public List<SysApp> queryByTagIds(@ApiParam(name = "menuId", value = "菜单ID") @PathVariable String menuId,
                                      @ApiParam(name = "tagMaps", value = "查询对象") @RequestBody List<Map<String, String>> tagMaps) throws Exception {
        return sysAppManager.queryByTagIds(menuId, tagMaps);
    }

    /**
     * 新增应用信息
     *
     * @param sysApp
     * @return
     * @throws Exception
     * @throws
     */
    @PostMapping(value = "save")
    @ApiOperation(value = "新增,更新应用信息数据", httpMethod = "POST", notes = "新增,更新portal_sys_app数据")
    public CommonResult<String> save(@ApiParam(name = "sysApp", value = "应用信息业务对象", required = true) @RequestBody SysApp sysApp) throws Exception {
        String msg = "添加应用信息成功";
        if (StringUtil.isEmpty(sysApp.getId())) {

            sysAppManager.create(sysApp);
        } else {
            sysAppManager.update(sysApp);
            msg = "更新应用信息成功";
        }
        return new CommonResult<String>(msg);
    }

    /**
     * 批量删除portal_sys_app记录
     *
     * @param ids
     * @return
     * @throws Exception
     * @throws
     */
    @DeleteMapping(value = "/remove")
    @ApiOperation(value = "批量删除应用信息记录", httpMethod = "DELETE", notes = "批量删除应用信息记录")
    public CommonResult<String> removes(@ApiParam(name = "ids", value = "业务主键数组,多个业务主键之间用逗号分隔", required = true) @RequestParam String... ids) throws Exception {
        sysAppManager.removeByIds(ids);
        return new CommonResult<String>(true, "删除成功");
    }

    @PostMapping(value = "/publish")
    @ApiOperation(value = "发布应用", httpMethod = "POST", notes = "发布应用")
    public CommonResult<String> publish(@ApiParam(name = "id", value = "应用ID", required = true) @RequestBody SysApp sysApp) throws Exception {
        String message = SysApp.IS_PUBLISH.equals(sysApp.getIsPublish()) ? "发布成功" : "取消发布成功";
        sysAppManager.update(sysApp);
        return new CommonResult<String>(true, message);
    }

    @PostMapping(value = "/saveAppTags/{appId}")
    @ApiOperation(value = "保存应用标签", httpMethod = "POST", notes = "保存应用标签")
    public CommonResult<String> saveAppTags(@ApiParam(name = "appId", value = "应用ID", required = true) @PathVariable String appId,
                                            @ApiParam(name = "tagIds", value = "标签ID集", required = true) @RequestBody String tagIds) {
        try {
            appTagsRelationManager.saveAppTags(appId, tagIds);
            return new CommonResult<>(true, "保存成功");
        } catch (Exception e) {
            return new CommonResult<>(false, "保存失败");
        }
    }

    @GetMapping(value = "/getAppTagsById/{appId}")
    @ApiOperation(value = "根据应用ID获取应用标签", httpMethod = "GET", notes = "根据应用ID获取应用标签")
    public CommonResult<List<AppTagsRelation>> getAppTagsById(@ApiParam(name = "appId", value = "应用Id", required = true) @PathVariable String appId) throws Exception {
        List<AppTagsRelation> byAppId = appTagsRelationManager.getByAppId(appId);
        return new CommonResult<>(true, "获取成功", byAppId);
    }

    @GetMapping(value = "/validMenu")
    @ApiOperation(value = "获取APP首个有内容的菜单", httpMethod = "GET", notes = "获取APP首个有内容的菜单")
    public List<String> validMenu() throws Exception {
        List<String> validMenu = sysAppManager.getValidMenu(ContextUtil.getCurrentUserId());
        return validMenu;
    }

    @RequestMapping(value = "exportXml", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "导出应用xml", httpMethod = "GET", notes = "导出应用xml")
    public void exportXml(HttpServletRequest request, HttpServletResponse response,
                          @ApiParam(name = "ids", value = "应用id", required = true) @RequestParam String ids) throws Exception {
        response.setContentType("APPLICATION/OCTET-STREAM");
        if (BeanUtils.isNotEmpty(ids)) {
            String[] stringsIds = ids.split(",");
            List<String> list = Arrays.asList(stringsIds);
            String zipName = "ht_sysApp_" + DateFormatUtil.format(LocalDateTime.now(), "yyyy_MMdd_HHmmss");
            // 写XML
            Map<String, String> strXml = baseService.exportData(list);
            HttpUtil.downLoadFile(request, response, strXml, zipName);
        }
    }

    @RequestMapping(value = "import", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "应用导入", httpMethod = "POST", notes = "应用导入")
    public CommonResult<String> importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            CommonResult<String> message = new CommonResult<>("导入成功");
            baseService.importData(request.getFile("file"));
            // 应用 导入成功！
            LinkedHashSet<String> sysAppsSaved = ThreadMsgUtil.getMapMsg2("sysAppsSaved");
            // 应用 已存在故跳过！
            LinkedHashSet<String> sysAppsSkipped = ThreadMsgUtil.getMapMsg2("sysAppsSkipped");
            StringBuilder sb = new StringBuilder();
            if (BeanUtils.isNotEmpty(sysAppsSkipped)) {
                sb.append("<div style='font-weight:bold;'>以下应用已存在故跳过：</div>");
                String msg = String.format("%s", String.join("", sysAppsSkipped));
                sb.append(msg);
            }
            String msg = sb.toString();
            if (StringUtil.isNotEmpty(msg)) {
                message.setMessage(msg);
            }
            return message;
        } catch (Exception e) {
            return new CommonResult<>(false, "导入失败：" + e.getMessage());
        }
    }
}
