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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.TsbizPunishUnlock;
import com.chinaweal.aiccs.aiccs.punishment.mapper.TsbizpunishunlockMapper;
import com.chinaweal.aiccs.aiccs.punishment.service.EntlockService;
import com.chinaweal.aiccs.aiccs.punishment.service.PersonlockService;
import com.chinaweal.aiccs.aiccs.punishment.service.TsbizPunishLockService;
import com.chinaweal.aiccs.aiccs.punishment.service.TsbizPunishUnlockService;
import com.chinaweal.aiccs.aiccs.punishment.util.BusTridMakeUtil;
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.TfPunishmentApi;
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.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.util.AssertUtils;
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 javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

import static com.chinaweal.aiccs.common.base.controller.BaseController.getLoginUser;

/**
 * <p>
 * 解锁业务表 服务实现类
 * </p>
 *
 * @author Lee
 * @since 2021-06-07
 */
@Slf4j
@Service
public class TsbizPunishUnlockServiceImpl extends BaseServiceImpl<TsbizpunishunlockMapper, TsbizPunishUnlock> implements TsbizPunishUnlockService {

    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private EntlockService entlockService;
    @Autowired
    private PersonlockService personlockService;
    @Autowired
    private TsbizPunishLockService tsbizPunishLockService;
    @Resource
    private AicorgMapper aicorgMapper;
    @Resource
    private TfPunishmentApi tfPunishmentApi;
    @Autowired
    private RedisService redisService;

    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private TsbizpunishunlockMapper tsbizpunishunlockMapper;

    @Autowired
    private BusTridMakeUtil busTridMakeUtil;
//    @Transactional
//    @Override
//    public TSTaskList savePunishUnlockAccept(AICUser user, TSTaskList taskListModel, List<TsbizPunishUnlock> tsbizPunishUnlocks, List<EntLock> entLocks) {
//        if (StringUtils.isBlank(taskListModel.getTasklistid())) {
//            for (TsbizPunishUnlock bizPunishUnlockModel : tsbizPunishUnlocks) {
//                bizPunishUnlockModel.setUnluserid(user.getPrimaryKey());
//                bizPunishUnlockModel.setUlunitid(user.getOrgID());
//                bizPunishUnlockModel.setUldeptid(user.getUnitID());
//                bizPunishUnlockModel.setHandler(user.getName());//设置列入主办人
//                bizPunishUnlockModel.setStatus("9"); // 流程启动把状态设置为 "受理中"
//                saveOrUpdate(bizPunishUnlockModel);
//            }
//            for (EntLock entLock : entLocks) {
//                entLock.setState("2");  //解锁中
//                entlockService.updateById(entLock);
//            }
//            String definedname = FlowUtil.PUNISHWORKFLOW;//企业经营异常名录流程模板
//            //新待办 设置待办信息
//            taskListModel = HandleWorkFlowUtil.createTaskList(taskListModel, user);
//            //开始工作流
//            taskListService.startWorkFlow(taskListModel, user, definedname);
//        }
//        return taskListModel;
//    }
    @Transactional
    @Override
    public TSTaskList savePunishUnlockAccept(AICUser user, TSTaskList taskListModel, List<TsbizPunishUnlock> tsbizPunishUnlocks, List list) {
        if (StringUtils.isBlank(taskListModel.getTasklistid())) {
            for (TsbizPunishUnlock bizPunishUnlockModel : tsbizPunishUnlocks) {
                bizPunishUnlockModel.setUnluserid(user.getPrimaryKey());
                bizPunishUnlockModel.setUlunitid(user.getOrgID());
                bizPunishUnlockModel.setUldeptid(user.getUnitID());
                bizPunishUnlockModel.setHandler(user.getName());//设置列入主办人
                bizPunishUnlockModel.setStatus("9"); // 流程启动把状态设置为 "受理中"
                saveOrUpdate(bizPunishUnlockModel);
            }
//            for (EntLock entLock : entLocks) {
//                entLock.setState("2");  //解锁中
//                entlockService.updateById(entLock);
//            }
            for (Object o : list) {
                if(o instanceof EntLock){
                 EntLock e=(EntLock) o;
                 e.setState("2");
                 entlockService.updateById(e);
                }
            }
            String definedname = FlowUtil.PUNISHWORKFLOW;//企业经营异常名录流程模板
            //新待办 设置待办信息
            taskListModel = HandleWorkFlowUtil.createTaskList(taskListModel, user);
            //开始工作流
            taskListService.startWorkFlow(taskListModel, user, definedname);
        }
        return taskListModel;
    }
    @Transactional
    @Override
    public TSTaskList savePunishUnlockProcess(AICUser user, TSTaskList taskListModel, List<TsbizPunishUnlock> tsbizPunishUnlocks,
                                              TSOpinion opinionModel, String nextNodeID, String[] nextPerformerids, String[] nextPerformerNames) {
        try {
            for (TsbizPunishUnlock bizPunishUnlockModel : tsbizPunishUnlocks) {
                //下一步为审核
                if (FlowUtil.PUNISHWORKFLOWE_HANDLEPUNISH.equals(nextNodeID)) { //审批时操作
                    bizPunishUnlockModel.setStatus("1"); // 审批流程中把状态设置成 "审批中"
                    saveOrUpdate(bizPunishUnlockModel);
                }
                //添加到 业户锁定表
                if (FlowUtil.PUNISHWORKFLOWE_ENDPUNISH.equals(nextNodeID)) {//完结时
                    LambdaQueryWrapper<EntLock> entLockWrapper = new LambdaQueryWrapper<>();
                    entLockWrapper.eq(EntLock::getElid,bizPunishUnlockModel.getElid());
                    LambdaQueryWrapper<Personlock> personlockWrapper = new LambdaQueryWrapper<>();
                    personlockWrapper.eq(Personlock::getPlid,bizPunishUnlockModel.getElid());
                    EntLock e = entlockService.getOne(entLockWrapper);
                    if(null!=e){
                        EntLock entLockModel = new EntLock();
                        entLockModel.setElid(bizPunishUnlockModel.getElid());
                        entLockModel.setUnluserid(user.getPrimaryKey());
                        entLockModel.setUlunitid(user.getOrgID());
                        entLockModel.setUldeptid(user.getUnitID());
                        entLockModel.setUnlockreason(bizPunishUnlockModel.getUnlockreason());
                        entLockModel.setUnlusername(user.getName());
                        entLockModel.setUnlockTime(LocalDateTime.now());
                        entLockModel.setLaupTime(LocalDateTime.now());
                        entLockModel.setState("3"); //以解锁
                        entlockService.updateById(entLockModel);
//                        Long start = System.currentTimeMillis();
//                        Boolean rs = sendUnEntLock(entlockService.getById(bizPunishUnlockModel.getElid()));
//                        if (rs) {
//                            log.info("推送解锁数据id：{},推送解锁数据耗时: {}ms", bizPunishUnlockModel.getElid(), System.currentTimeMillis() - start);
//                        } else {
//                            throw new BusinessException("推送锁定数据失败");
//                        }
                    }
                    Personlock p = personlockService.getOne(personlockWrapper);
                    if(null!=p){
                            Personlock personlock = new Personlock();
                            personlock.setPlid(bizPunishUnlockModel.getElid());
                            personlock.setUnlockuserid(user.getPrimaryKey());
                            personlock.setUlunitid(user.getOrgID());
                            personlock.setUldeptid(user.getUnitID());
                            personlock.setUlockseason(bizPunishUnlockModel.getUnlockreason());
                            personlock.setUnlockusername(bizPunishUnlockModel.getUnlusername());
                            personlock.setUnldate(LocalDateTime.now());
                            personlock.setInputdate(LocalDateTime.now());
                            personlock.setLockstate("0"); //以解锁
                            personlockService.updateById(personlock);
//                            Long start = System.currentTimeMillis();
//                            Boolean rs = sendUnPersonLock(personlockService.getById(bizPunishUnlockModel.getElid()));
//                            if (rs) {
//                                log.info("推送解锁数据id：{},推送解锁数据耗时: {}ms", bizPunishUnlockModel.getElid(), System.currentTimeMillis() - start);
//                            } else {
//                                throw new BusinessException("推送锁定数据失败");
//                            }
                        }

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

                //  审批选择不同意> 结束流程
                if (FlowUtil.PUNISHWORKFLOWE_OVERPUNISH.equals(nextNodeID)) {
                    bizPunishUnlockModel.setApprovaldate(LocalDate.now());//核准日期
                    bizPunishUnlockModel.setStatus("3");// 9 受理中、1 审批中、2 已通过、3 不通过
                    updateById(bizPunishUnlockModel);
                    //将状态设置为拟解锁
                    if(StringUtils.isNotBlank(bizPunishUnlockModel.getElid())){
                        LambdaQueryWrapper<EntLock> wrapper = new LambdaQueryWrapper();
                        wrapper.eq(EntLock::getElid,bizPunishUnlockModel.getElid());
                        EntLock entLock = entlockService.getOne(wrapper);
                        //entLock.setState("1");
                        entLock.setState("0");
                        entlockService.updateById(entLock);
                    }
                }
            }
            taskListService.updateWorkFlow(user, opinionModel, taskListModel, nextNodeID, nextPerformerids, nextPerformerNames);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("联合惩戒解锁审核出错");
        }
        return taskListModel;
    }

    @Override
    public boolean checkpunishlock(String elid) {
        return tsbizpunishunlockMapper.checkpunishlock(elid);
    }

    public Boolean sendUnEntLock(EntLock entlock){
        String token = tsbizPunishLockService.getToken();
        if(StringUtils.isBlank(token)){
            return false;
        }
        Map<String,Object> params = new HashMap<>();
        params.put("aicode", BaseDataConstant.TFUNLOCK_AICODE);
        Map<String,String> param = new HashMap<>();
        param.put("lockid",entlock.getTflockid());
        param.put("unlockreason",entlock.getUnlockreason());
        param.put("unlockuser",entlock.getUnlusername());
        OrgUnits orgUnits = aicorgMapper.queryByOrgUnitID(entlock.getUlunitid());
        if(orgUnits!=null) {
            String orgUnitName = orgUnits.getOrgUnitName();
//            String orgUnitCode = ConstantsUtil.getTFbmcode(orgUnitName);
            String orgUnitCode = "150000";
            param.put("unlockuserunit",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());
            return true;
        } else {
            redisService.remove(BaseDataConstant.LOCKTOKEN_REDIS);
            log.info("推送解锁数据失败："+entlock.getElid());
            log.info("返回结果：代码值" + tfPunishLock.getCode() + "message："+tfPunishLock.getMessage());
            return false;
        }
    }

    public Boolean sendUnPersonLock(Personlock personlock){
        String token = tsbizPunishLockService.getToken();
        if(StringUtils.isBlank(token)){
            return false;
        }
        Map<String,Object> params = new HashMap<>();
        params.put("aicode", BaseDataConstant.TFUNLOCK_AICODE);
        Map<String,String> param = new HashMap<>();
        param.put("lockid",personlock.getTflockid());
        param.put("unlockreason",personlock.getUlockseason());
        param.put("unlockuser",personlock.getUnlockusername());
        OrgUnits orgUnits = aicorgMapper.queryByOrgUnitID(personlock.getUlunitid());
        if(orgUnits!=null) {
            String orgUnitName = orgUnits.getOrgUnitName();
//            String orgUnitCode = ConstantsUtil.getTFbmcode(orgUnitName);
            String orgUnitCode = "150000";
            param.put("unlockuserunit",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());
            return true;
        } else {
            redisService.remove(BaseDataConstant.LOCKTOKEN_REDIS);
            log.info("推送解锁数据失败："+ personlock.getPlid());
            log.info("返回结果：代码值" + tfPunishLock.getCode() + "message："+tfPunishLock.getMessage());
            return false;
        }
    }
    @Transactional
    public Map<String, String> addtounlock(String[] elIdArray, String bizSeq, HttpServletRequest request){

        AICUser aicUser = getLoginUser(request);
        ArrayList<TsbizPunishUnlock> tsbizPunishUnlocks = new ArrayList<>();
        List<EntLock> entLocks = entlockService.list(new LambdaQueryWrapper<EntLock>().in(EntLock::getElid, Arrays.asList(elIdArray)));
        List<Personlock> personlocks = personlockService.list(new LambdaQueryWrapper<Personlock>().in(Personlock::getPlid, Arrays.asList(elIdArray)));
        List list=new ArrayList();
        if(entLocks!=null&&entLocks.size()>0){
            list.addAll(entLocks);
            if(personlocks!=null&&personlocks.size()>0){
                for (Personlock personlock : personlocks) {
                    Iterator iterator = list.iterator();
                    while (iterator.hasNext()) {
                        EntLock e = (EntLock) iterator.next();
                        if (!personlock.getPlid().equals(e.getElid())) {
                            list.add(personlock);
                            continue;
                        }
                    }
                }
            }
        }else{
            list.addAll(personlocks);
        }
        if(list!=null&&list.size()>0){
            for (Object o : list) {
                TsbizPunishUnlock tsbizpunishunlockmodel = new TsbizPunishUnlock();
                tsbizpunishunlockmodel.setBizseq(bizSeq);
                if(o instanceof EntLock){
                    EntLock entLock= (EntLock) o;
                    tsbizpunishunlockmodel.setElid(entLock.getElid());
                    tsbizpunishunlockmodel.setEntname(entLock.getEntname());
                    tsbizpunishunlockmodel.setPripid(entLock.getPripid());
                    tsbizpunishunlockmodel.setRegno(entLock.getRegno());
                    tsbizpunishunlockmodel.setUniscid(entLock.getUniscid());
                    tsbizPunishUnlocks.add(tsbizpunishunlockmodel);
                }else if(o instanceof Personlock){
                    Personlock personlock=(Personlock)o;
                    LambdaQueryWrapper<EBaseinfo> wrapper=new LambdaQueryWrapper<>();
                    wrapper.eq(EBaseinfo::getEntname,personlock.getEntname());
                    EBaseinfo one = eBaseinfoService.getOne(wrapper);
                    tsbizpunishunlockmodel.setElid(personlock.getPlid());
                    tsbizpunishunlockmodel.setEntname(personlock.getEntname());
                    tsbizpunishunlockmodel.setPripid(one.getPripid());
                    tsbizpunishunlockmodel.setRegno(personlock.getRegno());
                    tsbizpunishunlockmodel.setUniscid(one.getUniscid());
                    tsbizPunishUnlocks.add(tsbizpunishunlockmodel);
                }
            }
        }

        if (tsbizPunishUnlocks.size() == 0) throw new BusinessException("尚未查找到锁定信息");

        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizSeq);
        taskListModel.setBustype(BaseDataConstant.PUNISH_TYPE_UNLOCK);
        //封装待办业务名称
        String entname = "联合惩戒解锁"+busTridMakeUtil.getUnlockCurAcceptNo();
        String entname1 = list.get(0) instanceof EntLock?((EntLock) list.get(0)).getEntname():((Personlock) list.get(0)).getEntname();
        taskListModel.setBusname(entname1+"等企业及法人");
        //taskListModel = tsbizPunishUnlockService.savePunishUnlockAccept(aicUser, taskListModel, tsbizPunishUnlocks, entLocks);
        taskListModel = savePunishUnlockAccept(aicUser, taskListModel, tsbizPunishUnlocks, entLocks);

            Map<String, String> result = new HashMap<>();
            result.put("tasklistid", taskListModel.getTasklistid());
            result.put("bizseq", bizSeq);
            result.put("workflowId", taskListModel.getWorkflowid());
            return result;


    }
}
