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

import com.fasterxml.jackson.databind.ObjectMapper;
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.uploadfile.UploadDatumReq;
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.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.datum.model.DatumFileEntity;
import com.mortals.xhx.module.datum.service.DatumFileService;
import com.mortals.xhx.module.member.model.MemberQuery;
import com.mortals.xhx.module.member.service.MemberService;
import com.mortals.xhx.module.yth.dao.YthOnethingDao;
import com.mortals.xhx.module.yth.model.YthOnethingEntity;
import com.mortals.xhx.module.yth.service.YthOnethingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
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 DatumFileService datumFileService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ParamService paramService;
    @Autowired
    private InterceptorConfig config;
    @Autowired
    private IApiFlowInstanceFeign apiFlowInstanceFeign;

    @Override
    public void datumUploadAndStartFlow(UploadDatumReq req) {
        try {
            //保存一件事
            YthOnethingEntity entity = new YthOnethingEntity();
            entity.setMemberId(memberService.selectOne(new MemberQuery().openId(req.getOpen_id()), null).getId());
            entity.setOpenId(req.getOpen_id());
            entity.setMatterid(req.getMatterid());
            entity.setOptionContent(req.getOption_content());
            entity.setManner(MannerEnum.SELF.getValue());
            entity.setSiteid(req.getSiteid().intValue());

            entity.setType(OneThingTypeEnum.UNSUBMIT.getValue());
            entity.setStatus(ApproveStateEnum.UN_AUDIT.getValue());
            entity.setCreateUser("admin");
            entity.setCreateTime(new Date());
            YthOnethingEntity save = this.save(entity);


            //保存材料附件
            List<DatumFileEntity> fileList = req.getFile_arr().stream().map(item -> {
                DatumFileEntity datumFileEntity = new DatumFileEntity();
                datumFileEntity.setTid(save.getId());
                datumFileEntity.setDatumid(item.getDatumid());
                datumFileEntity.setFile(item.getFile());
                datumFileEntity.setUploadtime(new Date());
                datumFileEntity.setCreateTime(new Date());
                datumFileEntity.setCreateUser("admin");
                return datumFileEntity;
            }).collect(Collectors.toList());
            datumFileService.save(fileList);

            //获取流程定义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.getOpenId());
            startProcessInstanceReq.setPlatformSn(config.getTenantId());
            startProcessInstanceReq.setVariables(variables);

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

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

        }

    }
}