package com.artfess.application.controller;

import com.artfess.base.annotation.ApiGroup;
import com.artfess.base.constants.ApiGroupConsts;
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.application.model.AppModel;
import com.artfess.application.params.AppTree;
import com.artfess.application.persistence.manager.AppModelManager;
import com.artfess.sysConfig.persistence.manager.SysAuthUserManager;
import com.artfess.sysConfig.persistence.manager.SysCategoryManager;
import com.artfess.sysConfig.persistence.manager.SysTypeManager;
import com.artfess.sysConfig.persistence.model.SysCategory;
import com.artfess.sysConfig.persistence.model.SysType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <pre>
 * 描述：移动端应用 控制器类
 * 构建组：x7
 * 作者:pangq
 * 邮箱:pangq@jee-soft.cn
 * 日期:2020-07-06 15:25:12
 * 版权：广州宏天软件股份有限公司
 * </pre>
 */
@RestController
@RequestMapping(value = "/appModel/v1")
@Api(tags = "移动端应用")
@ApiGroup(group = {ApiGroupConsts.GROUP_APPLICATION})
public class AppModelController extends BaseController<AppModelManager, AppModel> {
    @Resource
    AppModelManager appModelManager;
    @Resource
    SysTypeManager sysTypeManager;
    @Resource
    SysCategoryManager sysCategoryManager;
    @Resource
    SysAuthUserManager sysAuthUserManager;

    /**
     * 移动端应用列表(分页条件查询)数据
     *
     * @param queryFilter
     * @return
     * @throws Exception PageJson
     * @throws
     */
    @PostMapping("/listJson")
    @ApiOperation(value = "移动端应用数据列表", httpMethod = "POST", notes = "获取移动端应用列表")
    public PageList<AppModel> list(@ApiParam(name = "queryFilter", value = "查询对象") @RequestBody QueryFilter<AppModel> queryFilter) throws Exception {
        List<FieldSort> sorter = queryFilter.getSorter();
        sorter.add(new FieldSort("ID_", Direction.DESC));
        queryFilter.setSorter(sorter);
        return appModelManager.query(queryFilter);
    }

    @RequestMapping(value = "getApp", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "根据可以key获取App", httpMethod = "GET", notes = "根据可以key获取App")
    public List<AppTree> getApp(@ApiParam(name = "typeKey", value = "分类key", required = true) @RequestParam String typeKey) throws Exception {
        SysCategory sysCategory = sysCategoryManager.getByTypeKey(typeKey);
        List<AppTree> appTrees = new ArrayList<>();
        if (BeanUtils.isEmpty(sysCategory)) {
            return appTrees;
        }
        List<SysType> list = sysTypeManager.getByGroupKey(sysCategory.getGroupKey());

        List<SysType> newList = sysAuthUserManager.getAuthItems(list, SysType::getId);
        List<String> authList = newList.stream().map(SysType::getId).collect(Collectors.toList());

        for (SysType sysType : list) {
            List<AppModel> appList = appModelManager.getByTypeId(sysType.getId());
            appList = sysAuthUserManager.getAuthItems(appList, AppModel::getId);

            AppTree appItem = new AppTree();
            appItem.setTypeId(sysType.getId());
            appItem.setTypeName(sysType.getName());
            appItem.setPid(sysType.getParentId());
            appItem.setAppList(appList);
            appTrees.add(appItem);
        }
        List<AppTree> rtnList = BeanUtils.listToTree(appTrees);
        rtnList = traversalTree(rtnList, authList, false);

        return rtnList;
    }

    private List<AppTree> traversalTree(List<AppTree> appTrees, List<String> authList, boolean isShow) {
        List<AppTree> trees = new ArrayList<>();
        for (AppTree tree : appTrees) {
            if (authList.contains(tree.getId())) {
                List<AppTree> children = traversalTree(tree.getChildren(), authList, true);
                tree.setChildren(children);
                trees.add(tree);
            } else {
                QueryWrapper wrapper = new QueryWrapper();
                wrapper.eq("authorize_id_", tree.getId());
                wrapper.eq("obj_type_", "app");
                if (sysAuthUserManager.count(wrapper) <= 0 && isShow) {
                    List<AppTree> children = traversalTree(tree.getChildren(), authList, true);
                    tree.setChildren(children);
                    trees.add(tree);
                }
            }
        }
        return trees;
    }

    /**
     * 移动端应用明细页面
     *
     * @param id
     * @return
     * @throws Exception ModelAndView
     */
    @GetMapping(value = "/getJson")
    @ApiOperation(value = "移动端应用数据详情", httpMethod = "GET", notes = "移动端应用数据详情")
    public AppModel get(@ApiParam(name = "id", value = "业务对象主键", required = true) @RequestParam String id) throws Exception {
        return appModelManager.get(id);
    }

    /**
     * 新增移动端应用
     *
     * @param appModel
     * @return
     * @throws Exception
     * @throws
     */
    @PostMapping(value = "save")
    @ApiOperation(value = "新增,更新移动端应用数据", httpMethod = "POST", notes = "新增,更新移动端应用数据")
    public CommonResult<String> save(@ApiParam(name = "appModel", value = "移动端应用业务对象", required = true) @RequestBody AppModel appModel) throws Exception {
        String msg = "添加移动端应用成功";
        if (StringUtil.isEmpty(appModel.getId())) {
            appModelManager.create(appModel);
        } else {
            appModelManager.update(appModel);
            msg = "更新移动端应用成功";
        }
        return new CommonResult<String>(msg);
    }

    @GetMapping(value = "updateEnable/{id}")
    @ApiOperation(value = "更改应用中心状态", httpMethod = "POST", notes = "更改应用中心状态")
    public CommonResult<String> updateEnable(@PathVariable("id") String id) {
        AppModel appModel = appModelManager.get(id);
        if (BeanUtils.isEmpty(appModel)) {
            return new CommonResult<>(false, "根据ID无法查询到应用中心");
        }
        if (appModel.getEnable().equals(0)) {
            appModel.setEnable(1);
        } else {
            appModel.setEnable(0);
        }
        appModelManager.update(appModel);
        return new CommonResult<>(true, "状态修改成功");
    }

    /**
     * 批量删除移动端应用记录
     *
     * @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 {
        appModelManager.removeByIds(ids);
        return new CommonResult<String>(true, "删除成功");
    }

    @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_appModel_" + 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> appModelsSaved = ThreadMsgUtil.getMapMsg2("appModelsSaved");
            // 移动端应用 已存在故跳过！
            LinkedHashSet<String> appModelsSkipped = ThreadMsgUtil.getMapMsg2("appModelsSkipped");
            StringBuilder sb = new StringBuilder();
            if (BeanUtils.isNotEmpty(appModelsSkipped)) {
                sb.append("<div style='font-weight:bold;'>以下移动端应用已存在故跳过：</div>");
                String msg = String.format("%s", String.join("", appModelsSkipped));
                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());
        }
    }
}
