package com.mortals.xhx.module.area.web;

import com.mortals.xhx.base.system.param.service.ParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.mortals.framework.model.Context;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mortals.framework.web.BaseCRUDJsonPhpController;
import com.mortals.xhx.module.area.model.AreaEntity;
import com.mortals.xhx.module.area.model.AreaQuery;
import com.mortals.xhx.module.area.service.AreaService;
import com.mortals.xhx.module.area.model.AreaTreeSelect;
import org.apache.commons.lang3.ArrayUtils;
import com.mortals.framework.util.StringUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSONObject;
import java.util.Arrays;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import static com.mortals.framework.ap.SysConstains.*;
/**
 *
 * 区域
 *
 * @author zxfei
 * @date 2022-01-19
 */
@RestController
@RequestMapping("area")
public class AreaController extends BaseCRUDJsonPhpController<AreaService,AreaForm,AreaEntity,Long> {

    @Autowired
    private ParamService paramService;

    public AreaController(){
        super.setFormClass(AreaForm.class);
        super.setModuleDesc( "区域");
    }

    @Override
    protected void init(HttpServletRequest request, HttpServletResponse response, AreaForm form, Map<String, Object> model, Context context) {
        this.addDict(model, "haveSonArea", paramService.getParamBySecondOrganize("Area","haveSonArea"));
        this.addDict(model, "haveSonDept", paramService.getParamBySecondOrganize("Area","haveSonDept"));
        this.addDict(model, "haveGetDept", paramService.getParamBySecondOrganize("Area","haveGetDept"));
        this.addDict(model, "haveGetMatterList", paramService.getParamBySecondOrganize("Area","haveGetMatterList"));
        this.addDict(model, "areaLevel", paramService.getParamBySecondOrganize("Area","areaLevel"));
        this.addDict(model, "status", paramService.getParamBySecondOrganize("Area","status"));
        super.init(request, response, form, model, context);
    }

    @PostMapping("list/exclude")
    public String excludeList(AreaForm form) {
        Map<String, Object> model = new HashMap<>();
        JSONObject ret = new JSONObject();
        String busiDesc = "查询" + this.getModuleDesc();
        Long id = form.getId()[0];
        int code=VALUE_RESULT_SUCCESS;
        try {
            List<AreaEntity> collect = this.service.find(new AreaQuery()).stream().map(item -> {
                if (item.getId().intValue() == id || ArrayUtils.contains(StringUtils.split(item.getAncestors(), ","), id + "")) {
                    return null;
                }
                return item;
            }).filter(f -> f != null).collect(Collectors.toList());
            model.put("result", collect);
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            code = VALUE_RESULT_FAILURE;
            this.doException(request, busiDesc, model, e);
        }
        ret.put(KEY_RESULT_DATA, model);
        ret.put(KEY_RESULT_CODE, code);
        return ret.toJSONString();
    }


    /**
     * 获取站点下拉树列表
     */
    @PostMapping("treeselect")
    public String treeselect() {
        Map<String, Object> model = new HashMap<>();
        JSONObject ret = new JSONObject();
        String busiDesc = "查询" + this.getModuleDesc();
        int code=VALUE_RESULT_SUCCESS;
        try {
            List<AreaEntity> list = this.service.find(new AreaQuery());
            List<AreaTreeSelect> treeSelects = this.service.buildAreaTreeSelect(list);
            model.put(KEY_RESULT_DATA, treeSelects);
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            code = VALUE_RESULT_FAILURE;
            this.doException(request, busiDesc, model, e);
        }
        ret.put(KEY_RESULT_DATA, model);
        ret.put(KEY_RESULT_CODE, code);
        return ret.toJSONString();
    }


    /**
     * 根据parentId查询子信息
     */
    @GetMapping(value = "getListByParentId")
    public String getListByParentId(String parentId) {
        JSONObject ret = new JSONObject();
        Map<String, Object> model = new HashMap<>();
        String busiDesc = "查询" + this.getModuleDesc()+"子节点";
        try {
            List<AreaTreeSelect> treeList = this.service.getListByParentId(parentId, getContext());
            model.put(KEY_RESULT_DATA,treeList);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            ret.put(KEY_RESULT_DATA, model);
            recordSysLog(request, busiDesc+"【成功】");
        } catch (Exception e) {
            log.error("根据parentId查询子信息错误", e);
            this.doException(request, busiDesc, model, e);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, e.getMessage());
        }
        return ret.toJSONString();
    }

    /**
     * 查询区域
     */
    @PostMapping(value = "list")
    public String list(@RequestBody AreaQuery query) {
        try {
            AreaForm form = new AreaForm();
            form.setQuery(query);
            return super.list(form);
        } catch (Exception e) {
            log.error("查询区域列表错误", e);
            JSONObject ret = new JSONObject();
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        }
    }

    /**
     * 区域模块
     */
    @GetMapping(value = "edit")
    public String edit(Long id) {
        try {
            AreaForm form = new AreaForm();
            form.setId(new Long[]{id});
            return super.edit(form);
        } catch (Exception e) {
            log.error("区域模块错误", e);
            JSONObject ret = new JSONObject();
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        }
    }

    /**
     * 保存区域
     */
    @PostMapping(value = "save")
    public String save(@RequestBody AreaEntity entity) {
        try {
            AreaForm form = new AreaForm();
            form.setArea(entity);
            return super.save(form);
        } catch (Exception e) {
            log.error("区域模块错误", e);
            JSONObject ret = new JSONObject();
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        }
    }

    /**
     * 删除区域
     */
    @GetMapping(value = "delete")
    public String delete(String id) {
        try {
            AreaForm form = new AreaForm();
            String[] split = id.split(",");
            Long[] ids = Arrays.asList(split).stream().map(Long::parseLong).toArray(Long[]::new);
            form.setId(ids);
            return super.delete(form);
        } catch (Exception e) {
            log.error("删除区域错误", e);
            JSONObject ret = new JSONObject();
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        }
    }

    /**
     * 查看区域
     */
    @GetMapping(value = "info")
    public String info(Long id) {
        try {
            AreaForm form = new AreaForm();
            form.setId(new Long[]{id});
            return super.view(form);
        } catch (Exception e) {
            log.error("查看区域错误", e);
            JSONObject ret = new JSONObject();
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        }
    }


    /**
     * 模块导入模板下载
     */
    @PostMapping(value = "downloadTemplate")
    public void downloadTemplate() {
        try {
            super.downloadTemplate();
        } catch (Exception e) {
            log.error("区域导入模板下载错误", e);
        }
    }

    /**
     * 模块导入
     */
    @PostMapping(value = "importData")
    public String importData(MultipartFile file, boolean updateSupport) {
        try {
            return super.importData(file, updateSupport);
        } catch (Exception e) {
            log.error("区域导入错误", e);
            JSONObject ret = new JSONObject();
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        }
    }
}