package com.yeejoin.amos.boot.module.jyjc.biz.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapBuilder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.netflix.loadbalancer.RetryRule;
import com.yeejoin.amos.boot.biz.common.bo.CompanyBo;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.dto.AttachmentDto;
import com.yeejoin.amos.boot.module.jyjc.api.common.CommonConstants;
import com.yeejoin.amos.boot.module.jyjc.api.entity.JyjcOpeningApplication;
import com.yeejoin.amos.boot.module.jyjc.api.enums.FlowStatusEnum;
import com.yeejoin.amos.boot.module.jyjc.api.mapper.JyjcBaseMapper;
import com.yeejoin.amos.boot.module.jyjc.api.mapper.JyjcOpeningApplicationMapper;
import com.yeejoin.amos.boot.module.jyjc.api.model.JyjcOpeningApplicationRequstDto;
import com.yeejoin.amos.boot.module.jyjc.api.service.IJyjcOpeningApplicationService;
import com.yeejoin.amos.boot.module.jyjc.api.model.JyjcOpeningApplicationModel;
import com.yeejoin.amos.boot.module.jyjc.biz.config.BaseException;
import com.yeejoin.amos.boot.module.jyjc.biz.feign.WorkflowFeignClient;
import com.yeejoin.amos.boot.module.ymt.api.dto.TzBaseUnitLicenceDto;
import com.yeejoin.amos.boot.module.ymt.api.dto.TzsUserInfoDto;
import com.yeejoin.amos.boot.module.ymt.api.entity.TzBaseEnterpriseInfo;
import com.yeejoin.amos.boot.module.ymt.api.entity.TzsUserInfo;
import com.yeejoin.amos.boot.module.ymt.api.enums.ApplicationFormTypeEnum;
import com.yeejoin.amos.boot.module.ymt.api.mapper.TzBaseEnterpriseInfoMapper;
import com.yeejoin.amos.boot.module.ymt.api.mapper.TzBaseUnitLicenceMapper;
import com.yeejoin.amos.boot.module.ymt.api.mapper.TzsUserInfoMapper;
import com.yeejoin.amos.boot.module.ymt.api.service.ICreateCodeService;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.workflow.Workflow;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowStartDTO;
import com.yeejoin.amos.feign.workflow.model.AjaxResult;
import com.yeejoin.amos.feign.workflow.model.TaskResultDTO;
import org.apache.commons.lang3.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.expression.Ids;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 服务实现类
 *
 * @author system_generator
 * @date 2023-12-13
 */
@Service
@Slf4j
public class JyjcOpeningApplicationServiceImpl extends BaseService<JyjcOpeningApplicationModel, JyjcOpeningApplication, JyjcOpeningApplicationMapper> implements IJyjcOpeningApplicationService {

    @Autowired
    CommonserviceImpl commonserviceImpl;
    @Autowired
    private ICreateCodeService createCodeService;
    @Autowired
    JyjcOpeningApplicationMapper jyjcOpeningApplicationMapper;

    @Resource(type = JyjcBaseMapper.class)
    private JyjcBaseMapper baseMapper;

    @Value("${process-definition-key.jyjc.openapplication:}")
    private String processDefinitionKey;

    @Value("${jyjc.user-post:6615}")
    private String jyjcUserPost;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private TzBaseUnitLicenceMapper unitLicenceMapper;
    @Autowired
    private TzBaseEnterpriseInfoMapper enterpriseInfoMapper;
    @Autowired
    private TzsUserInfoMapper userInfoMapper;

    @Autowired
    private WorkflowFeignClient workflowFeignClient;

    @Transactional(rollbackFor = {Exception.class, BaseException.class})
    public JyjcOpeningApplicationModel saveOrUpdateModel(JyjcOpeningApplicationModel model, Boolean enableStartFlow) {
        boolean isUpdate = false;
        String instanceId = null;
        try {
            if (model.getSequenceNbr() != null) {
                JyjcOpeningApplication entity = jyjcOpeningApplicationMapper.selectById(model.getSequenceNbr());
                if (entity != null) {
                    instanceId = entity.getWorkflowProstanceId();
                    isUpdate = true;
                }
            }
            if (enableStartFlow) {
                if (StringUtils.isBlank(instanceId)) {
                    // 未开启过工作流则进行开启 startProcess
                    instanceId = startFlow("1");
                }
                JSONObject dataObject = getTask(instanceId);
                JSONArray executorArray = dataObject.getJSONObject("nodeInfo").getJSONArray("executor");
                if (!ValidationUtil.isEmpty(executorArray)) {
                    String roleGroups = executorArray.stream().map(json -> Optional.ofNullable(((LinkedHashMap) json).get("groupId")).orElse("").toString()).collect(Collectors.joining(","));
                    model.setWorkflowRole(roleGroups);
                }
                model.setStatus(FlowStatusEnum.SUBMITTED.getCode() + "");
                model.setStatusName(FlowStatusEnum.SUBMITTED.getName());
                model.setApplyTime(new Date());
                model.setWorkflowActiveKey(dataObject.getString("taskDefinitionKey"));
                model.setWorkflowProstanceId(instanceId);
                // 默认自动执行第一步
                execueFlow(MapBuilder.<String, Object>create().put("op", "0").put("instanceId", instanceId).put("comments", "").build());
            } else {
                model.setStatus(FlowStatusEnum.TO_BE_SUBMITTED.getCode() + "");
                model.setStatusName(FlowStatusEnum.TO_BE_SUBMITTED.getName());
            }
            if (!isUpdate) {
                CompanyBo companyBo = commonserviceImpl.getReginParamsOfCurrentUser().getCompany();
                model.setUnitCode(companyBo.getCompanyCode());
                model.setUnitCodeName(companyBo.getCompanyName());
                List<String> codes = createCodeService.createApplicationFormCode(ApplicationFormTypeEnum.JY.getCode(), 1);
                model.setApplicationSeq(codes.get(0));
                return this.createWithModel(model);
            } else {
                return this.updateWithModel(model);
            }
        } catch (Exception e) {
            log.error("saveModel: model={} error", model, e);
            throw new BaseException(e.getMessage());
        }
    }

    @Transactional(rollbackFor = {Exception.class, BaseException.class})
    public JyjcOpeningApplicationModel resubmit(JyjcOpeningApplicationModel model) {
        model.setStatus(FlowStatusEnum.SUBMITTED.getCode() + "");
        model.setStatusName(FlowStatusEnum.SUBMITTED.getName());
        model = this.updateWithModel(model);
        execueFlow(MapBuilder.<String, Object>create().put("op", "0").put("instanceId", model.getWorkflowProstanceId()).put("comments", "").build());
        return model;
    }

    public void updateModelByInstanceId(String instanceId, String status) {
        JyjcOpeningApplication entity = this.lambdaQuery().eq(JyjcOpeningApplication::getWorkflowProstanceId, instanceId).one();
        if (entity == null) {
            return;
        }
        JSONObject taskJson = getTask(instanceId);
        if (taskJson == null) {
            log.warn("流程=>{}查询不到或已结束", instanceId);
            return;
        }
        entity.setWorkflowRole(getWorkflowRoleGroups(taskJson));
        // entity.setStatus(getWorkflowStatus(taskJson));
        entity.setWorkflowActiveKey(taskJson.getString("taskDefinitionKey"));
        entity.setStatus(status);
        entity.setStatusName(FlowStatusEnum.getNameByType(Long.parseLong(status)));
        this.updateById(entity);
    }


    /**
     * 分页查询
     */

    public Page<JyjcOpeningApplicationModel> queryForJyjcOpeningApplicationPage(Page<JyjcOpeningApplicationModel> page) {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询 示例
     */
    public List<JyjcOpeningApplicationModel> queryForJyjcOpeningApplicationList() {
        return this.queryForList("", false);
    }

    public Page<JyjcOpeningApplicationModel> queryForJyjcOpeningApplicationPage(Page<JyjcOpeningApplication> page, JyjcOpeningApplicationRequstDto jyjcOpeningApplicationRequstDto) {
        String applyStartTime = "";
        String applyEndTime = "";
        if (ObjectUtils.isNotEmpty(jyjcOpeningApplicationRequstDto.getApplyTime())) {
            String date = jyjcOpeningApplicationRequstDto.getApplyTime();
            applyStartTime = date + " 00:00:00";
            applyEndTime = date + " 23:59:59";
        }
        return jyjcOpeningApplicationMapper.selectJyjcOpeningApplicationList(page, jyjcOpeningApplicationRequstDto, applyStartTime, applyEndTime);
    }

    public Page<JyjcOpeningApplicationModel> querypageForCompany(Page<JyjcOpeningApplication> page, JyjcOpeningApplicationRequstDto jyjcOpeningApplicationRequstDto) {
        //根据申请单中的单位信息对于列表数据进行过滤
        CompanyBo companyBo = commonserviceImpl.getReginParamsOfCurrentUser().getCompany();
//        if (companyBo.getLevel().equals("company")) {
            jyjcOpeningApplicationRequstDto.setUnitCode(companyBo.getCompanyCode());
//        }

        String applyStartTime = "";
        String applyEndTime = "";
        if (ObjectUtils.isNotEmpty(jyjcOpeningApplicationRequstDto.getApplyTime())) {
            String date = jyjcOpeningApplicationRequstDto.getApplyTime();
            applyStartTime = date + " 00:00:00";
            applyEndTime = date + " 23:59:59";
        }
        return jyjcOpeningApplicationMapper.selectJyjcOpeningApplicationList(page, jyjcOpeningApplicationRequstDto, applyStartTime, applyEndTime);
    }


    /**
     * 获取详情跳转
     *
     * @param
     * @return {@link }
     * @throws
     * @author yangyang
     */
    public JyjcOpeningApplicationModel queryDetail(Long sequenceNbr) {
        ReginParams reginParams = commonserviceImpl.getReginParamsOfCurrentUser();
        if (ValidationUtil.isEmpty(reginParams.getCompany())) {
            throw new RuntimeException("未指定人员归属单位信息");
        }
        String unitCode;
        JyjcOpeningApplicationModel jyjcOpeningApplicationModel;
        if (null != sequenceNbr) {
            jyjcOpeningApplicationModel = this.queryBySeq(sequenceNbr);
            unitCode = jyjcOpeningApplicationModel.getUnitCode();
        } else {
            jyjcOpeningApplicationModel = new JyjcOpeningApplicationModel();
            unitCode = reginParams.getCompany().getCompanyCode();
        }
        // unitCode = "91611103MAC4Q1EG7B"; // 测试用，之后务必删除！！！
        QueryWrapper enterpriseInfoQueryWrapper = new QueryWrapper<>();
        enterpriseInfoQueryWrapper.eq("use_code", unitCode);
        TzBaseEnterpriseInfo baseUnitLicenceEntity = enterpriseInfoMapper.selectOne(enterpriseInfoQueryWrapper);
        // 获取企业资质
        if (baseUnitLicenceEntity != null) {
            jyjcOpeningApplicationModel.setUseContact(baseUnitLicenceEntity.getUseContact());
            jyjcOpeningApplicationModel.setContactPhone(baseUnitLicenceEntity.getContactPhone());
            if (StringUtils.isNotBlank(baseUnitLicenceEntity.getIndustrySupervisor())) {
                List<Map<String, String>> dicts = baseMapper.selectDataDictionaryList(Arrays.asList(baseUnitLicenceEntity.getIndustrySupervisor()));
                if (!ValidationUtil.isEmpty(dicts)) {
                    jyjcOpeningApplicationModel.setIndustrySupervisor(dicts.get(0).get("name"));
                } else {
                    jyjcOpeningApplicationModel.setIndustrySupervisor(baseUnitLicenceEntity.getIndustrySupervisor());
                }
            }
            jyjcOpeningApplicationModel.setLongitude(baseUnitLicenceEntity.getLongitude());
            jyjcOpeningApplicationModel.setLatitude(baseUnitLicenceEntity.getLatitude());
            if (ObjectUtils.isNotEmpty(baseUnitLicenceEntity.getUnitBusinessLicense())) {
                jyjcOpeningApplicationModel.setUnitBusinessLicense(JSONArray.parseArray(baseUnitLicenceEntity.getUnitBusinessLicense(), AttachmentDto.class));
            }
        }
        // QueryWrapper unitLicenceQueryWrapper = new QueryWrapper<>();
        // unitLicenceQueryWrapper.eq("unit_code", unitCode);
        // unitLicenceQueryWrapper.eq("licence_type", LicenceTypeEnum.JYJC.getCode());
        // List<TzBaseUnitLicenceDto> baseUnitLicences = Bean.toModels(unitLicenceMapper.selectList(unitLicenceQueryWrapper), TzBaseUnitLicenceDto.class );
        //
        List<TzBaseUnitLicenceDto> baseUnitLicences = baseMapper.selectBaseUnitLicenceList(MapBuilder.<String, Object>create().put("unitCode", unitCode).put("licenceType", "jyjc").build());
        jyjcOpeningApplicationModel.setBaseUnitLicences(baseUnitLicences);
        // 获取检验人员信息
        QueryWrapper userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("unit_code", unitCode);
        List<TzsUserInfo> userInfos = userInfoMapper.selectList(userInfoQueryWrapper);
        if (!ValidationUtil.isEmpty(userInfos)) {
            // List<String> codes = userInfos.stream()
            //                            .map(o -> o.getPost() != null ? JSON.parseArray(o.getPost(), String.class) : null)
            //                            .filter(Objects::nonNull)
            //                            .collect(Collectors.toList())
            //                            .stream().flatMap(o -> o.stream()).distinct().collect(Collectors.toList());
            // List<Map<String, String>> dicts = baseMapper.selectDataDictionaryList(codes);
            List<TzsUserInfoDto> userInfoDtos = userInfos.stream().map(o -> {
                TzsUserInfoDto dto = new TzsUserInfoDto();
                Bean.toModel(o, dto);
                // 字段不要了
                // if (o.getPost() != null) {
                //    List<String> temps = JSON.parseArray(o.getPost(), String.class);
                //    String postName = temps.stream().map(m -> dicts.stream().filter(dict -> dict.get("code").equals(m)).findFirst().map(n -> n.get("name")).orElse("")).collect(Collectors.joining(","));
                //    dto.setPostName(postName);
                // }
                return dto;
            }).filter(o -> o.getPost() != null && o.getPost().contains(jyjcUserPost)).collect(Collectors.toList());
            jyjcOpeningApplicationModel.setUserInfos(userInfoDtos);
        }
        return jyjcOpeningApplicationModel;
    }

    public String startFlow(String businessKey) throws Exception {
        // 重新开启工作流
        ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
        dto.setProcessDefinitionKey(processDefinitionKey);
        dto.setBusinessKey(StringUtils.defaultString(businessKey, "1"));
        // dto.setCompleteFirstTask(true);
        // FeignClientResult ajaxResult = Workflow.taskV2Client.startByVariable(dto);
        //
        // if (log.isDebugEnabled()) {
        //     log.debug("开启工作流结果：{}", ajaxResult);
        // }
        // if (ajaxResult == null || 200 != ajaxResult.getStatus()) {
        //     throw new BaseException("开启工作流错误");
        // }
        // return ((Map) ajaxResult.getResult()).get("id").toString();
        // V1
        AjaxResult ajaxResult = Workflow.taskClient.startByVariable(dto);
        if (log.isDebugEnabled()) {
            log.debug("开启工作流结果：{}", ajaxResult);
        }
        if (ajaxResult == null || (ajaxResult.get(AjaxResult.CODE_TAG) != null && !"200".equals(ajaxResult.get(AjaxResult.CODE_TAG).toString()))) {
            throw new BaseException("开启工作流错误");
        }
        return ((Map) ajaxResult.get("data")).get("id").toString();
    }

    /**
     * 接收/驳回通知检验单
     */
    public void execueFlow(Map<String, Object> params) {
        String op = params.get("op").toString();
        String instanceId = params.get("instanceId").toString();
        String comments = params.get("comments").toString();
        try {
            AjaxResult ajaxResult = Workflow.taskClient.getTask(instanceId);
            JSONObject dataObject = JSON.parseObject(JSON.toJSONString(ajaxResult.get("data")));
            String taskId = dataObject.getString("id");
            //组装信息
            TaskResultDTO dto = new TaskResultDTO();
//            dto.setResult(op);
            dto.setResultCode("approvalStatus");
            dto.setTaskId(taskId);
            HashMap<String, Object> varibalble = new HashMap<>();
            varibalble.put("approvalStatus", op);
            dto.setVariable(varibalble);
            dto.setComment(comments);
            //执行流程
            AjaxResult ajaxResult1 = Workflow.taskClient.completeByTask(taskId, dto);
            if (ObjectUtils.isEmpty(ajaxResult1)) {

            }
            if (op.equals("0")) {
                String originalDataId = params.get("originalDataId").toString();
                JyjcOpeningApplication jyjcOpeningApplication = jyjcOpeningApplicationMapper.selectById(originalDataId);
                List<String> detectionRegion = (List<String>) params.get("detectionRegion");
//                String detectionRegionName =  params.get("detectionRegionName").toString();
                if(!detectionRegion.isEmpty()){
                    jyjcOpeningApplication.setDetectionRegion(detectionRegion);
                }
//                jyjcOpeningApplication.setDetectionRegionName(detectionRegionName);
                if(ObjectUtils.isEmpty(jyjcOpeningApplication.getAcceptDate())){
                    jyjcOpeningApplication.setAcceptDate(new Date());
                }
                jyjcOpeningApplicationMapper.updateById(jyjcOpeningApplication);
            }

            updateModelByInstanceId(instanceId, "0".equals(op) ? FlowStatusEnum.HAVE_PROCESSED.getCode() + "" : FlowStatusEnum.REJECTED.getCode() + "");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 撤回流程办理单
     */
    public JSONObject stopFlow(String sequenceNbr) {
        JSONObject jsonObject= new JSONObject();
        JyjcOpeningApplication jyjcOpeningApplication = jyjcOpeningApplicationMapper.selectById(sequenceNbr);
        try {
            //撤回流程
             jsonObject = workflowFeignClient.rollBack(jyjcOpeningApplication.getWorkflowProstanceId());
            if (ObjectUtils.isEmpty(jsonObject)) {

            }
            updateModelByInstanceId(jyjcOpeningApplication.getWorkflowProstanceId(), FlowStatusEnum.ROLLBACK.getCode() + "");
        } catch (Exception e) {
            throw  new BadRequest("撤回流程失败，请联系管理员！");
        }
        return jsonObject;
    }

    private String getWorkflowStatus(JSONObject dataObject) {
        return !ValidationUtil.isEmpty(dataObject) && !ValidationUtil.isEmpty(dataObject.get("status")) ? String.valueOf(dataObject.get("status")) : "";
    }

    private String getWorkflowRoleGroups(JSONObject dataObject) {
        JSONArray executorArray = dataObject.getJSONObject("nodeInfo").getJSONArray("executor");
        if (!ValidationUtil.isEmpty(executorArray)) {
            return executorArray.stream().map(json -> Optional.ofNullable(((LinkedHashMap) json).get("groupId")).orElse("").toString()).collect(Collectors.joining(","));
        }
        return null;
    }

    private JSONObject getTask(String instanceId) {
        AjaxResult ajaxResult = Workflow.taskClient.getTaskNoAuth(instanceId);
        JSONObject dataObject = JSON.parseObject(JSON.toJSONString(ajaxResult.get("data")));
        String taskId = dataObject.getString("id");// 工作流ID
        FeignClientResult<JSONObject> nodeInfo = workflowFeignClient.getNodeInfotoken(RequestContext.getAppKey(), RequestContext.getProduct(), RequestContext.getToken(), taskId);
        dataObject.put("nodeInfo", nodeInfo.getResult());
        return dataObject;
    }

    public List<Map<String, Object>> selectForFlowStatusList() {
        return Arrays.stream(FlowStatusEnum.values()).map(this::mapPointTypeToMap).collect(Collectors.toList());
    }

    private Map<String, Object> mapPointTypeToMap(FlowStatusEnum e) {
        Map<String, Object> record = new HashMap<>();
        record.put("key", e.getCode());
        record.put("label", e.getName());
        return record;
    }

    public Boolean deleteBatchByIds(List<Long> ids){
        List<JyjcOpeningApplication> jyjcOpeningApplicationList=jyjcOpeningApplicationMapper.selectList(new QueryWrapper<JyjcOpeningApplication>()
                .in("sequence_nbr"));
        List<String> status = Arrays.asList(String.valueOf(FlowStatusEnum.ROLLBACK.getCode()),String.valueOf(FlowStatusEnum.REJECTED.getCode()));
        jyjcOpeningApplicationList = jyjcOpeningApplicationList.stream().filter(jyjcOpeningApplication ->!status.contains(jyjcOpeningApplication.getStatus())).collect(Collectors.toList());
        if(jyjcOpeningApplicationList.isEmpty()){
            throw new BadRequest("除撤回跟驳回的流程之外其余流程不可删除，请核对数据后重新提交！");
        }
        deleteBatchByIds(ids);
        return true;
    }

    public List<TzBaseEnterpriseInfo> getInspectionUnitList() {
        List<TzBaseEnterpriseInfo> tzBaseEnterpriseInfos = enterpriseInfoMapper.getInspectionUnitList(CommonserviceImpl.UNIT_TYPE);
        if (ValidationUtil.isEmpty(tzBaseEnterpriseInfos)) {
            return Collections.EMPTY_LIST;
        }
        List<String> unitCodes = this.lambdaQuery().select(JyjcOpeningApplication::getUnitCode).list().stream().map(JyjcOpeningApplication::getUnitCode).collect(Collectors.toList());
        // 根据开通机构过滤
        return tzBaseEnterpriseInfos.stream().filter(o -> StringUtils.isNotBlank(o.getUseCode()) && unitCodes.contains(o.getUseCode())).collect(Collectors.toList());
    }
}