package com.qmth.teachcloud.cas.mq.gdpu.api;

import com.qmth.boot.api.annotation.Aac;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.teachcloud.cas.mq.gdpu.cache.FlowMqCacheUtil;
import com.qmth.teachcloud.exchange.common.bean.dto.flow.DoneTaskDto;
import com.qmth.teachcloud.exchange.common.bean.dto.flow.ToDoTaskDto;
import com.qmth.teachcloud.exchange.common.bean.dto.syssetting.SimpleObject;
import com.qmth.teachcloud.exchange.common.contant.SystemConstant;
import com.qmth.teachcloud.exchange.common.entity.BasicSchool;
import com.qmth.teachcloud.exchange.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.exchange.common.service.CommonCacheService;
import com.qmth.teachcloud.exchange.common.util.*;
import io.swagger.annotations.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "广东药科大学获取流程消息controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_GDPU_MQ)
@Aac(auth = false)
@Validated
public class OpenMqController {
    private final static Logger log = LoggerFactory.getLogger(OpenMqController.class);

    @Resource
    CommonCacheService commonCacheService;

    @RequestMapping(value = "/{schoolCode}/todotask", method = RequestMethod.POST)
    @ApiOperation(value = "获取流程待办信息")
    @ApiResponses({@ApiResponse(code = 200, message = "常规信息", response = ResultUtil.class)})
    public Result toDoTask(@ApiParam(value = "学校编码") @PathVariable("schoolCode") String schoolCode,
                           @ApiParam(value = "消息数据", required = true) @RequestBody String data) throws IOException {
        Optional.ofNullable(data).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("账号为空"));
        String decodeJson = URLDecoder.decode(data, SystemConstant.CHARSET_NAME);
        ToDoTaskDto toDoTaskDto = JacksonUtil.readJson(decodeJson, ToDoTaskDto.class);
        log.info("todotask进来了,toDoTaskDto:{}", JacksonUtil.parseJson(toDoTaskDto));

        BasicSchool basicSchool = AuthThirdUtil.hasPermission();
        //发送广药流程
        if (Objects.nonNull(toDoTaskDto.getFlowData())) {
            this.sendFlowDataMq(basicSchool.getId(), String.valueOf(toDoTaskDto.getFlowData().getFlowId()));
            FlowMqCacheUtil.setSchoolId(toDoTaskDto.getFlowData().getFlowId(), String.valueOf(basicSchool.getId()));
            FlowMqCacheUtil.setToDoTask(toDoTaskDto.getFlowData().getFlowId(), toDoTaskDto);
        }
        return ResultUtil.ok(true);
    }

    @RequestMapping(value = "/{schoolCode}/donetask", method = RequestMethod.POST)
    @ApiOperation(value = "获取流程已办信息")
    @ApiResponses({@ApiResponse(code = 200, message = "常规信息", response = ResultUtil.class)})
    public Result doneTask(@ApiParam(value = "学校编码") @PathVariable("schoolCode") String schoolCode,
                           @ApiParam(value = "消息数据", required = true) @RequestBody String data) throws IOException {
        Optional.ofNullable(data).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("账号为空"));
        String decodeJson = URLDecoder.decode(data, SystemConstant.CHARSET_NAME);
        DoneTaskDto doneTaskDto = JacksonUtil.readJson(decodeJson, DoneTaskDto.class);
        log.info("donetask进来了,doneTaskDto:{}", JacksonUtil.parseJson(doneTaskDto));

        BasicSchool basicSchool = AuthThirdUtil.hasPermission();
        //发送广药流程
        if (Objects.nonNull(doneTaskDto)) {
            this.sendFlowDataMq(basicSchool.getId(), String.valueOf(doneTaskDto.getFlowId()));
            FlowMqCacheUtil.setSchoolId(doneTaskDto.getFlowId(), String.valueOf(basicSchool.getId()));
            FlowMqCacheUtil.setDoneTask(doneTaskDto.getFlowId(), doneTaskDto);
        }
        return ResultUtil.ok(true);
    }

    /**
     * 发送广药流程
     *
     * @param schoolId
     * @param flowId
     * @return
     * @throws IOException
     */
    private String sendFlowDataMq(Long schoolId, String flowId) throws IOException {
        String result = null;
        Map<String, SimpleObject> mapSetting = commonCacheService.getSysSetting(schoolId);
        if (!CollectionUtils.isEmpty(mapSetting)) {
            SimpleObject simpleObjectAppId = mapSetting.get(SystemConstant.GDPU_APP_ID_PARAM);
            Objects.requireNonNull(simpleObjectAppId, "未配置学校appId");

            SimpleObject simpleObjectAppSecret = mapSetting.get(SystemConstant.GDPU_APP_SECRET_PARAM);
            Objects.requireNonNull(simpleObjectAppSecret, "未配置学校secret");

            SimpleObject simpleObjectSysAppId = mapSetting.get(SystemConstant.GDPU_SYS_APP_ID_PARAM);
            Objects.requireNonNull(simpleObjectSysAppId, "未配置学校sysAppid");

            SimpleObject simpleObjectServiceAddress = mapSetting.get(SystemConstant.GDPU_SERVICE_ADDRESS_PARAM);
            Objects.requireNonNull(simpleObjectServiceAddress, "未配置学校服务中台地址");

            String appId = simpleObjectAppId.getValue();
            String secret = simpleObjectAppSecret.getValue();
            String sysAppId = simpleObjectSysAppId.getValue();
            String serviceAddress = simpleObjectServiceAddress.getValue();

            Map<String, Object> params = new LinkedHashMap<>();
            params.put(SystemConstant.GDPU_DOCUN_ID, sysAppId + flowId);
            params.put(SystemConstant.GDPU_SYS_APP_ID, sysAppId);
            String dateStr = new SimpleDateFormat(SystemConstant.DEFAULT_DATE).format(new Date());
            String encryptedvalue = DigestUtils.md5Hex(appId + secret + dateStr).toUpperCase();

            //更新流程事件
            result = HttpUtil.postGdpu(serviceAddress, params, appId, encryptedvalue, System.currentTimeMillis());
            log.info("result:{}", result);
        }
        return result;
    }
}