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

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaweal.aiccs.aiccs.abnormal.entity.*;
import com.chinaweal.aiccs.aiccs.abnormal.entity.dto.DissentAppDto;
import com.chinaweal.aiccs.aiccs.abnormal.mapper.TSBizDissentMapper;
import com.chinaweal.aiccs.aiccs.abnormal.service.*;
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.business.service.WorkFlowService;
import com.chinaweal.aiccs.aiccs.inspect.service.TSWorkNoService;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.util.*;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.aicorg.services.OrgUM;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 经营异常名录异议业务表 服务实现类
 * </p>
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021-01-19
 */
@Slf4j
@Service
public class TSBizDissentServiceImpl extends ServiceImpl<TSBizDissentMapper, TSBizDissent> implements TSBizDissentService {

    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private TSWorkNoService workNoService;
    @Autowired
    private TSWritService tsWritService;
    @Autowired
    private AicorgService aicorgService;
    @Autowired
    private TSAbnListService abnListService;
    @Autowired
    private TSAbnListService tsAbnListService;
    @Lazy
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Lazy
    @Autowired
    private IGzaiccodeService iGzaiccodeService;
    @Autowired
    private OrgUM orgUM;
    @Autowired
    private WorkFlowService workFlowService;

    @Override
    public List<TSBizDissent> selectbizDissentList(TSBizDissent tsBizDissentModel) {
        return baseMapper.selectbizDissentList(tsBizDissentModel);
    }

    @Override
    public TSBizDissent selectbizDissentone(String bizSeqId) {
        return getOne(new LambdaQueryWrapper<TSBizDissent>().eq(TSBizDissent::getBizseq, bizSeqId));
    }

    @Override
    public TSTaskList startBizDissentAccept(AICUser user, List<String> userIdList, TSTaskList taskListModel, TSBizDissent tsBizDissentModel) {
        if (StringUtils.isBlank(taskListModel.getTasklistid())) {
            saveOrUpdate(tsBizDissentModel);
            taskListModel = HandleWorkFlowUtil.createTaskList(taskListModel, user); //新生成待办
            String definedName = FlowUtil.DISSENTWORKFLOW; //经营异常名录异议 流程模板 dissentWorkFlow
            if (CollUtil.isEmpty(userIdList) || userIdList.size() <= 1) {
                taskListService.startWorkFlow(taskListModel, user, definedName);
            } else {
                taskListService.startWorkFlow(taskListModel, userIdList, user.getRegionID().substring(0, 6), definedName);
            }
        }
        return taskListModel;
    }

    @Override
    public TSTaskList saveBizDissentAuditProcess(AICUser user, TSTaskList taskListModel, TSBizDissent tsBizDissentModel, TSOpinion opinionModel, String nextNodeID, String[] nextPerformerids, String[] nextPerformerNames) {
        // 审批通过-办结
        if (FlowUtil.DISSENTWORKFLOW_ENDDISSENT.equals(nextNodeID)) {
            TSWrit tsWritModel = new TSWrit();
            tsWritModel.setWritsid(UUID.randomUUID().toString());
            String worgNoType = "";
            if (StringUtils.isNotBlank(tsBizDissentModel.getAcceptstat()) && tsBizDissentModel.getAcceptstat().equals("0")) {//生成文书号
                worgNoType = WorkNoUtil.WORKNOTYPE_13;// "列入经营异常名录异议不予受理通知书";
                tsWritModel.setContent(BaseDataConstant.ABN_DISSENT_DISAGREE_ACCEPT_CONTENT);
            } else if (StringUtils.isNotBlank(tsBizDissentModel.getAcceptstat()) && tsBizDissentModel.getAcceptstat().equals("1")) {
                worgNoType = WorkNoUtil.WORKNOTYPE_14;//"列入经营异常名录异议核实结果告知书";

                TSAbnList tsAbnList = abnListService.getById(tsBizDissentModel.getAbnlistid());
                if (BaseDataConstant.BUSTNESS_TYPE_REM_ABN_OBJECTION.equals(taskListModel.getBustype())) { // 移出经营异常异议
                    abnListService.update(null, new LambdaUpdateWrapper<TSAbnList>()
                            .set(TSAbnList::getOperatestatus, "1")
                            .set(TSAbnList::getRemSponsor, null)
                            .set(TSAbnList::getRemdate, null)
                            .set(TSAbnList::getRemreasons, null)
                            .set(TSAbnList::getRemexcpres, null)
                            .set(TSAbnList::getRemDecorg, null)
                            .set(TSAbnList::getReDecorg, null)
                            .set(TSAbnList::getRemRemark, null)
                            .set(TSAbnList::getLauptime, LocalDateTime.now())
                            .eq(TSAbnList::getAbnlistid, tsAbnList.getAbnlistid()));
                } else { // 列入经营异常异议
                    tsAbnList.setOperatestatus("2");//撤销
                    tsAbnList.setLauptime(LocalDateTime.now());
                    abnListService.updateById(tsAbnList);
                    tsBizDissentModel.setStatus("2");
                }
            }
            tsWritModel.setWritstype(worgNoType);
            tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(worgNoType));
            //获取用户所在部门辖区码值
            tsWritModel.setAreaCode(aicorgService.getRegionCodeByUser(user));
            String writsno = workNoService.getOperatingWrirsno(worgNoType,tsWritModel.getAreaCode());
            tsWritModel.setWritsno(writsno);
            tsWritModel.setBizseq(tsBizDissentModel.getBizseq());
            tsWritModel.setPripid(tsBizDissentModel.getPripid());
            tsWritModel.setCreatetime(LocalDateTime.now());
            tsWritService.save(tsWritModel);

            tsBizDissentModel.setApprovaldate(LocalDate.now()); //核准时间
        }
        //下一步为核准经办
        if (FlowUtil.DISSENTWORKFLOW_APPROVEDISSENTACCEPT.equals(nextNodeID)) {

            TSWrit tsWritModel = new TSWrit();
            tsWritModel.setWritsid(UUID.randomUUID().toString());
            String worgNoType = WorkNoUtil.WORKNOTYPE_12;//"列入经营异常名录异议受理通知书";
            //检查是否已生成 回退时是已生成的情况
            List<TSWrit> list = tsWritService.list(new LambdaQueryWrapper<TSWrit>().eq(TSWrit::getBizseq, tsBizDissentModel.getBizseq()).eq(TSWrit::getWritstype,worgNoType));
            if(list.size() == 0){
                tsWritModel.setAreaCode(aicorgService.getRegionCodeByUser(user));
                String writsno = workNoService.getOperatingWrirsno(worgNoType, tsWritModel.getAreaCode());
                tsWritModel.setWritstype(worgNoType);
                tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(worgNoType));
                tsWritModel.setContent(BaseDataConstant.ABN_DISSENT_AGREE_ACCEPT_CONTENT);
                tsWritModel.setBizseq(tsBizDissentModel.getBizseq());
                tsWritModel.setWritsno(writsno);
                tsWritModel.setPripid(tsBizDissentModel.getPripid());
                tsWritModel.setCreatetime(LocalDateTime.now());
                tsWritService.save(tsWritModel);
            }
        }

        updateById(tsBizDissentModel);
        // 判断是否以组为签收单位
        if (StringUtils.isNotBlank(taskListModel.getAcceptgroupid())) {
            workFlowService.claimGroup(taskListModel.getWorkflowid(), user.getPrimaryKey());
        }
        taskListService.updateWorkFlow(user, opinionModel, taskListModel, nextNodeID, nextPerformerids, nextPerformerNames);
        return  taskListModel;
    }

    @Override
    public void startAppDissent(DissentAppDto dissentAppDto) {

        String bizSeq = dissentAppDto.getBizSeq();
        TSAbnList tsAbnListModel = tsAbnListService.getById(dissentAppDto.getAbnlistid());
        EBaseinfo eBaseInfo = eBaseinfoService.getById(tsAbnListModel.getPripid());

        //添加异议表数据
        TSBizDissent tsBizDissentModel = new TSBizDissent();
        tsBizDissentModel.setBizseq(bizSeq);
        tsBizDissentModel.setAbnlistid(tsAbnListModel.getAbnlistid());
        tsBizDissentModel.setPripid(tsAbnListModel.getPripid());
        tsBizDissentModel.setRegno(tsAbnListModel.getRegno());
        tsBizDissentModel.setUniscid(tsAbnListModel.getUniscid());
        tsBizDissentModel.setEntname(tsAbnListModel.getEntname());
        tsBizDissentModel.setLerepname(eBaseInfo.getName());
        tsBizDissentModel.setAbnTime(tsAbnListModel.getAbntime());
        tsBizDissentModel.setAbnRea(tsAbnListModel.getSpecause());
        tsBizDissentModel.setAbnReaCn(tsAbnListModel.getSpereasons());
        tsBizDissentModel.setStatus("9");
        tsBizDissentModel.setAppOrPc("1");
        tsBizDissentModel.setApplicant(dissentAppDto.getApplicant());
        tsBizDissentModel.setApplicantId(dissentAppDto.getApplicantId());
        tsBizDissentModel.setApplicantNo(dissentAppDto.getApplicantNo());
        tsBizDissentModel.setContacts(dissentAppDto.getApplicant());
        tsBizDissentModel.setTelephone(dissentAppDto.getApplicantNo());

        String entTypeAlias = ConstantsUtil.getEntTypeAlias(tsAbnListModel.getEnttype());
        String permission = "individual".equals(entTypeAlias) ? "individualRecoverAccept" : "exptRemoveEnter";
        List<String> userIdList = iGzaiccodeService.byPermissionListHandleUserList(tsAbnListModel.getPripid(), permission, tsAbnListModel.getDecorg(), tsAbnListModel.getIntoDecorg())
                .stream().map(AICUser::getPrimaryKey).collect(Collectors.toList());
        if (userIdList.isEmpty()) {
            log.error("分派失败，受理人列表为空, tsabnlist为：{},权限为：{}", tsAbnListModel, permission);
            throw new BusinessException("受理人列表为空！");
        } else {
            TSTaskList taskListModel = new TSTaskList();
            //添加待办
            taskListModel.setBizseqid(bizSeq);
            if ("individual".equals(entTypeAlias)) {
                taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_OBJECTION);
            } else if ("farmer".equals(entTypeAlias)) {
                taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_FARMER_OBJECTION);
            } else {
                taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_OBJECTION);
            }
            taskListModel.setBusname(tsBizDissentModel.getEntname());
            AICUser aicUser = orgUM.findUserByPrimaryKey(userIdList.get(0));
            taskListModel = startBizDissentAccept(aicUser, userIdList, taskListModel, tsBizDissentModel);
            //移动端过来的数据要更新为申请人的信息
            taskListModel.setSenderuserid("");
            taskListModel.setSenderorgid("");
            taskListModel.setSendername(dissentAppDto.getApplicant());
            taskListService.updateById(taskListModel);
        }

    }
}
