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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.IUser;
import com.mortals.framework.util.DataUtil;
import com.mortals.framework.util.StringUtils;
import com.mortals.framework.web.BaseJsonBodyController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.pdu.device.DevicePdu;
import com.mortals.xhx.feign.base.IApiBaseManagerFeign;
import com.mortals.xhx.feign.base.pdu.DeptPdu;
import com.mortals.xhx.feign.base.pdu.SitePdu;
import com.mortals.xhx.feign.rsp.ApiResp;
import com.mortals.xhx.module.home.pdu.HomeQueryPdu;
import com.mortals.xhx.module.matter.model.MatterDatumEntity;
import com.mortals.xhx.module.matter.model.MatterEntity;
import com.mortals.xhx.module.matter.service.MatterDatumService;
import com.mortals.xhx.module.matter.service.MatterService;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;

import java.util.*;

@RestController
@RequestMapping("home")
public class HomeController extends BaseJsonBodyController {

    @Autowired
    private IApiBaseManagerFeign iApiBaseManagerFeign;
//    @Autowired
//    private IApiDeviceFeign iApiDeviceFeign;
    @Autowired
    private MatterDatumService matterDatumService;
    @Autowired
    private MatterService matterService;
    @Autowired
    private ParamService paramService;

    @PostMapping({"site/list"})
    public Rest<Object> list() {
        IUser user = this.getCurUser();
        if(user==null){
            throw new AppException("用户未登录");
        }
        Rest<Object> ret = new Rest();
        Map<String, Object> model = new HashMap();
        String busiDesc = "查询用户站点列表" ;

        int code=1;
        try {

            if(StringUtils.isNotEmpty(user.getSiteIds())){
                SitePdu sitePdu = new SitePdu();
                List<String> siteIds = Arrays.asList(user.getSiteIds().split(","));
                List<Long> idList = new ArrayList<>();
                siteIds.forEach(s -> {
                    idList.add(DataUtil.converStr2Long(s,0));
                });
                sitePdu.setIdList(idList);
                String resp = iApiBaseManagerFeign.getSitesByQuery(sitePdu);
                ApiResp<JSONObject> apiResp = JSON.parseObject(resp, ApiResp.class);
                if (apiResp.getCode() != YesNoEnum.YES.getValue()) {
                    throw new AppException("获取用户站点列表树数据失败：" + apiResp.getMsg());
                }
                if(apiResp.getData().get("data")!=null) {
                    model.put("data", apiResp.getData().get("data"));
                }else {
                    model.put("data", Collections.emptyList());
                }
            }else {
                model.put("data", Collections.emptyList());
            }
            model.put("message_info", busiDesc + "成功");
            this.recordSysLog(this.request, busiDesc + " 【成功】");
        } catch (Exception var9) {
            code = -1;
            this.doException(this.request, busiDesc, model, var9);
        }

        ret.setCode(code);
        ret.setData(model);
        ret.setDict(model.get("dict"));
        ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
        return ret;
    }

    @PostMapping({"dept/list"})
    @UnAuth
    public Rest<Object> deptList(@RequestBody HomeQueryPdu queryPdu) {
//        IUser user = this.getCurUser();
//        if(user==null){
//            throw new AppException("用户未登录");
//        }
        Rest<Object> ret = new Rest();
        Map<String, Object> model = new HashMap();
        String busiDesc = "查询站点部门列表" ;

        int code=1;
        try {

            if(queryPdu.getSiteId()!=null){
                DeptPdu deptPdu = new DeptPdu();
                deptPdu.setSiteId(queryPdu.getSiteId());
                deptPdu.setSize(-1);
                String resp = iApiBaseManagerFeign.getDeptByQuery(deptPdu);
                ApiResp<JSONObject> apiResp = JSON.parseObject(resp, ApiResp.class);
                if (apiResp.getCode() != YesNoEnum.YES.getValue()) {
                    throw new AppException("获取用户站点部门列表失败：" + apiResp.getMsg());
                }
                if(apiResp.getData().get("data")!=null) {
                    model.put("data", apiResp.getData().get("data"));
                }else {
                    model.put("data", Collections.emptyList());
                }
            }else {
                model.put("data", Collections.emptyList());
            }
            model.put("message_info", busiDesc + "成功");
            this.recordSysLog(this.request, busiDesc + " 【成功】");
        } catch (Exception var9) {
            code = -1;
            this.doException(this.request, busiDesc, model, var9);
        }

        ret.setCode(code);
        ret.setData(model);
        ret.setDict(model.get("dict"));
        ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
        return ret;
    }

   /* @PostMapping({"device/list"})
    @UnAuth
    public Rest<Object> deviceList(@RequestBody DevicePdu queryPdu) {
//        IUser user = this.getCurUser();
//        if(user==null){
//            throw new AppException("用户未登录");
//        }
        Rest<Object> ret = new Rest();
        Map<String, Object> model = new HashMap();
        String busiDesc = "查询站点设备列表" ;

        int code=1;
        try {

            if(queryPdu.getSiteId()!=null){
                String resp = iApiDeviceFeign.getDeviceByQuery(queryPdu);
                ApiResp<JSONObject> apiResp = JSON.parseObject(resp, ApiResp.class);
                if (apiResp.getCode() != YesNoEnum.YES.getValue()) {
                    throw new AppException("获取站点设备列表失败：" + apiResp.getMsg());
                }
                if(apiResp.getData().get("data")!=null) {
                    model.put("data", apiResp.getData().get("data"));
                    model.put("dict", apiResp.getData().get("dict"));
                    model.put("pageInfo",apiResp.getData().get("pageInfo"));
                }else {
                    model.put("data", Collections.emptyList());
                }
            }else {
                model.put("data", Collections.emptyList());
            }
            model.put("message_info", busiDesc + "成功");
            this.recordSysLog(this.request, busiDesc + " 【成功】");
        } catch (Exception var9) {
            code = -1;
            this.doException(this.request, busiDesc, model, var9);
        }

        ret.setCode(code);
        ret.setData(model);
        ret.setDict(model.get("dict"));
        ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
        return ret;
    }*/

    /**
     * 合成表单与模板
     */
    @PostMapping(value = "mergeFormToDocx")
    @UnAuth
    public String mergeFormToDocx(@RequestBody MatterDatumEntity docFormVo) {
        JSONObject jsonObject = new JSONObject();
        try {
            String paths = matterDatumService.mergeFormToDoc(docFormVo, getContext());
            String[] vals = paths.split(";");
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            jsonObject.put("mergeDoc", vals[0]);
            jsonObject.put("preview", vals[1]);
            //todo 保存表单数据
//            docFormVo.setCreateTime(new Date());
//            docFormVo.setCreateUserId(getContextUserId(getContext()));
//            docFormVo.setCreateUser("");
//            docFormService.save(docFormVo, getContext());
        } 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({"info"})
    @UnAuth
    public Rest<Object> homePageInfo() {

        Rest<Object> ret = new Rest();
        Map<String, Object> model = new HashMap();
        String busiDesc = "获取首页数据" ;

        int code=1;
        try {
            model.put("hotWords", paramService.getHotWords());
            MatterEntity matterQuery =  new MatterEntity();
            int matterCont = matterService.count(matterQuery,this.getContext());
            matterQuery.setIsRecommend(1);
            List<MatterEntity> matterList = matterService.find(matterQuery,this.getContext());
            model.put("matterList",matterList);   //热门事项
            model.put("matterCont",matterCont);   //入驻事项数量
            MatterDatumEntity matterDatumQuery = new MatterDatumEntity();
            int datumCont = matterDatumService.count(matterDatumQuery,this.getContext());
            matterDatumQuery.setIsRecommend(1);
            List<MatterDatumEntity> datumList = matterDatumService.find(matterDatumQuery,this.getContext());
            model.put("datumList",datumList);    //热门表单
            model.put("datumCont",datumCont);    //入驻表单数量

            model.put("localPrint",20);     //本地打印数量
            model.put("onlineSubmit",20);   //在线提交数量
            model.put("dayThrift",66);      //今日节约
            model.put("totalThrift",996);    //累计节约
            model.put("message_info", busiDesc + "成功");
            this.recordSysLog(this.request, busiDesc + " 【成功】");
        } catch (Exception var9) {
            code = -1;
            this.doException(this.request, busiDesc, model, var9);
        }

        ret.setCode(code);
        ret.setData(model);
        ret.setDict(model.get("dict"));
        ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
        return ret;
    }
}
