package com.mortals.xhx.busiz.web;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.model.Result;
import com.mortals.framework.service.ICacheService;
import com.mortals.xhx.busiz.req.ComplexImplementationReq;
import com.mortals.xhx.busiz.req.FindHandlingPageReq;
import com.mortals.xhx.busiz.req.accept.ComplexAcceptReq;
import com.mortals.xhx.busiz.rsp.ApiResp;
import com.mortals.xhx.busiz.rsp.ImplementEventInfo;
import com.mortals.xhx.busiz.rsp.RecordsItem;
import com.mortals.xhx.busiz.rsp.implement.ComplexImplementDetailInfo;
import com.mortals.xhx.busiz.rsp.material.ComplexMaterialInfo;
import com.mortals.xhx.busiz.rsp.situation.ComplexStituationInfo;
import com.mortals.xhx.busiz.rsp.work.ComplexWorkInfo;
import com.mortals.xhx.common.code.ApiRespCodeEnum;
import com.mortals.xhx.module.matter.model.ApplyMatterEntity;
import com.mortals.xhx.module.matter.model.ApplyMatterQuery;
import com.mortals.xhx.module.matter.model.EventImplementationEntity;
import com.mortals.xhx.module.matter.service.ApplyMatterService;
import com.mortals.xhx.module.matter.service.EventImplementationService;
import com.mortals.xhx.protocol.complex.matter.model.rsp.AcceptRspInfo;
import com.mortals.xhx.protocol.complex.matter.model.rsp.DictInfo;
import com.mortals.xhx.protocol.complex.matter.model.rsp.HandlingRspInfoList;
import lombok.extern.slf4j.Slf4j;
import org.apache.axis.utils.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
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.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import static com.mortals.xhx.common.key.Constant.HTTP_TIMEOUT;
import static com.mortals.xhx.common.key.RedisKey.KEY_COMPLEX_REQ;
import static com.mortals.xhx.common.key.RedisKey.KEY_EVENT_IMPLEMENTATION_RESP;

/**
 * 综窗对接api
 *
 * @author: zxfei
 * @date: 2023/11/30 14:17
 */
@RestController
@Slf4j
@RequestMapping("api")
public class ComplexApiController {

    @Autowired
    private ICacheService cacheService;

    @Autowired
    private ApplyMatterService applyMatterService;


    /**
     * 事项列表查询
     *
     * @param req
     * @return
     */
    @PostMapping("event-implementation/list")
    @UnAuth
    public String eventImplementationList(@RequestBody ComplexImplementationReq req) {
        log.info("【事项列表查询】【请求体】-->  " + JSONObject.toJSONString(req));
        req.setUrlPath("eventImplementation/list");
        ApiResp<Object> rsp = new ApiResp<>();
        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        try {
            PageInfo pageInfo = new PageInfo(req.getPageSize());
            pageInfo.setCurrPage(req.getCurrentPage());
            ApplyMatterEntity query = new ApplyMatterEntity();
            BeanUtils.copyProperties(req, query);

            Result<ApplyMatterEntity> result = applyMatterService.find(query,pageInfo,null);
            Map<String, Object> model = new HashMap();
            model.put("records",result.getList());
            model.put("current",result.getPageInfo().getCurrPage());
            model.put("pages",result.getPageInfo().getTotalPage());
            model.put("size",result.getPageInfo().getPrePageResult());
            model.put("total",result.getPageInfo().getTotalResult());
            rsp.setData(model);
//            req.setNonce(RandomUtil.randomNumbers(6));
//            cacheService.lpush(KEY_COMPLEX_REQ, JSONObject.toJSONString(req));
//            String rest = cacheService.blpop(KEY_EVENT_IMPLEMENTATION_RESP + req.getNonce(), HTTP_TIMEOUT, String.class);
//            if (ObjectUtil.isEmpty(rest)) {
//                throw new AppException("请求访问超时");
//            }
//            Rest<ImplementEventInfo> eventListRest = JSON.parseObject(rest, new TypeReference<Rest<ImplementEventInfo>>() {
//            });
//            if(eventListRest.getCode()==1){
//                Integer applyType = req.getApplyType()==null?1:req.getApplyType();
//                List<ApplyMatterEntity> entityList = applyMatterService.find(new ApplyMatterQuery().applyType(applyType));
//                if(CollectionUtils.isNotEmpty(entityList)) {
//                    Set<String> matter = entityList.stream().map(t -> t.getEventId()).collect(Collectors.toSet());
//                    for (RecordsItem item : eventListRest.getData().getRecords()) {
//                        if(matter.contains(item.getEventId())){
//                            item.setEnableFlag(1);
//                        }else {
//                            item.setEnableFlag(0);
//                        }
//                    }
//                }
//            }
            return JSON.toJSONString(rsp);
        } catch (Exception e) {
            log.error("接收数据失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        }
    }

    /**
     * 事项详细查询
     *
     * @param req
     * @return
     */
    @PostMapping("event-implementation/get-by-id")
    @UnAuth
    public String implementationGetById(@RequestBody ComplexImplementationReq req) {
        log.info("【事项详细查询】【请求体】-->  " + JSONObject.toJSONString(req));
        req.setUrlPath("event-implementation/get-by-id");
        ApiResp<String> rsp = new ApiResp<>();
        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        try {
            req.setNonce(RandomUtil.randomNumbers(6));
            cacheService.lpush(KEY_COMPLEX_REQ, JSONObject.toJSONString(req));
            String rest = cacheService.blpop(KEY_EVENT_IMPLEMENTATION_RESP + req.getNonce(), HTTP_TIMEOUT, String.class);
            if (ObjectUtil.isEmpty(rest)) {
                throw new AppException("请求访问超时");
            }
            Rest<ComplexImplementDetailInfo> eventRest = JSON.parseObject(rest, new TypeReference<Rest<ComplexImplementDetailInfo>>() {
            });
            return JSON.toJSONString(eventRest);
        } catch (Exception e) {
            log.error("接收数据失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        }
    }

    /**
     * 查询办理事项情形
     *
     * @param req
     * @return
     */
    @PostMapping("bus-situation-material/getSituationMaterialTreeByEventIds")
    @UnAuth
    public String getSituationMaterialTreeByEventIds(@RequestBody ComplexImplementationReq req) {
        log.info("【查询办理事项情形】【请求体】-->  " + JSONObject.toJSONString(req));
        req.setUrlPath("bus-situation-material/getSituationMaterialTreeByEventIds");
        ApiResp<String> rsp = new ApiResp<>();
        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        try {
            req.setNonce(RandomUtil.randomNumbers(6));
            cacheService.lpush(KEY_COMPLEX_REQ, JSONObject.toJSONString(req));
            String rest = cacheService.blpop(KEY_EVENT_IMPLEMENTATION_RESP + req.getNonce(), HTTP_TIMEOUT, String.class);
            if (ObjectUtil.isEmpty(rest)) {
                throw new AppException("请求访问超时");
            }
            Rest<List<ComplexStituationInfo>> eventRest = JSON.parseObject(rest, new TypeReference<Rest<List<ComplexStituationInfo>>>() {
            });
            return JSON.toJSONString(eventRest);
        } catch (Exception e) {
            log.error("接收数据失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        }
    }

    /**
     * 根据事项与情形查询办理事项材料
     *
     * @param req
     * @return
     */
    @PostMapping("consulting-service/getMaterialByEventAndSituation")
    @UnAuth
    public String getMaterialByEventAndSituation(@RequestBody ComplexImplementationReq req) {
        log.info("【根据事项与情形查询办理事项材料】【请求体】-->  " + JSONObject.toJSONString(req));
        req.setUrlPath("consulting-service/getMaterialByEventAndSituation");
        ApiResp<String> rsp = new ApiResp<>();
        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        try {
            req.setNonce(RandomUtil.randomNumbers(6));
            cacheService.lpush(KEY_COMPLEX_REQ, JSONObject.toJSONString(req));
            String rest = cacheService.blpop(KEY_EVENT_IMPLEMENTATION_RESP + req.getNonce(), HTTP_TIMEOUT, String.class);
            if (ObjectUtil.isEmpty(rest)) {
                throw new AppException("请求访问超时");
            }
            Rest<List<ComplexMaterialInfo>> eventRest = JSON.parseObject(rest, new TypeReference<Rest<List<ComplexMaterialInfo>>>() {
            });
            return JSON.toJSONString(eventRest);
        } catch (Exception e) {
            log.error("接收数据失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        }
    }

    /**
     * 根据事项查询办理事项材料
     *
     * @param req
     * @return
     */
    @PostMapping("material/findList")
    @UnAuth
    public String materialFindList(@RequestBody ComplexImplementationReq req) {
        log.info("【根据事项查询办理事项材料】【请求体】-->  " + JSONObject.toJSONString(req));
        req.setUrlPath("material/findList");
        ApiResp<String> rsp = new ApiResp<>();
        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        try {
            req.setNonce(RandomUtil.randomNumbers(6));
            cacheService.lpush(KEY_COMPLEX_REQ, JSONObject.toJSONString(req));
            String rest = cacheService.blpop(KEY_EVENT_IMPLEMENTATION_RESP + req.getNonce(), HTTP_TIMEOUT, String.class);
            if (ObjectUtil.isEmpty(rest)) {
                throw new AppException("请求访问超时");
            }
            Rest<List<ComplexMaterialInfo>> eventRest = JSON.parseObject(rest, new TypeReference<Rest<List<ComplexMaterialInfo>>>() {
            });
            return JSON.toJSONString(eventRest);
        } catch (Exception e) {
            log.error("接收数据失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        }
    }


    /**
     * 获取办件要素
     *
     * @param req
     * @return
     */
    @PostMapping("event-implementation/getDynamicFormByEventIds")
    @UnAuth
    public String getDynamicFormByEventIds(@RequestBody ComplexImplementationReq req) {
        log.info("【获取办件要素】【请求体】-->  " + JSONObject.toJSONString(req));
        req.setUrlPath("event-implementation/getDynamicFormByEventIds");
        ApiResp<String> rsp = new ApiResp<>();
        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        try {
            req.setNonce(RandomUtil.randomNumbers(6));
            cacheService.lpush(KEY_COMPLEX_REQ, JSONObject.toJSONString(req));
            String rest = cacheService.blpop(KEY_EVENT_IMPLEMENTATION_RESP + req.getNonce(), HTTP_TIMEOUT, String.class);
            if (ObjectUtil.isEmpty(rest)) {
                throw new AppException("请求访问超时");
            }
            Rest<ComplexWorkInfo> eventRest = JSON.parseObject(rest, new TypeReference<Rest<ComplexWorkInfo>>() {
            });
            return JSON.toJSONString(eventRest);
        } catch (Exception e) {
            log.error("接收数据失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        }
    }

    /**
     * 查询字典值
     *
     * @param req
     * @return
     */
    @PostMapping("common/queryDict")
    @UnAuth
    public String queryDict(@RequestBody ComplexImplementationReq req) {
        log.info("【查询字典值】【请求体】-->  " + JSONObject.toJSONString(req));
        req.setUrlPath("common/queryDict");
        ApiResp<String> rsp = new ApiResp<>();
        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        try {
            req.setNonce(RandomUtil.randomNumbers(6));
            cacheService.lpush(KEY_COMPLEX_REQ, JSONObject.toJSONString(req));
            String rest = cacheService.blpop(KEY_EVENT_IMPLEMENTATION_RESP + req.getNonce(), HTTP_TIMEOUT, String.class);
            if (ObjectUtil.isEmpty(rest)) {
                throw new AppException("请求访问超时");
            }
            Rest<List<DictInfo>> eventRest = JSON.parseObject(rest, new TypeReference<Rest<List<DictInfo>>>() {
            });
            return JSON.toJSONString(eventRest);
        } catch (Exception e) {
            log.error("接收数据失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        }
    }


    /**
     * 自助设备接件
     *
     * @param req
     * @return
     */
    @PostMapping("self-device-info/acceptHandling")
    @UnAuth
    public String acceptHandling(@RequestBody ComplexAcceptReq req) {
        log.info("【自助设备接件】【请求体】-->  " + JSONObject.toJSONString(req));
        req.setUrlPath("self-device-info/acceptHandling");
        ApiResp<String> rsp = new ApiResp<>();
        if(CollectionUtils.isEmpty(req.getHandlings())){
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg("办理事项参数为空");
            return JSON.toJSONString(rsp);
        }
        List<String> eventIds = req.getHandlings().stream().map(i->i.getEventId()).collect(Collectors.toList());
        List<ApplyMatterEntity> entityList = applyMatterService.find(new ApplyMatterQuery().applyType(req.getApplyType()).eventIdList(eventIds));
        if(CollectionUtils.isEmpty(entityList)||entityList.size()!=eventIds.size()){
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg("事项没有启用，无法申报");
            return JSON.toJSONString(rsp);
        }
        if(CollectionUtils.isNotEmpty(req.getMaterials())){
            if(StringUtils.isEmpty(req.getMaterials().get(0).getMaterialContent())){
                log.info("材料附件为空");
            }
        }

        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        try {
            req.setNonce(RandomUtil.randomNumbers(6));
            cacheService.lpush(KEY_COMPLEX_REQ, JSONObject.toJSONString(req));
            String rest = cacheService.blpop(KEY_EVENT_IMPLEMENTATION_RESP + req.getNonce(), 30, String.class);
            if (ObjectUtil.isEmpty(rest)) {
                throw new AppException("请求访问超时");
            }
            Rest<List<AcceptRspInfo>> eventRest = JSON.parseObject(rest, new TypeReference<Rest<List<AcceptRspInfo>>>() {
            });
            return JSON.toJSONString(eventRest);
        } catch (Exception e) {
            log.error("接收数据失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        }
    }

    /**
     * 查询已受理事项列表
     *
     * @param req
     * @return
     */
    @PostMapping("handling/findPageWithPermission")
    @UnAuth
    public String findPageWithPermission(@RequestBody FindHandlingPageReq req) {
        log.info("【查询已受理事项列表】【请求体】-->  " + JSONObject.toJSONString(req));
        req.setUrlPath("handling/findPageWithPermission");
        ApiResp<String> rsp = new ApiResp<>();
        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        try {
            req.setNonce(RandomUtil.randomNumbers(6));
            cacheService.lpush(KEY_COMPLEX_REQ, JSONObject.toJSONString(req));
            String rest = cacheService.blpop(KEY_EVENT_IMPLEMENTATION_RESP + req.getNonce(), HTTP_TIMEOUT, String.class);
            if (ObjectUtil.isEmpty(rest)) {
                throw new AppException("请求访问超时");
            }
            Rest<HandlingRspInfoList> eventRest = JSON.parseObject(rest, new TypeReference<Rest<HandlingRspInfoList>>() {
            });
            return JSON.toJSONString(eventRest);
        } catch (Exception e) {
            log.error("接收数据失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        }
    }

    /**
     * 文件下载
     *
     * @param req
     * @return
     */
    @PostMapping("common/downloadFileFtp")
    @UnAuth
    public String downloadFileFtp(@RequestBody FindHandlingPageReq req) {
        log.info("【查询字典值】【请求体】-->  " + JSONObject.toJSONString(req));
        req.setUrlPath("common/downloadFileFtp");
        ApiResp<String> rsp = new ApiResp<>();
        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        try {
            req.setNonce(RandomUtil.randomNumbers(6));
            cacheService.lpush(KEY_COMPLEX_REQ, JSONObject.toJSONString(req));
            String rest = cacheService.blpop(KEY_EVENT_IMPLEMENTATION_RESP + req.getNonce(), HTTP_TIMEOUT, String.class);
            if (ObjectUtil.isEmpty(rest)) {
                throw new AppException("请求访问超时");
            }
            Rest<String> eventRest = JSON.parseObject(rest, new TypeReference<Rest<String>>() {
            });
            return JSON.toJSONString(eventRest);
        } catch (Exception e) {
            log.error("接收数据失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        }
    }

    public static void main(String[] args) {

        File file = new File("E:\\pic\\1.png");

        String encode = Base64.encode(file);
        System.out.println(encode);

    }


}
