package com.mortals.xhx.modules.information.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.xhx.common.code.NodeTypeEnum;
import com.mortals.xhx.common.utils.DateByAffairUtils;
import com.mortals.xhx.modules.arameter.model.ArameterEntity;
import com.mortals.xhx.modules.arameter.service.ArameterService;
import com.mortals.xhx.modules.implementlist.dao.RybMatterDao;
import com.mortals.xhx.modules.implementlist.dao.RybWorkDao;
import com.mortals.xhx.modules.implementlist.model.RybMatterListEntry;
import com.mortals.xhx.modules.implementlist.model.RybWorkEntry;
import com.mortals.xhx.modules.information.model.InformationEntity;
import com.mortals.xhx.modules.information.service.InformationService;
import com.mortals.xhx.modules.service.QueryInformationServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @author shenxin
 * @Date: 2021/11/17-16:28
 * @Description:办件数据推送蓉易办(申请并受理)
 */
@Slf4j
@Component("rybApplyAndAcceptInformationTaskImpl")
public class RybApplyAndAcceptInformationTaskImpl implements ITaskExcuteService {

    @Autowired
    private InformationService informationService;

    @Autowired
    private QueryInformationServiceImpl queryInformationService;

    @Autowired
    private ArameterService arameterService;

    @Resource
    private RybWorkDao rybWorkDao;

    @Resource
    private RybMatterDao rybMatterDao;

    @Override
    public void excuteTask(ITask task) throws AppException {
        //1.查询上月的表是否存在未推送的数据
        List<InformationEntity> informationEntities =
                queryInformationService.queryDataThatHasNotBeenPushed(NodeTypeEnum.蓉易办受理.getCode(), "1", "0", task.getExcuteParam());
        //组装申请并受理数据推送一体化平台
        this.applyAndAccept(informationEntities);
    }

    private void applyAndAccept(List<InformationEntity> informationEntities) {
        log.info("开始推送申请并受理数据");
        if(CollectionUtils.isEmpty(informationEntities)){
            log.info("没有需要推送申请并受理数据");
            return;
        }
        List<InformationEntity> entities = informationEntities.parallelStream().map(e -> {
            ArameterEntity extCache = new ArameterEntity();
            extCache.setSysCode(e.getSystemCode());
            extCache = arameterService.find(extCache).get(0);
            //组装参数
            HashMap<String, Object> stringObjectHashMap = assemblyParameters(e);
            if(stringObjectHashMap == null){
                log.info("推送失败，没有该办件所对应的事项部门编码！");
                e.setFailReason("推送失败，没有该办件所对应的事项部门编码！");
                e.setIsReport("1");
                e.setIsSuccess("0");
                return e;
            }
            Map<String, String> map = (Map<String, String>) stringObjectHashMap.get("params");
            e.setAcceptName(map.get("receiveusername"));
            e.setAcceptId(map.get("receiveuseridcard"));
            e.setAcceptPhone(map.get("receiveuserphone"));
            Map<String, Object> params = new HashMap<>();
            params.put("jsonData", JSONObject.toJSONString(stringObjectHashMap));
            HttpRequest key = HttpUtil.createPost(extCache.getDecideAdress())//蓉易办
                    .header("AppKey", extCache.getSysCode())
                    .header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8").form(params);
            HttpResponse appKey = key.execute().charset("utf-8");
            JSONObject jsonObject = JSONObject.parseObject(appKey.body());
            log.info("响应：" + jsonObject);
            JSONObject data = JSONObject.parseObject(jsonObject.getString("data"));
            if ("200".equals(jsonObject.getString("code")) && "1".equals(data.getJSONObject("custom").getString("code"))) {
                log.info("推送成功");
                e.setIsReport("1");
                e.setIsSuccess("1");
                e.setBizStatus(NodeTypeEnum.蓉易办环节.getDesc());
                e.setNodeType(NodeTypeEnum.蓉易办环节.getCode());
                //默认区间3~20分钟
                e.setCreateTime(DateByAffairUtils.getTimeByAddRandomDouble(DateTime.now(), null, null));
                e.setOfficeCode(data.getJSONObject("custom").getJSONObject("content").getString("flowsn"));
            } else {
                log.info("推送失败:" + jsonObject);
                e.setFailReason(jsonObject.toString());
                e.setIsReport("1");
                e.setIsSuccess("0");
            }
            e.setProcessStatusName(NodeTypeEnum.蓉易办受理.getValue());
            return e;
        }).collect(Collectors.toList());
        log.info("申请受理推送完成");
        informationService.update(entities, null);
    }

    private HashMap<String, Object> assemblyParameters(InformationEntity e) {
        HashMap<String, Object> dataMap = new HashMap<>(16);
        dataMap.put("token", "Epoint_WebSerivce_**##0601");
        HashMap<String, Object> baseInfoMap = new HashMap<>(16);
        baseInfoMap.put("projectname", e.getEventName());
        baseInfoMap.put("applyway", "20");
        if (e.getApplicantAttributes() == 2) {
            baseInfoMap.put("applyertype", "20");
        } else {
            baseInfoMap.put("applyertype", "10");
            baseInfoMap.put("legal", e.getLegalPerson());
            baseInfoMap.put("legalpersoncardtype", "");
            baseInfoMap.put("legalpersonidcard", "");
        }
        baseInfoMap.put("applyername", e.getApplicantName());
        baseInfoMap.put("applyersex", e.getApplicantSex());
        baseInfoMap.put("certtype", "22");
        baseInfoMap.put("certnum", e.getApplicantCardNumbe());
        baseInfoMap.put("address", "地址暂无");
        baseInfoMap.put("contactmobile", e.getContactPhone());
        baseInfoMap.put("contactperson", e.getContactName());
        List<RybWorkEntry> workEntries = rybWorkDao.find(e.getDeptCode());
        if(CollectionUtils.isEmpty(workEntries)){
            return null;
        }
        baseInfoMap.putAll(randomlyExtractPersonnelInformation(workEntries));
        baseInfoMap.put("receivedate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(e.getCreateTime()));
        RybMatterListEntry entry = rybMatterDao.find(e.getEventCode()).get(0);
        if (null != entry) {
            baseInfoMap.put("tasktype", entry.getMatterType());
            baseInfoMap.put("task_id", entry.getTaskId());
        } else {
            baseInfoMap.put("tasktype", "1A");
            baseInfoMap.put("task_id", "123");
        }
        baseInfoMap.put("eventcode", entry.getMatterCode());
        baseInfoMap.put("areacode", e.getAreaCode());
        baseInfoMap.put("source", "MTEwNDEyOTc0MDAw");
        baseInfoMap.put("contactcertnum", e.getContactIdCard());
        baseInfoMap.put("contactidcard", e.getContactIdCard());
        dataMap.put("params", baseInfoMap);
        return dataMap;
    }

    private HashMap<String, String> randomlyExtractPersonnelInformation(List<RybWorkEntry> workEntries) {
        HashMap<String, String> dataMap = new HashMap<>(16);
        Random random = new Random();
        int i = random.nextInt(workEntries.size());
        dataMap.put("receiveusername", workEntries.get(i).getReceiveUserName());
        dataMap.put("receiveuseridcard", workEntries.get(i).getReceiveUserIdcard());
        dataMap.put("receiveuserphone", workEntries.get(i).getReceiveUserPhone());
        return dataMap;
    }


    @Override
    public void stopTask(ITask task) throws AppException {

    }

}
