package com.artfess.portal.controller;

import com.artfess.base.annotation.ApiGroup;
import com.artfess.base.constants.ApiGroupConsts;
import com.artfess.base.context.BaseContext;
import com.artfess.base.controller.BaseController;
import com.artfess.base.handler.MultiTenantHandler;
import com.artfess.base.model.CommonResult;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.FileUtil;
import com.artfess.base.util.HttpUtil;
import com.artfess.base.util.JsonUtil;
import com.artfess.base.util.StringUtil;
import com.artfess.base.util.ThreadMsgUtil;
import com.artfess.base.util.UniqueIdUtil;
import com.artfess.base.util.ZipUtil;
import com.artfess.base.util.time.DateFormatUtil;
import com.artfess.portal.model.SysIndexColumn;
import com.artfess.portal.persistence.manager.SysIndexColumnManager;
import com.artfess.sysConfig.persistence.manager.SysAuthUserManager;
import com.artfess.uc.api.impl.util.ContextUtil;
import com.artfess.uc.api.service.IOrgService;
import com.artfess.uc.api.service.IUserGroupService;
import com.artfess.uc.api.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 首页栏目 控制器类
 *
 * @author maoww
 * @company 阿特菲斯信息技术有限公司
 * @email maoww@jee-soft.cn
 * @date 2018年6月14日
 */
@RestController
@RequestMapping("/portal/sysIndexColumn/sysIndexColumn/v1/")
@Api(tags = "门户栏目")
@ApiGroup(group = {ApiGroupConsts.GROUP_SYSTEM})
public class SysIndexColumnController extends BaseController<SysIndexColumnManager, SysIndexColumn> {
    @Resource
    SysIndexColumnManager sysIndexColumnService;
    @Resource
    IOrgService sysOrgService;
    @Resource
    IUserService ius;
    @Resource
    IUserGroupService ig;
    @Resource
    BaseContext baseContext;
    @Resource
    MultiTenantHandler multiTenantHandler;
    @Resource
    SysAuthUserManager sysAuthUserManager;
    @Value("${system.saas.enable:false}")
    Boolean saasEnable;

    @RequestMapping(value = "listJson", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "列表(分页条件查询)数据", httpMethod = "POST", notes = "列表(分页条件查询)数据")
    public PageList<SysIndexColumn> listJson(@ApiParam(name = "queryFilter", value = "通用查询对象") @RequestBody QueryFilter<SysIndexColumn> queryFilter) throws Exception {
        return sysIndexColumnService.query(queryFilter);
    }

    @RequestMapping(value = "getJson", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "明细页面", httpMethod = "GET", notes = "明细页面")
    public @ResponseBody
    SysIndexColumn getJson(@ApiParam(name = "id", value = "主键", required = true) @RequestParam String id) throws Exception {
        if (BeanUtils.isEmpty(id)) {
            return null;
        }
        return sysIndexColumnService.get(id);
    }

    @RequestMapping(value = "getByAlias", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "明细页面", httpMethod = "GET", notes = "明细页面")
    public @ResponseBody
    SysIndexColumn getByAlias(@ApiParam(name = "alias", value = "主键", required = true) @RequestParam String alias) throws Exception {
        if (BeanUtils.isEmpty(alias)) {
            return null;
        }

        return sysIndexColumnService.getByColumnAlias(alias);
    }

    @RequestMapping(value = "remove", method = RequestMethod.DELETE, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "批量删除记录", httpMethod = "DELETE", notes = "批量删除记录")
    public CommonResult<String> remove(@ApiParam(name = "ids", value = "主键", required = true) @RequestParam String ids) throws Exception {
        try {
            String[] aryIds = StringUtil.getStringAryByStr(ids);
            sysIndexColumnService.removeByIds(aryIds);
            return new CommonResult<>(true, ThreadMsgUtil.getMessage(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult<>(false, "删除栏目失败", null);
        }
    }

    @RequestMapping(value = "save", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "添加或更新首页栏目", httpMethod = "POST", notes = "添加或更新首页栏目")
    public CommonResult<String> save(@ApiParam(name = "sysIndexColumn", value = "首页栏目") @RequestBody SysIndexColumn sysIndexColumn) throws Exception {
        String message = null;
        try {
            String alias = sysIndexColumn.getAlias();
            // 判断别名是否存在。
            Boolean isExist = sysIndexColumnService.isExistAlias(sysIndexColumn.getAlias(), sysIndexColumn.getId());
            if (isExist) {
                message = "栏目别名：[" + alias + "]已存在";
                return new CommonResult<>(false, message, null);
            }
            if (!ContextUtil.getCurrentUser().isAdmin()) {// 把自己的组织设置进去
                String orgId = ig.getGroupsByUserIdOrAccount(ContextUtil.getCurrentUserId()).get(0).getGroupId();
                if (BeanUtils.isNotEmpty(orgId))
                    sysIndexColumn.setOrgId(orgId);
            }
            if (StringUtil.isZeroEmpty(sysIndexColumn.getId())) {
                sysIndexColumn.setId(UniqueIdUtil.getSuid());
                sysIndexColumn.setCreateTime(LocalDateTime.now());
                sysIndexColumnService.createAndAuth(sysIndexColumn);
                message = "添加首页栏目成功";
            } else {
                sysIndexColumn.setUpdateTime(LocalDateTime.now());
                sysIndexColumnService.update(sysIndexColumn);
                message = "更新首页栏目成功";
            }
            return new CommonResult<>(true, message, null);
        } catch (Exception e) {
            return new CommonResult<>(false, message + "," + e.getMessage(), null);
        }
    }

    @RequestMapping(value = "getTemp", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "预览模版", httpMethod = "POST", notes = "预览模版")
    public String getTemp(@ApiParam(name = "id", value = "主键", required = true) @RequestParam String id) throws Exception {
        String html = "";
        SysIndexColumn sysIndexColumn = sysIndexColumnService.get(id);
        if (BeanUtils.isNotEmpty(sysIndexColumn)) {
            html = "<div template-alias=\"" + sysIndexColumn.getAlias()
                    + "\"></div>";
        }
        return JsonUtil.toJson(html);
    }

    @RequestMapping(value = "getData", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "取得首页栏目明细", httpMethod = "POST", notes = "取得首页栏目明细")
    public String getData(@ApiParam(name = "alias", value = "别名", required = true) @RequestParam String alias,
                          @ApiParam(name = "params", value = "参数", required = true) @RequestParam String params
    ) throws Exception {
        Map<String, Object> param = getParameterValueMap(params);
        String data = "";
        try {
            data = sysIndexColumnService.getHtmlByColumnAlias(alias, param);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return data;
    }

    @RequestMapping(value = "parseByAlias", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "取得首页栏目明细", httpMethod = "POST", notes = "取得首页栏目明细")
    public String parseByAlias(@ApiParam(name = "alias", value = "别名", required = true) @RequestParam String alias,
                               @ApiParam(name = "params", value = "参数", required = true) @RequestParam String params
    ) throws Exception {
        Map<String, Object> param = getParameterValueMap(params);
        String data = "";
        try {
            data = sysIndexColumnService.getHtmlByColumnAlias(alias, param);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return data;
    }

    @RequestMapping(value = "getDatasByAlias", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "取得首页栏目明细（根据别名批量获取）", httpMethod = "POST", notes = "取得首页栏目明细（根据别名批量获取）")
    public List<SysIndexColumn> getDatasByAlias(@ApiParam(name = "alias", value = "别名(多个用“,”号隔开)", required = true) @RequestBody String alias) throws Exception {
        return baseService.batchGetColumnAliases(alias);
    }

    private Map<String, Object> getParameterValueMap(String params) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        if (BeanUtils.isEmpty(params))
            return map;
        ObjectNode node = (ObjectNode) JsonUtil.toJsonNode(params);
        Iterator<?> it = node.fields();
        while (it.hasNext()) {
            String key = (String) it.next();
            Object value = node.get(key);
            map.put(key, value);
        }
        return map;
    }

    @GetMapping(value = "validateProcAnn", produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "根据流程定义key判断该流程公示列表能否访问", httpMethod = "GET", notes = "根据流程定义key判断该流程公示列表能否访问")
    public CommonResult validateProcAnn(@ApiParam(name = "defKey", value = "流程定义key") @RequestParam String defKey) throws Exception {
        QueryWrapper<SysIndexColumn> qw = new QueryWrapper<>();
        //获取门户应用
        qw.eq("COL_TYPE", 2);
        qw.eq("is_public", 2);
        qw.eq("col_url", "/completeView/" + defKey);
        List<SysIndexColumn> sysIndexColumns = baseService.getBaseMapper().selectList(qw);
        if (BeanUtils.isEmpty(sysIndexColumns)) {
            return new CommonResult(false, "该流程未配置流程公示");
        }
        //判断当前用户是否有该流程公示栏目的权限
        for (SysIndexColumn column : sysIndexColumns) {
            if (sysAuthUserManager.hasRights(column.getId())) {
                return new CommonResult(true, "");
            }
        }
        return new CommonResult(false, "您无权查看该流程的流程公示");
    }

    @PostMapping(value = "exportColumn", produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "根据id集合导出门户栏目", httpMethod = "POST", notes = "根据id集合导出门户栏目")
    public void exportColumn(@ApiParam(name = "ids", value = "id集合") @RequestBody List<String> ids,
                             HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = "indexColumn_" + DateFormatUtil.format(LocalDateTime.now(), "yyyy_MM_dd_HHmm");
        String json = baseService.exportColumn(ids);
        HttpUtil.downLoadFile(request, response, json, "indexColumns.json", fileName);
    }

    @RequestMapping(value = "importColumn", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "导入栏目", httpMethod = "POST", notes = "导入栏目")
    public CommonResult importColumn(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartFile file = request.getFile("file");
        String uzPath = "";
        try {
            String rootRealPath = (FileUtil.getIoTmpdir() + "/attachFiles/unZip/").replace("/", File.separator);
            FileUtil.createFolder(rootRealPath, true);
            String name = file.getOriginalFilename();
            String fileDir = StringUtil.substringBeforeLast(name, ".");
            ZipUtil.unZipFile(file, rootRealPath); // 解压文件
            uzPath = rootRealPath + File.separator + fileDir; // 解压后文件的真正路径
            baseService.importFile(uzPath);
            return new CommonResult<>(true, "导入成功");
        } catch (Exception e) {
            return new CommonResult(false, "导入失败：" + e.getMessage());
        } finally {
            if (StringUtil.isNotEmpty(uzPath)) {
                File file1 = new File(uzPath);
                if (file1.exists()) {
                    file1.delete();
                }
            }
        }
    }

}
