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

import com.mortals.framework.exception.AppException;
import com.mortals.framework.util.DataUtil;
import com.mortals.framework.web.BaseCRUDJsonPhpController;
import com.mortals.xhx.base.system.param.service.ParamService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.BaseCRUDJsonMappingController;
import com.mortals.xhx.module.business.model.BusinessEntity;
import com.mortals.xhx.module.business.model.BusinessQuery;
import com.mortals.xhx.module.business.service.BusinessService;
import com.mortals.xhx.module.business.model.BusinessTreeSelect;
import org.apache.commons.lang3.ArrayUtils;
import com.mortals.framework.util.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import static com.mortals.framework.ap.SysConstains.RESULT_KEY;

/**
*
* 站点业务
*
* @author zxfei
* @date 2022-01-13
*/
@RestController
@RequestMapping("business")
public class BusinessController extends BaseCRUDJsonPhpController<BusinessService,BusinessForm,BusinessEntity,Long> {

    @Autowired
    private ParamService paramService;

    public BusinessController(){
        super.setFormClass(BusinessForm.class);
        super.setModuleDesc( "站点业务");
    }

    @Override
    protected void init(HttpServletRequest request, HttpServletResponse response, BusinessForm form, Map<String, Object> model, Context context) {
        this.addDict(model, "isBusiness", paramService.getParamBySecondOrganize("Business","isBusiness"));
        this.addDict(model, "canorder", paramService.getParamBySecondOrganize("Business","canorder"));
        this.addDict(model, "cantake", paramService.getParamBySecondOrganize("Business","cantake"));
        this.addDict(model, "datashow", paramService.getParamBySecondOrganize("Business","datashow"));
        this.addDict(model, "status", paramService.getParamBySecondOrganize("Business","status"));
        this.addDict(model, "businessType", paramService.getParamBySecondOrganize("Business","businessType"));
        super.init(request, response, form, model, context);
    }

    /**
     * 查询站点业务
     */
    @PostMapping(value = "list")
    public String list(@RequestBody BusinessQuery query) {
        try {
            BusinessForm form = new BusinessForm();
            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();
        }
    }


    @Override
    protected int doListAfter(HttpServletRequest request, HttpServletResponse response, BusinessForm form, Map<String, Object> model, Context context) throws AppException {
        List<BusinessEntity> businessEntities = (List<BusinessEntity>) model.get(RESULT_KEY);
        if(!ObjectUtils.isEmpty(businessEntities)){
            businessEntities.stream().peek(item->{
                List<BusinessEntity> childs = this.service.find(new BusinessQuery().parentId(item.getId()));
                if(!ObjectUtils.isEmpty(childs)){
                    item.setChildren(childs);
                }else{
                    item.setChildren(null);
                }
            }).count();
            model.put(RESULT_KEY,businessEntities);
        }
        return super.doListAfter(request, response, form, model, context);
    }

    /**
     * 添加业务到站点
     */
    @PostMapping(value = "addBusinessToSite")
    public String addBusinessToSite(@RequestBody Map<String, Object> map) {
        JSONObject jsonObject = new JSONObject();
        Map<String, Object> model = new HashMap<String, Object>();
        String businessIds=(String)map.get("businessIds");
        Long siteId= DataUtil.converObj2Long(map.get("siteId"));
        try {
            this.service.addBusinessToSite(businessIds,siteId,getContext());
            jsonObject.put(KEY_RESULT_DATA, model);
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            jsonObject.put(KEY_RESULT_MSG, "添加业务到站点成功！");
        } catch (Exception e) {
            log.error("获取异常", e);
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            jsonObject.put(KEY_RESULT_MSG, super.convertException(e));
        }
        return jsonObject.toJSONString();
    }

    /**
     * 新增站点业务
     */
    @PostMapping(value = "add")
    public String add() {
        try {
            BusinessForm form = new BusinessForm();
            return super.add(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 {
            BusinessForm form = new BusinessForm();
            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 BusinessEntity entity) {
        try {
            BusinessForm form = new BusinessForm();
            form.setBusiness(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 {
            BusinessForm form = new BusinessForm();
            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 {
            BusinessForm form = new BusinessForm();
            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();
        }
    }

    /**
     * 站点业务导出
     */
    @PostMapping("exportExcel")
    public void exportExcel(@RequestBody BusinessQuery query) {
        try {
            BusinessForm form = new BusinessForm();
            form.setQuery(query);
            super.exportExcel(form);
        } catch (Exception e) {
            log.error("站点业务导出错误", e);
        }
    }

}