package com.chinaweal.aiccs.aiccs.punishment.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.abnormal.entity.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.service.EBaseinfoService;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.punishment.entity.EntLock;
import com.chinaweal.aiccs.aiccs.punishment.entity.Personlock;
import com.chinaweal.aiccs.aiccs.punishment.entity.Tolockentlist;
import com.chinaweal.aiccs.aiccs.punishment.entity.TsbizPunishLock;
import com.chinaweal.aiccs.aiccs.punishment.job.Task;
import com.chinaweal.aiccs.aiccs.punishment.mapper.TsbizPunishLockMapper;
import com.chinaweal.aiccs.aiccs.punishment.service.EntlockService;
import com.chinaweal.aiccs.aiccs.punishment.service.PersonlockService;
import com.chinaweal.aiccs.aiccs.punishment.service.TolockentlistService;
import com.chinaweal.aiccs.aiccs.punishment.service.TsbizPunishLockService;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.util.ConstantsUtil;
import com.chinaweal.aiccs.common.util.FlowUtil;
import com.chinaweal.aiccs.common.util.HandleWorkFlowUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.org.entity.OrgUnits;
import com.chinaweal.aiccs.org.mapper.AicorgMapper;
import com.chinaweal.aiccs.outside.api.SOAServiceApi;
import com.chinaweal.aiccs.outside.api.TfPunishmentApi;
import com.chinaweal.aiccs.outside.vo.ChangRuanResult;
import com.chinaweal.aiccs.outside.vo.Personnel;
import com.chinaweal.aiccs.outside.vo.TfPunishLock;
import com.chinaweal.aiccs.redis.RedisService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.BaseServiceImpl;
import com.dtflys.forest.http.ForestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 联合惩戒锁定业务表 服务实现类
 * </p>
 *
 * @author Lee
 * @since 2021-06-06
 */
@Slf4j
@Service
public class TsbizpunishlockServiceImpl extends BaseServiceImpl<TsbizPunishLockMapper, TsbizPunishLock> implements TsbizPunishLockService {

    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private EntlockService entlockService;
    @Autowired
    private PersonlockService personlockService;
    @Autowired
    EBaseinfoService eBaseinfoService;
    @Resource
    private SOAServiceApi soaServiceApi;
    @Autowired
    private TolockentlistService tolockentlistService;
    @Resource
    private TfPunishmentApi tfPunishmentApi;
    @Autowired
    private RedisService redisService;
    @Resource
    private AicorgMapper aicorgMapper;
    @Autowired
    private TsbizPunishLockMapper tsbizPunishLockMapper;

    @Transactional
    @Override
    public TSTaskList savePunishLockAccept(AICUser user, TSTaskList taskListModel, List<TsbizPunishLock> tsbizPunishLocks, List<Tolockentlist> tolockentlists) {
        if (StringUtils.isBlank(taskListModel.getTasklistid())) {

            for (TsbizPunishLock bizPunishLockModel : tsbizPunishLocks) {
                bizPunishLockModel.setLockuserid(user.getPrimaryKey());
                bizPunishLockModel.setLockuserunitid(user.getOrgID());
                bizPunishLockModel.setLockuserdeptid(user.getUnitID());
                bizPunishLockModel.setHandler(user.getName());//设置列入主办人
                bizPunishLockModel.setStatus("9");
                // 流程启动把状态设置为 "受理中"
                saveOrUpdate(bizPunishLockModel);
            }
            if (tolockentlists != null) { // 列表发起
                for (Tolockentlist item : tolockentlists) {
                    item.setState("1");// 更新状态为在办
                    tolockentlistService.updateById(item);
                }
            }
            String definedname = FlowUtil.PUNISHWORKFLOW;//企业经营异常名录流程模板
            //新待办 设置待办信息
            taskListModel = HandleWorkFlowUtil.createTaskList(taskListModel, user);
            //开始工作流
            taskListService.startWorkFlow(taskListModel, user, definedname);
        }
        return taskListModel;
    }

//    @Transactional
//    @Override
//    public TSTaskList savePunishLockAccept(AICUser user, TSTaskList taskListModel, List<TsbizPunishLock> tsbizPunishLocks) {
//        if (StringUtils.isBlank(taskListModel.getTasklistid())) {
//            for (TsbizPunishLock bizPunishLockModel : tsbizPunishLocks) {
//                bizPunishLockModel.setLockuserid(user.getPrimaryKey());
//                bizPunishLockModel.setLockuserunitid(user.getOrgID());
//                bizPunishLockModel.setLockuserdeptid(user.getUnitID());
//                bizPunishLockModel.setHandler(user.getName());//设置列入主办人
//                bizPunishLockModel.setStatus("9"); // 流程启动把状态设置为 "受理中"
//                saveOrUpdate(bizPunishLockModel);
//            }
//
//            String definedname = FlowUtil.PUNISHWORKFLOW;//企业经营异常名录流程模板
//            //新待办 设置待办信息
//            taskListModel = HandleWorkFlowUtil.createTaskList(taskListModel, user);
//            //开始工作流
//            taskListService.startWorkFlow(taskListModel, user, definedname);
//        }
//        return taskListModel;
//    }

    @Transactional
    @Override
    public TSTaskList savePunishLockProcess(AICUser user, TSTaskList taskListModel, List<TsbizPunishLock> tsbizPunishLocks,
                                            TSOpinion opinionModel, String nextNodeID, String[] nextPerformerids, String[] nextPerformerNames) {
        try {
            for (TsbizPunishLock bizPunishLockModel : tsbizPunishLocks) {

                //下一步为审核
                if (FlowUtil.PUNISHWORKFLOWE_HANDLEPUNISH.equals(nextNodeID)) { //审批时操作
                    bizPunishLockModel.setStatus("1"); // 审批流程中把状态设置成 "审批中"
                    saveOrUpdate(bizPunishLockModel);
                }
                //添加到 业户锁定表
                if (FlowUtil.PUNISHWORKFLOWE_ENDPUNISH.equals(nextNodeID)) {//完结时
                    if(!"9".equals(bizPunishLockModel.getPunishFrom())) {
                        EntLock entLockModel = new EntLock();
                        EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, bizPunishLockModel.getPripid()));
                        if (StringUtils.isNotBlank(eBaseinfo.getLerep())) {
                            entLockModel.setRepresentative(eBaseinfo.getLerep());
                            entLockModel.setCertype(eBaseinfo.getCertype());
                            entLockModel.setCerno(eBaseinfo.getCerno());
                        }
// 6月7日                   else {
//                        Personnel personnel = queryCerno(eBaseinfo);
//                        if(personnel != null ){
//                            entLockModel.setRepresentative(personnel.getName());
//                            entLockModel.setCertype(personnel.getCertype());
//                            entLockModel.setCerno(personnel.getCerno());
//                        }
//                    }
                        entLockModel.setLockuserid(user.getPrimaryKey());
                        entLockModel.setLockuserunitid(user.getOrgID());
                        entLockModel.setLockuserdeptid(user.getUnitID());
                        entLockModel.setDepartment(Task.PunishFromAndDepartmentMap.get(bizPunishLockModel.getPunishFrom()));
                        entLockModel.setRegorg(eBaseinfo.getRegorg());
                        entLockModel.setRepresentative(eBaseinfo.getName());
                        entLockModel.setElid(bizPunishLockModel.getLockId());
                        entLockModel.setUniscid(bizPunishLockModel.getUniscid());
                        entLockModel.setPripid(bizPunishLockModel.getPripid());
                        entLockModel.setEntname(bizPunishLockModel.getEntname());
                        entLockModel.setRegno(bizPunishLockModel.getRegno());
                        entLockModel.setLockreason(bizPunishLockModel.getLockreason());
                        entLockModel.setLockusername(bizPunishLockModel.getLockusername());
                        entLockModel.setInputdate(LocalDateTime.now());
                        entLockModel.setLaupTime(LocalDateTime.now());
                        entLockModel.setLocktype(bizPunishLockModel.getLocktype());
                        entLockModel.setLockTime(bizPunishLockModel.getLockTime());
                        entLockModel.setPunishFrom(bizPunishLockModel.getPunishFrom());
                        entLockModel.setIsdelete("0");
                        entLockModel.setLockstate("1");//锁定状态 有效
                        entLockModel.setMeasure(bizPunishLockModel.getMeasure());

                        entlockService.save(entLockModel);

                        bizPunishLockModel.setApprovaldate(LocalDate.now());//核准日期
                        bizPunishLockModel.setStatus("2"); // 9 受理中、1 审批中、2 已通过、3 不通过
                        updateById(bizPunishLockModel);

/*6月7日          Tolockentlist tolockentlist = tolockentlistService.getById(bizPunishLockModel.getTolockentlistid());
                   tolockentlist.setState("3"); //已办结
                    tolockentlistService.updateById(tolockentlist);*/
                        //推送
//                        Long start = System.currentTimeMillis();
//                        String tflockid = sendEntLock(entLockModel);
//                        log.info("推送锁定数据id：{},推送解锁数据耗时: {}ms", tflockid, System.currentTimeMillis() - start);
//                        if (StringUtils.isNotBlank(tflockid)) {
//                            entLockModel.setTflockid(tflockid);
//                            entlockService.updateById(entLockModel);
//                        } else {
//                            throw new BusinessException("推送锁定数据失败");
//                        }
                    }
                    if(!"3".equals(bizPunishLockModel.getPunishFrom())){
                        Personlock personlock=new Personlock();
                        EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, bizPunishLockModel.getPripid()));
                        if (StringUtils.isNotBlank(eBaseinfo.getLerep())) {
                            personlock.setPername(eBaseinfo.getLerep());
                            personlock.setIdcardno(eBaseinfo.getCerno());
                            personlock.setPlid(bizPunishLockModel.getLockId());
                            personlock.setEntname(eBaseinfo.getEntname());
                            personlock.setRegno(eBaseinfo.getRegno());
                            personlock.setLockreason(bizPunishLockModel.getLockreason());
                            personlock.setLockstartdate(LocalDateTime.now());
                            personlock.setInputdate(LocalDateTime.now());
                            personlock.setLockusername(user.getName());
                            personlock.setLockuserid(user.getPrimaryKey());
                            personlock.setLockuserunitid(user.getOrgID());
                            personlock.setLockuserdeptid(user.getUnitID());
                            personlock.setLockstate("1");
                            personlock.setInputdate(LocalDateTime.now());
                            personlockService.save(personlock);
//                            Long start = System.currentTimeMillis();
//                            String tflockid = sendPersonlock(personlock);
//                            log.info("推送锁定数据id：{},推送解锁数据耗时: {}ms", tflockid, System.currentTimeMillis() - start);
//                            if (StringUtils.isNotBlank(tflockid)) {
//                                //personlock.setTflockid(tflockid);
//                               //personlockService.updateById(personlock);
//                            } else {
//                                throw new BusinessException("推送锁定数据失败");
//                            }

                        }
                    }
                }
                //  审批选择不同意> 结束流程
                if (FlowUtil.PUNISHWORKFLOWE_OVERPUNISH.equals(nextNodeID)) {
                    bizPunishLockModel.setApprovaldate(LocalDate.now());//核准日期
                    bizPunishLockModel.setStatus("3");// 9 受理中、1 审批中、2 已通过、3 不通过
                    updateById(bizPunishLockModel);
                    //恢复拟锁定列表状态为未办:0
                    if(StringUtils.isNotBlank(bizPunishLockModel.getTolockentlistid())){
                        tolockentlistService.updateByTolockId(bizPunishLockModel.getTolockentlistid());
                    }
                }
            }
            taskListService.updateWorkFlow(user, opinionModel, taskListModel, nextNodeID, nextPerformerids, nextPerformerNames);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("联合惩戒锁定审核出错");
        }
        return taskListModel;
    }

    /**
     * 获取企业的法定代表人的证件号
     * @param eBaseinfo
     * @return
     */
    public Personnel queryCerno(EBaseinfo eBaseinfo){
//        Personnel personnelRs = null;
//        Map<String,String> para = new HashMap<>();
//        if(StringUtils.isNotBlank(eBaseinfo.getUniscid())){
//            para.put("uniscid", eBaseinfo.getUniscid());
//        } else if (StringUtils.isNotBlank(eBaseinfo.getRegno())) {
//            para.put("regno", eBaseinfo.getRegno());
//        }
//        ForestResponse<ChangRuanResult<List<Personnel>>> response = soaServiceApi.queryPriPerson(para);
//        assert response != null;
//        ChangRuanResult<List<Personnel>> result = response.getResult();
//        List<Personnel> personnels = result.getData();
//        Optional<Personnel> optional = personnels.stream().filter(item -> "1".equals(item.getLerepsign())).findFirst();
//        personnelRs = optional.get();
//        return personnelRs;
        return null;
    }

    /**
     * 推送锁定数据
     * @param entLock
     */
    public String sendEntLock(EntLock entLock) {
        String token = getToken();
        if(StringUtils.isBlank(token)) {
            return "";
        }
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Map<String,Object> params = new HashMap<>();
        OrgUnits orgUnits = aicorgMapper.queryByOrgUnitID(entLock.getLockuserunitid());
        String lockTiem = df.format(entLock.getLockTime());
        params.put("aicode",BaseDataConstant.TFLOCK_AICODE);
        Map<String,String> param = new HashMap<>();
        param.put("entname",entLock.getEntname());
        param.put("uniscid",entLock.getUniscid());
        param.put("lockstartdate",lockTiem);
        param.put("lockenddate","9999-12-31 23:59:59"); //默认结束时间为永久
        String warningContent = entLock.getWarningcontent() == null ? "" : entLock.getWarningcontent(); //警告语
        param.put("lockreason",entLock.getLockreason() + warningContent);
        param.put("lockuser",entLock.getLockusername());
//        if(orgUnits!=null) param.put("lockuserunit",orgUnits.getOrgUnitName());
        if(orgUnits!=null) {
            String orgUnitName = orgUnits.getOrgUnitName();
//            String orgUnitCode = ConstantsUtil.getTFbmcode(orgUnitName);
            String orgUnitCode = "150000";
            param.put("lockuserunit",orgUnitCode);
        }
        params.put("param",param);
        ForestResponse<TfPunishLock> sendRs = tfPunishmentApi.pushEntlockData(token,params);
        TfPunishLock tfPunishLock = sendRs.getResult();
        Map<String,Object> map = tfPunishLock.getData();
        if(tfPunishLock.getCode()==200){
            log.info("推送锁定数据成功："+ entLock.getElid()+"==="+tfPunishLock.getLockid());
            return tfPunishLock.getLockid();
        } else {
            //清除缓存
            redisService.remove(BaseDataConstant.LOCKTOKEN_REDIS);
            log.info("推送锁定数据失败："+entLock.getElid());
            log.info("返回结果：代码值" + tfPunishLock.getCode() + "message："+tfPunishLock.getMessage());
            return "";
        }
    }
    public String sendPersonlock(Personlock personlock){
        String token = getToken();
        if(StringUtils.isBlank(token)) {
            return "";
        }
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Map<String,Object> params = new HashMap<>();
        Map<String,Object> param = new HashMap<>();
        OrgUnits orgUnits = aicorgMapper.queryByOrgUnitID(personlock.getLockuserunitid());
        String lockTiem = df.format(personlock.getLockstartdate());
        params.put("aicode",BaseDataConstant.TFLOCK_AICODE);
        param.put("entname",personlock.getEntname());
        //param.put("uniscid",personlock.getUniscid());
        param.put("lockstartdate",lockTiem);
        param.put("lockenddate","9999-12-31 23:59:59"); //默认结束时间为永久
        //String warningContent = personlock.getWarningcontent() == null ? "" : personlock.getWarningcontent(); //警告语
        param.put("lockreason",personlock.getLockreason());
        param.put("lockuser",personlock.getLockusername());
        if(orgUnits!=null) {
            String orgUnitName = orgUnits.getOrgUnitName();
//            String orgUnitCode = ConstantsUtil.getTFbmcode(orgUnitName);
            String orgUnitCode = "150000";
            param.put("lockuserunit",orgUnitCode);
        }
        params.put("param",param);
        ForestResponse<TfPunishLock> sendRs = tfPunishmentApi.pushEntlockData(token,params);
        TfPunishLock tfPunishLock = sendRs.getResult();
        Map<String,Object> map = tfPunishLock.getData();
        if(tfPunishLock.getCode()==200){
            log.info("推送锁定数据成功："+ personlock.getPlid()+"==="+tfPunishLock.getLockid());
            return tfPunishLock.getLockid();
        } else {
            //清除缓存
            redisService.remove(BaseDataConstant.LOCKTOKEN_REDIS);
            log.info("推送锁定数据失败："+personlock.getPlid());
            log.info("返回结果：代码值" + tfPunishLock.getCode() + "message："+tfPunishLock.getMessage());
            return "";
        }
    }

    /**
     * 获取token
     * @return
     */
    public String getToken() {
        //先从缓存获取token
        String token = "";
        Object obj = redisService.get(BaseDataConstant.LOCKTOKEN_REDIS);
        if(obj != null){
            token = obj.toString();
            return token;
        }
        Map<String,Object> tokenParam = new HashMap<>();
        tokenParam.put("appid", BaseDataConstant.TFLOCKTOKEN_APPID);
        tokenParam.put("appsecret",BaseDataConstant.TFLOCKTOKEN_APPSECRET);
        ForestResponse<TfPunishLock> tokenRs = tfPunishmentApi.getToken(tokenParam);
        TfPunishLock tfToken = tokenRs.getResult();
        if(tfToken.getCode()==200){
            Map<String,Object> map = tfToken.getData();
            if(map.get("token")!=null) {
                token = map.get("token").toString();
                // 有效时限3小时,泰富为4小时
                redisService.set(BaseDataConstant.LOCKTOKEN_REDIS,token,10800);
            }
        } else {
            log.info("获取锁定token失败返回码：{}",tfToken.getCode());
            log.info("获取锁定token失败返回信息：{}",tfToken.getMessage());
            return "";
        }
        return token;
    }



    @Override
    public Boolean checkpunishlock(String pripid) {
        return tsbizPunishLockMapper.checkpunishlock(pripid);
    }
}
