package com.mortals.xhx.module.yth.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.javafaker.Faker;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.xhx.base.framework.config.InterceptorConfig;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.busiz.question.DatumInfo;
import com.mortals.xhx.busiz.uploadfile.MatterReq;
import com.mortals.xhx.busiz.uploadfile.SubmitDatumReq;
import com.mortals.xhx.common.code.ApproveStateEnum;
import com.mortals.xhx.common.code.MannerEnum;
import com.mortals.xhx.common.code.OneThingTypeEnum;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.keys.BusizParams;
import com.mortals.xhx.feign.flowable.IApiFlowInstanceFeign;
import com.mortals.xhx.feign.rsp.ApiResp;
import com.mortals.xhx.feign.runtime.StartProcessInstanceReq;
import com.mortals.xhx.module.matter.service.MatterDatumService;
import com.mortals.xhx.module.matter.service.MatterService;
import com.mortals.xhx.module.member.model.MemberEntity;
import com.mortals.xhx.module.member.model.MemberQuery;
import com.mortals.xhx.module.member.service.MemberService;
import com.mortals.xhx.module.one.model.OneClassifyEntity;
import com.mortals.xhx.module.one.model.OneClassifyTopicalEntity;
import com.mortals.xhx.module.one.service.OneClassifyService;
import com.mortals.xhx.module.one.service.OneClassifyTopicalService;
import com.mortals.xhx.module.yth.dao.YthOnethingDao;
import com.mortals.xhx.module.yth.model.*;
import com.mortals.xhx.module.yth.service.YthOnethingDetailService;
import com.mortals.xhx.module.yth.service.YthOnethingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>Title: 一件事提交基础表</p>
 * <p>Description: YthOnethingService service接口 </p>
 * <p>Copyright: Copyright &reg;  </p>
 *
 * @version 1.0.0
 */
@Service("ythOnethingService")
public class YthOnethingServiceImpl extends AbstractCRUDServiceImpl<YthOnethingDao, YthOnethingEntity, Long> implements YthOnethingService {


    @Autowired
    private MemberService memberService;

    @Autowired
    private ParamService paramService;
    @Autowired
    private InterceptorConfig config;
    @Autowired
    private YthOnethingDetailService ythOnethingDetailService;
    @Autowired
    private IApiFlowInstanceFeign apiFlowInstanceFeign;
    @Autowired
    private OneClassifyTopicalService oneClassifyTopicalService;
    @Autowired
    private OneClassifyService oneClassifyService;
    @Autowired
    private MatterService matterService;
    @Autowired
    private MatterDatumService matterDatumService;

    @Override
    public void datumUploadAndStartFlow(SubmitDatumReq req) {
        try {
            //保存一件事
            YthOnethingEntity entity = new YthOnethingEntity();
            MemberEntity memberEntity = memberService.selectOne(new MemberQuery().openId(req.getOpenId()));
            if (ObjectUtils.isEmpty(memberEntity)) {
                throw new AppException(String.format("未找到当前openId:%s 对应的用户", req.getOpenId()));
            }
            entity.setMemberId(memberEntity.getId());
            entity.setOpenId(req.getOpenId());
            entity.setManner(MannerEnum.SELF.getValue());
            entity.setSiteid(req.getSiteId().intValue());
            entity.setIsAgent(req.getIsAgent());
            entity.setIsRevoke(YesNoEnum.NO.getValue());
            entity.setClassifyTopicId(req.getClassifyTopicId());

            Faker faker = new Faker(Locale.CHINESE);

            entity.setAddress(faker.address().fullAddress());
            entity.setLinkman(faker.name().name());
            entity.setPhone(138);
            entity.setGetnum(faker.number().digits(12));
            entity.setNumber(faker.idNumber().validSvSeSsn());

            entity.setStatus(ApproveStateEnum.UN_AUDIT.getValue());
            entity.setCreateUser("system");
            entity.setCreateTime(new Date());
            YthOnethingEntity save = this.save(entity);


            List<YthOnethingDetailEntity> detailList = req.getMatterReqList().stream().flatMap(item -> {
                return item.getAttachmentList().stream().map(m1 -> {
                    YthOnethingDetailEntity detailEntity = new YthOnethingDetailEntity();
                    detailEntity.setMatterId(item.getMatterid());
                    detailEntity.setOneThingId(save.getId());
                    detailEntity.setDatumId(m1.getDatumId());
                    detailEntity.setFileName(m1.getFileName());
                    detailEntity.setFilepath(m1.getFilepath());
                    detailEntity.setCreateTime(new Date());
                    detailEntity.setCreateUser("system");

                    return detailEntity;
                });
            }).collect(Collectors.toList());

            ythOnethingDetailService.save(detailList);


            //获取流程定义key 发起流程 当前通过param参数固定获取
            String oneThingKey = paramService.getValueByKey(BusizParams.SYS_PARAM_FLOW_KEY);
            //通过流程key获取基础提交参数
            String vars = paramService.getValueByKey(oneThingKey);

            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> variables = mapper.readValue(vars, Map.class);
            StartProcessInstanceReq startProcessInstanceReq = new StartProcessInstanceReq();
            startProcessInstanceReq.setProcessDefinitionKey(oneThingKey);
            startProcessInstanceReq.setBusinessKey(entity.getId().toString());
            startProcessInstanceReq.setFormName("一件事一次办");
            startProcessInstanceReq.setUserCode(entity.getMemberId().toString());
            startProcessInstanceReq.setPlatformSn(config.getTenantId());
            startProcessInstanceReq.setVariables(variables);

            ApiResp<String> resp = apiFlowInstanceFeign.processStart(startProcessInstanceReq);
            entity.setProcessInstanceId(resp.getData());
            entity.setStatus(ApproveStateEnum.AUDITING.getValue());

            this.update(entity);
        } catch (Exception e) {
            throw new AppException("创建用户资料，发起流程异常:" + e.getMessage());

        }

    }

    @Override
    public BusinessInfo getBusinessDetail(Long id) {
        YthOnethingEntity ythOnethingEntity = this.get(id);
        if (ObjectUtils.isEmpty(ythOnethingEntity)) {
            throw new AppException("未找到相关业务！");
        }

        OneClassifyTopicalEntity classifyTopicalEntity = oneClassifyTopicalService.get(ythOnethingEntity.getClassifyTopicId());

        OneClassifyEntity oneClassifyEntity = oneClassifyService.get(classifyTopicalEntity.getClassifyId());

        //组装展示数据
        BusinessInfo businessInfo = new BusinessInfo();
        businessInfo.setOneThingName(oneClassifyEntity.getClassifyName());
        businessInfo.setOneThingDesc(oneClassifyEntity.getSortRemarks());

        //查询提交的附件信息及事项名称
        YthOnethingDetailQuery query = new YthOnethingDetailQuery().oneThingId(ythOnethingEntity.getId());

        Map<String, List<MatterDatumInfo>> collect = ythOnethingDetailService.find(query).stream().map(item -> {
            MatterDatumInfo matterDatumInfo = new MatterDatumInfo();
            matterDatumInfo.setDatumId(item.getDatumId());
            matterDatumInfo.setDatumName(matterDatumService.get(item.getDatumId()).getMaterialName());
            matterDatumInfo.setMatterId(item.getMatterId());
            matterDatumInfo.setMatterName(matterService.getCache(item.getMatterId().toString()).getMatterName());
            matterDatumInfo.setFileName(item.getFileName());
            matterDatumInfo.setFilePath(item.getFilepath());
            return matterDatumInfo;
        }).collect(Collectors.groupingBy(m -> m.getMatterName()));

        businessInfo.setMatterGroup(collect);

        return businessInfo;
    }
}