package com.ruoyi.system.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.*;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.UnitAndTSystableVo;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ISubInfoService;
import org.apache.poi.util.Internal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 参数配置 服务层实现
 *
 * @author ruoyi
 */
@Service
@DataSource(value = DataSourceType.SLAVE)
public class SubInfoServiceImpl extends ServiceImpl<SubInfoMapper, SubInfo> implements ISubInfoService {

    @Autowired
    private SubInfoMapper subInfoMapper;


    @Autowired
    private SyncVisitMapper visitMapper;

    @Autowired
    private UnitMapper unitMapper;
    @Autowired
    private SubSourceMapper subSourceMapper;

    @Autowired
    private SyncLogMapper syncLogMapper;

    @Autowired
    private SubFlowMapper subFlowMapper;

    @Autowired
    private SysTableMapper sysTableMapper;

    @Autowired
    private SubPreNewMapper subPreNewMapper;

    @Autowired
    private CommUserMapper commUserMapper;

    @Autowired
    private SecUserMapper secUserMapper;


    @Autowired
    private SecRoleMapper secRoleMapper;
    @Autowired
    private SubPreLogMapper subPreLogMapper;

    @Override
    public List<SubInfo> list(Wrapper<SubInfo> wrapper) {
        return subInfoMapper.selectList(wrapper);
    }

    @Override
    public SubInfo findOne(Wrapper<SubInfo> wrapper) {
        return subInfoMapper.selectOne(wrapper);
    }

    /**
     * 同步项目信息
     *
     * @param sub
     * @param company
     * @return
     */
    @Override
    @Transactional
    public boolean syncSubInfo(Sub sub, String company) {
        List<SysTable> listTable = sysTableMapper.selectList(new LambdaQueryWrapper<SysTable>().eq(SysTable::getLogicDeleteFlag, "0"));
        Map<String, SysTable> map = new HashMap<>();
        for (SysTable sysTable : listTable) {
            map.put(sysTable.getTitle() + sysTable.getKind(), sysTable);
        }
        //名称
        List<SubInfo> lstSubInfo = subInfoMapper.selectList(new LambdaQueryWrapper<SubInfo>().eq(SubInfo::getSubName, sub.getProjectname()).eq(SubInfo::getLogicDeleteFlag, "0"));
        if (lstSubInfo == null || lstSubInfo.size() == 0) {
            lstSubInfo = subInfoMapper.selectList(new LambdaQueryWrapper<SubInfo>().eq(SubInfo::getSubCode, sub.getProjectid()).eq(SubInfo::getLogicDeleteFlag, "0"));
        }
        if(StringUtils.isEmpty(sub.getPsorttwoname())){
            sub.setPsorttwoname("其他");
        }
        //查找行业
        SyncVisit kindVist = visitMapper.selectOne(new LambdaQueryWrapper<SyncVisit>().eq(SyncVisit::getOtherTitle, sub.getPsorttwoname()).eq(SyncVisit::getCat, "1"));
        if (kindVist == null) {
            SyncLog log = new SyncLog();
            log.setCat("1").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(sub)).setState("1");
            log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步项目信息失败:项目名称【%s】和项目代码【%s】,所属行业【%s】未找到", sub.getProjectname(), sub.getProjectid(), sub.getPsorttwoname()));
            syncLogMapper.insert(log);
            return false;
        }
            SysTable kind = map.get(kindVist.getTitle() + "HYFL");
        if (kind == null) {
            SyncLog log = new SyncLog();
            log.setCat("1").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(sub)).setState("1");
            log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步项目信息失败:项目名称【%s】和项目代码【%s】,对应行业【%s】未找到", sub.getProjectname(), sub.getProjectid(), kindVist.getTitle()));
            syncLogMapper.insert(log);
            return false;
        }
        //查单位
        List<Unit> listUnit = unitMapper.selectList(new LambdaQueryWrapper<Unit>().eq(Unit::getTitle, sub.getIncname()).eq(Unit::getLogicDeleteFlag, "0"));
        if (listUnit.size() < 0) {
            listUnit = unitMapper.selectList(new LambdaQueryWrapper<Unit>().eq(Unit::getTrustCode, sub.getIncid()).eq(Unit::getLogicDeleteFlag, "0"));
        }
        Unit unit = null;
        if (listUnit.size() == 0) {
            unit = this.autoUnitAndUser(sub.getIncname(), sub.getIncid(), "1", "2", sub.getIncid(), "001");
        } else {
            if (listUnit.size() > 1) {
                //找有项目的那个
                for (int i = 0; i < listUnit.size(); i++) {
                    //多个找到有项目的那个
                    Integer cnt = subInfoMapper.selectCount(new LambdaQueryWrapper<SubInfo>().eq(SubInfo::getUnitId, listUnit.get(i).getId()).eq(SubInfo::getLogicDeleteFlag, "0"));
                    if (cnt > 0) {
                        unit = listUnit.get(i);
                        break;
                    }
                }
                if (unit == null) {
                    SyncLog log = new SyncLog();
                    log.setCat("1").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(sub)).setState("1");
                    log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步项目信息失败:项目名称【%s】和项目代码【%s】,单位找到【%s】多个请检查", sub.getProjectname(), sub.getProjectid(), sub.getIncname()));
                    syncLogMapper.insert(log);
                    return false;
                }

            } else {
                unit = listUnit.get(0);
            }
        }
        SyncVisit addressVist = visitMapper.selectOne(new LambdaQueryWrapper<SyncVisit>().eq(SyncVisit::getOtherTitle, sub.getAreaidtwoname()).eq(SyncVisit::getCat, "3"));
        if (addressVist == null) {
            SyncLog log = new SyncLog();
            log.setCat("1").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(sub)).setState("1");
            log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步项目信息失败:项目名称【%s】和项目代码【%s】,项目建设地点【%s】未找到", sub.getProjectname(), sub.getProjectid(), sub.getAreaidtwoname()));
            syncLogMapper.insert(log);
            return false;
        }

        if (lstSubInfo.size() > 0) {
            for (SubInfo subInfo : lstSubInfo) {
                if(StringUtils.isEmpty(subInfo.getSubName())) {
                    subInfo.setSubName(sub.getProjectname());
                }
                if(StringUtils.isEmpty(subInfo.getSubCode())) {
                    subInfo.setSubCode(sub.getProjectid());
                }
                if(StringUtils.isEmpty(subInfo.getIndusKind())) {
                    subInfo.setIndusKind(kind.getId());
                }
                if(StringUtils.isEmpty(subInfo.getContent())) {
                    subInfo.setContent(sub.getConstructionscale());
                }
                if(StringUtils.isEmpty(subInfo.getSubjectId())) {
                    subInfo.setSubjectId(addressVist.getSysId());
                }
                if(subInfo.getBeginDate()==null) {
                    subInfo.setBeginDate(sub.getStarttime());
                }
                if(subInfo.getEndDate()==null) {
                    subInfo.setEndDate(sub.getEndtime());
                }
                if(StringUtils.isEmpty(subInfo.getUnitId())) {
                    subInfo.setUnitId(unit.getId());
                }
                if(StringUtils.isEmpty(subInfo.getKindNature())) {
                    subInfo.setKindNature(sub.getZjlx());
                }
                if(StringUtils.isEmpty(subInfo.getNameZrr())) {
                    subInfo.setNameZrr(sub.getAgename());
                }
                if(StringUtils.isEmpty(subInfo.getNameLead())) {
                    subInfo.setNameLead(sub.getPagename());
                }
                if(subInfo.getCreateTime()==null) {
                    subInfo.setCreateTime(sub.getCreatetime());
                }
                if(StringUtils.isEmpty(subInfo.getTelLead())) {
                    subInfo.setTelLead(sub.getAgephone());
                }
                if(StringUtils.isEmpty(subInfo.getTel())) {
                    subInfo.setTel(sub.getAgemobile());
                }
                if(StringUtils.isEmpty(subInfo.getReason())) {
                    subInfo.setReason(sub.getCbsnum());
                }
                if(subInfo.getAmtTotal()==null) {
                    subInfo.setAmtTotal(sub.getGrossinvestment());
                }
                subInfo.setLastUpdateTime(new Date());
//                if (sub.getStatu().equals("2")) {
//                    subInfo.setLogicDeleteFlag(1);
//                }
                subInfoMapper.updateById(subInfo);
                //防止影响当前资金来源
//                if (!this.hanlderResouce(sub, subInfo, map)) {
//                    return false;
//                }
            }
        } else {
            SubInfo subInfo = null;
            subInfo = new SubInfo();
            subInfo.setId(UUID.randomUUID().toString());
            subInfo.setSubName(sub.getProjectname());
            subInfo.setSubCode(sub.getProjectid());
            subInfo.setIndusKind(kind.getId());
            subInfo.setContent(sub.getConstructionscale());
            subInfo.setSubjectId(addressVist.getSysId());
            subInfo.setBeginDate(sub.getStarttime());
            subInfo.setEndDate(sub.getEndtime());
            subInfo.setUnitId(unit.getId());
            subInfo.setNameZrr(sub.getAgename());
            subInfo.setNameLead(sub.getPagename());
            subInfo.setCreateTime(sub.getCreatetime());
            subInfo.setTelLead(sub.getAgephone());
            subInfo.setTel(sub.getAgemobile());
            subInfo.setKindNature(sub.getZjlx());
            subInfo.setReason(sub.getCbsnum());
            subInfo.setAmtTotal(sub.getGrossinvestment());
            subInfo.setLastUpdateTime(new Date());
            subInfo.setStatus("1");
            if (sub.getStatu().equals("2")) {
                subInfo.setLogicDeleteFlag(1);
            }
            subInfoMapper.insert(subInfo);
            if (!this.hanlderResouce(sub, subInfo, map)) {
                return false;
            }
        }
        SyncLog log = new SyncLog();
        log.setCat("1").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(sub)).setState("2").setInfo("");
        log.setCreateTime(DateUtil.date()).setIsHandle("2").setInfo("成功").setRemark(String.format("同步项目信息:项目名称【%s】和项目代码【%s】已同步", sub.getProjectname(), sub.getProjectid()));
        syncLogMapper.insert(log);
        return true;
    }

    /**
     * 处理资金来源
     *
     * @param sub
     * @param subInfo
     * @param map
     * @return
     */
    private boolean hanlderResouce(Sub sub, SubInfo subInfo, Map<String, SysTable> map) {
        if (StringUtils.isNotEmpty(sub.getZjly())) {
            JSONObject json = JSONObject.parseObject(sub.getZjly());
            for (String key : json.keySet()) {
                if (key.equals("总投资")) {
                    subInfo.setAmtTotal(json.getBigDecimal(key));
                } else {
                    SyncVisit sourceVisit = visitMapper.selectOne(new LambdaQueryWrapper<SyncVisit>().eq(SyncVisit::getOtherTitle, key).eq(SyncVisit::getCat, "2"));
                    if (sourceVisit == null) {
                        SyncLog log = new SyncLog();
                        log.setCat("1").setId(UUID.randomUUID().toString()).setContent(JSONUtil.toJsonStr(sub)).setState("1");
                        log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步项目信息失败:项目名称【%s】和项目代码【%s】,资金来源【%s】未找到", sub.getProjectname(), sub.getProjectid(), sub.getPsorttwoname()));
                        syncLogMapper.insert(log);
                    } else {
                        SysTable source = map.get(sourceVisit.getTitle() + "ZJLY");
                        if (source == null) {
                            SyncLog log = new SyncLog();
                            log.setCat("1").setId(UUID.randomUUID().toString()).setContent(JSONUtil.toJsonStr(sub)).setState("1");
                            log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步项目信息失败:项目名称【%s】和项目代码【%s】,对应资金来源【%s】未找到", sub.getProjectname(), sub.getProjectid(), sourceVisit.getTitle()));
                            syncLogMapper.insert(log);
                            return false;
                        }
                        SubSource subSource = subSourceMapper.selectOne(new LambdaQueryWrapper<SubSource>().eq(SubSource::getSubId, subInfo.getId()).eq(SubSource::getSourceId, source.getId()).eq(SubSource::getLogicDeleteFlag, "0"));
                        if (subSource == null) {
                            if (json.getBigDecimal(key).compareTo(BigDecimal.ZERO) > 0) {
                                subSource = new SubSource();
                                subSource.setId(UUID.randomUUID().toString());
                                subSource.setAmt(json.getBigDecimal(key));
                                subSource.setSubId(subInfo.getId());
                                subSource.setLogicDeleteFlag(0);
                                subSource.setSourceId(source.getId());
                                subSourceMapper.insert(subSource);
                            }
                        } else {
                            subSource.setAmt(json.getBigDecimal(key));
                            if (json.getBigDecimal(key).compareTo(BigDecimal.ZERO) == 0) {
                                subSource.setLogicDeleteFlag(1);
                            }
                            subSourceMapper.updateById(subSource);
                        }
                    }
                }
            }
        }
        return true;

    }

    /**
     * 自动创建账号
     *
     * @param name      用户
     * @param code      统一信用代码
     * @param kind      1:责任单位;2:监管单位
     * @param kindUnit  1-政府机构用户 2-申请单位用户
     * @param loginName 登录名
     * @param role      角色
     * @return
     */
    private Unit autoUnitAndUser(String name, String code, String kind, String kindUnit, String loginName, String role) {
        Unit unit = new Unit();
        unit.setId(UUID.randomUUID().toString());
        unit.setTitle(name);
        unit.setTrustCode(code);
        unit.setLogicDeleteFlag(0);
        unit.setProvince("新疆维吾尔自治区");
        unit.setCity("哈密市");
        //项目单位
        unit.setKind(kind);
        unitMapper.insert(unit);
        //创建用户信息
        String password = "Hm123456";
        CommUser commUser = new CommUser();
        commUser.setId(UUID.randomUUID().toString());
        commUser.setLoginname(loginName);
        commUser.setEnabled(1);
        commUser.setLocked(0);
        commUser.setCreateTime(new Date());
        commUser.setId(UUID.randomUUID().toString());
        byte[] salt = Digests.generateSalt(SecurityStaticValue.SALT_SIZE);
        commUser.setSalt(Encodes.encodeHex(salt));
        byte[] hashPassword = Digests.sha1(password.getBytes(),
                salt, SecurityStaticValue.HASH_INTERATIONS);
        commUser.setPassword(Encodes.encodeHex(hashPassword));
        commUserMapper.insert(commUser);
        //创建用户信息
        SecUser secUser = new SecUser();
        secUser.setId(commUser.getId());
        secUser.setKindUnit(kindUnit);
        //企业简称 设置为 用户真实姓名
        secUser.setTitle(name);
        secUser.setLogicDeleteFlag(false);
        secUser.setLogin(commUser.getLoginname());
        //设置邮箱
        secUser.setIsUnit(true);
        //设置角色
        SecRole secRole = secRoleMapper.selectOne(new LambdaQueryWrapper<SecRole>().eq(SecRole::getCode, role));
        if (secRole != null) {
            secUser.setKind(secRole.getId());
        }
        secUser.setUnitId(unit.getId());
        secUser.setCreateTime(new Date());
        secUserMapper.insert(secUser);
        return unit;
    }

    @Override
    public boolean syncDocument(SubDocument document, String company) {
        //通过项目名字找项目
        List<SubInfo> lstSubInfo = subInfoMapper.selectList(new LambdaQueryWrapper<SubInfo>().eq(SubInfo::getSubName, document.getProjectname()));
        if (lstSubInfo == null || lstSubInfo.size() == 0) {
//           //没找到项目，再通过项目代码去找
            lstSubInfo = subInfoMapper.selectList(new LambdaQueryWrapper<SubInfo>().eq(SubInfo::getSubCode, document.getProjectid()));
        }
        //找到了对应的项目
        if (lstSubInfo.size() > 0) {
            //可能找到多个相同项目，遍历
            for (SubInfo subInfo : lstSubInfo) {
                SubPreNew subPreNew = null;
                //在sync_visit这个对照表找对应的手续进行对照
                List<SyncVisit> flowVistList = visitMapper.selectList(new LambdaQueryWrapper<SyncVisit>().eq(SyncVisit::getOtherTitle, document.getSxzxname()).eq(SyncVisit::getCat, "5"));
                SubPreFlow flow = null;
                //如果对照表没找到，则记录日志
                if (flowVistList.size() <= 0) {
                    SyncLog log = new SyncLog();
                    log.setCat("4").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(document)).setState("1");
                    log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步前期手续信息失败:手续【%s】未找到", document.getSxzxname(), document.getSxzxname()));
                    syncLogMapper.insert(log);
                    return false;
                } else {
                    //如果对照找到了，取第一个
                    SyncVisit flowVist = flowVistList.get(0);
                    flow = subFlowMapper.selectOne(new LambdaQueryWrapper<SubPreFlow>().eq(SubPreFlow::getTitle, flowVist.getTitle()).eq(SubPreFlow::getLogicDeleteFlag, 0));
                }
                if (flow == null) {
                    //再次验证对照的手续
                    SyncLog log = new SyncLog();
                    log.setCat("4").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(document)).setState("1");
                    log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步前期办理手续失败:项目名称【%s】和项目代码【%s】已找到,手续【%s】未找到", document.getProjectname(), document.getProjectid(), document.getSxzxname()));
                    syncLogMapper.insert(log);
                    return false;
                }
                //从项目手续表中获取数据，判断是否存在数据
                subPreNew = subPreNewMapper.selectOne(new LambdaQueryWrapper<SubPreNew>().eq(SubPreNew::getSubId, subInfo.getId()).eq(SubPreNew::getPreFlowId, flow.getId()).eq(SubPreNew::getLogicDeleteFlag, 0));
                boolean isUpdate = true;
                if (subPreNew == null) {
                    //没有找到，则是增加操作
                    isUpdate = false;
                    subPreNew = new SubPreNew();
                    subPreNew.setId(UUID.randomUUID().toString());
                }

                //到对照表中找审批单位
                SyncVisit unitVist = visitMapper.selectOne(new LambdaQueryWrapper<SyncVisit>().eq(SyncVisit::getOtherTitle, document.getDeptname()).eq(SyncVisit::getCat, "4"));
                if (unitVist == null) {
                    SyncLog log = new SyncLog();
                    log.setCat("4").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(document)).setState("1");
                    log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步前期手续信息失败:手续名称【%s】,批复单位【%s】未找到", document.getSxzxname(), document.getDeptname()));
                    syncLogMapper.insert(log);
                    return false;
                }
                //查单位
                Unit unit = unitMapper.selectOne(new LambdaQueryWrapper<Unit>().eq(Unit::getTitle, unitVist.getTitle()));
                if (unit == null) {
                    //自动创建unit账号
                    SyncLog log = new SyncLog();
                    log.setCat("4").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(document)).setState("1");
                    log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步前期手续办理情况失败:手续名称【%s】,审批单位【%s】未找到", document.getSxzxname(), document.getDeptname()));
                    syncLogMapper.insert(log);
                    return false;
                }
                //根据subjectId获取单位名称
                UnitAndTSystableVo unitAndTSystableVo=sysTableMapper.getUnitNameAndUnitId(subInfo.getSubjectId());

                //存在手续
                if (isUpdate) {

                    if (StringUtils.isEmpty(subPreNew.getSubId())){
                        subPreNew.setSubId(subInfo.getId());
                    }
                    if (StringUtils.isEmpty(subPreNew.getPreFlowId())) {
                        subPreNew.setPreFlowId(flow.getId());
                    }
                    if (subPreNew.getCreateTime()==null) {
                        subPreNew.setCreateTime(new Date());
                    }
                    if (subPreNew.getDatePlan()==null) {
                        subPreNew.setDatePlan(document.getApplytime());
                    }
                    if (subPreNew.getDateConfirm()==null) {
                        subPreNew.setDateConfirm(document.getEndfortime());
                    }
                    if (StringUtils.isEmpty(subPreNew.getTransactors())) {
                        subPreNew.setTransactors(document.getUsername());
                    }
                    if (StringUtils.isEmpty(subPreNew.getTransactorsPhone())) {
                        subPreNew.setTransactorsPhone(document.getMobile());
                    }
                    if (subPreNew.getLogicDeleteFlag()==null) {
                        subPreNew.setLogicDeleteFlag(0);
                    }
                    if (subPreNew.getCreateTime()==null) {
                        subPreNew.setCreateTime(new Date());
                    }
                    if (StringUtils.isEmpty(subPreNew.getUnitDesc())) {
                        //默认以平台为主
                        //防止无数据
                        if (StringUtils.isEmpty(subPreNew.getSubUnitId())) {
                            subPreNew.setUnitDesc(unitAndTSystableVo.getUnitName());
                        }
                    }
                    //默认以平台为主
                    if (StringUtils.isEmpty(subPreNew.getSubUnitId())){
                        //防止无数据
                        subPreNew.setSubUnitId(unit.getId());
                    }

                    if (subPreNew.getStatusConf() == null) {
                        if (document.getApplytime() != null) {
                            subPreNew.setStatusConf("1");
                        }
                    }
                    if (subPreNew.getNum1() == null) {
                        subPreNew.setNum1(flow.getNum1());
                    }
                    if (subPreNew.getNum2() == null) {
                        subPreNew.setNum2(flow.getNum2());
                    }
                    if (subPreNew.getNumStage() == null) {
                        subPreNew.setNumStage(flow.getNumStage());
                    }

                    if (document.getEndfortime() != null) {
                        if (StringUtils.isEmpty(subPreNew.getStatusConf())) {
                            subPreNew.setStatusConf("2");
                        }
                        if (subPreNew.getNum3() == null) {
                            subPreNew.setNum3(DateUtils.differentDaysByMillisecond(document.getEndfortime(), document.getApplytime()));
                        }
                    }
/*
                        if (document.getState().equals("3")) {
                            subPreNew.setLogicDeleteFlag(1);
                        }
*/
                    subPreNewMapper.updateById(subPreNew);
                } else {
                    subPreNew.setSubId(subInfo.getId());
                    subPreNew.setPreFlowId(flow.getId());
                    subPreNew.setCreateTime(new Date());
                    subPreNew.setDatePlan(document.getApplytime());
                    subPreNew.setDateConfirm(document.getEndfortime());
                    subPreNew.setTransactors(document.getUsername());
                    subPreNew.setTransactorsPhone(document.getMobile());
                    subPreNew.setLogicDeleteFlag(0);
                    subPreNew.setCreateTime(new Date());
                    //确保单位与平台一致
                    subPreNew.setUnitDesc(unitAndTSystableVo.getUnitName());
                    subPreNew.setSubUnitId(unit.getId());
                    if (document.getApplytime() != null) {
                        subPreNew.setStatusConf("1");
                    }
                    subPreNew.setNum1(flow.getNum1());
                    subPreNew.setNum2(flow.getNum2());
                    subPreNew.setNumStage(flow.getNumStage());
                    if (document.getEndfortime() != null) {
                        subPreNew.setStatusConf("2");
                        subPreNew.setNum3(DateUtils.differentDaysByMillisecond(document.getEndfortime(), document.getApplytime()));
                    }
                    if (document.getState().equals("3")) {
                        subPreNew.setLogicDeleteFlag(1);
                    }
                    subPreNewMapper.insert(subPreNew);
                }
                this.setSubInfoStatus(subInfo);
            }
            SyncLog log = new SyncLog();
            log.setCat("4").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(document)).setState("2");
            log.setCreateTime(DateUtil.date()).setIsHandle("2").setRemark(String.format("同步前期办理手续:项目名称【%s】和项目代码【%s】已找到,手续【%s】已同步", document.getProjectname(), document.getProjectid(), document.getSxzxname()));
            syncLogMapper.insert(log);
            return true;

        } else {
            SyncLog log = new SyncLog();
            log.setCat("4").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(document)).setState("1");
            log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步前期办理手续:项目名称【%s】和项目代码【%s】未找到,手续【%s】未同步", document.getProjectname(), document.getProjectid(), document.getSxzxname()));
            syncLogMapper.insert(log);
            return false;
        }
    }


    @Override
    public boolean syncDoc(SubDoc document, String company) {

        //名称
        List<SubInfo> lstSubInfo = subInfoMapper.selectList(new LambdaQueryWrapper<SubInfo>().eq(SubInfo::getSubName, document.getProjectName()));
        if (lstSubInfo == null || lstSubInfo.size() == 0) {
            lstSubInfo = subInfoMapper.selectList(new LambdaQueryWrapper<SubInfo>().eq(SubInfo::getSubCode, document.getCode()));
        }

        if (lstSubInfo.size() > 0) {
            for (SubInfo subInfo : lstSubInfo) {
                SubPreFlow flow = null;
                SubPreNew subPreNew = null;
                flow = subFlowMapper.selectOne(new LambdaQueryWrapper<SubPreFlow>().eq(SubPreFlow::getTitle, document.getSxzxName()).eq(SubPreFlow::getLogicDeleteFlag, 0));
                if (flow == null) {
                    List<SyncVisit> flowVistList = visitMapper.selectList(new LambdaQueryWrapper<SyncVisit>().eq(SyncVisit::getOtherTitle, document.getSxzxName()).eq(SyncVisit::getCat, "6"));
                    if (flowVistList.size() >= 1) {
                        SyncVisit flowVist = flowVistList.get(0);
                        flow = subFlowMapper.selectOne(new LambdaQueryWrapper<SubPreFlow>().eq(SubPreFlow::getTitle, flowVist.getTitle()).eq(SubPreFlow::getLogicDeleteFlag, 0));
                    }
                }
                if (flow == null) {
                    //自动创建
                    SyncLog log = new SyncLog();
                    log.setCat("4").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(document)).setState("1");
                    log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步前期办理手续失败:项目名称【%s】和项目代码【%s】已找到,手续【%s】未找到", document.getProjectName(), document.getCode(), document.getSxzxName()));
                    syncLogMapper.insert(log);
                    return false;
                }
                subPreNew = subPreNewMapper.selectOne(new LambdaQueryWrapper<SubPreNew>().eq(SubPreNew::getSubId, subInfo.getId()).eq(SubPreNew::getPreFlowId, flow.getId()).eq(SubPreNew::getLogicDeleteFlag, 0));
                boolean isUpdate = true;
                if (subPreNew == null) {
                    isUpdate = false;
                    subPreNew = new SubPreNew();
                    subPreNew.setId(UUID.randomUUID().toString());
                    subPreNew.setCreateTime(new Date());
                    subPreNew.setLastUpdateTime(new Date());
                }
                //查单位
                Unit unit = unitMapper.selectOne(new LambdaQueryWrapper<Unit>().eq(Unit::getTitle, document.getDeptName()));
                if (unit == null) {
                    unit = this.autoUnitAndUser(document.getDeptName(), "", "2", "1", document.getDeptName(), "005");
                }
                UnitAndTSystableVo unitAndTSystableVo=sysTableMapper.getUnitNameAndUnitId(subInfo.getSubjectId());

                if (isUpdate) {
                    if (StringUtils.isEmpty(subPreNew.getSubId())){
                        subPreNew.setSubId(subInfo.getId());
                    }
                    if (StringUtils.isEmpty(subPreNew.getPreFlowId())) {
                        subPreNew.setPreFlowId(flow.getId());
                    }
                    if (subPreNew.getCreateTime()==null) {
                        subPreNew.setCreateTime(new Date());
                    }
                    if (StringUtils.isEmpty(subPreNew.getFileAddre())) {
                        subPreNew.setFileAddre(document.getFileUrl());
                    }
                    if (StringUtils.isEmpty(subPreNew.getFileType())) {
                        subPreNew.setFileType(document.getFileType());
                    }
                    if (subPreNew.getDatePlan()==null) {
                        subPreNew.setDatePlan(document.getApplyTime());
                    }
                    if (subPreNew.getDateConfirm()==null) {
                        subPreNew.setDateConfirm(document.getEndforTime());
                    }
                    if (StringUtils.isEmpty(subPreNew.getTransactors())) {
                        subPreNew.setTransactors(document.getUserName());
                    }
                    if (StringUtils.isEmpty(subPreNew.getTransactorsPhone())) {
                        subPreNew.setTransactorsPhone(document.getMobile());
                    }
                    if (subPreNew.getLogicDeleteFlag()==null) {
                        subPreNew.setLogicDeleteFlag(0);
                    }
                    subPreNew.setLastUpdateTime(new Date());
                    if (StringUtils.isEmpty(subPreNew.getUnitDesc())) {
                        //默认以平台为主
                        //防止无数据
                        if (StringUtils.isEmpty(subPreNew.getSubUnitId())) {
                            subPreNew.setUnitDesc(unitAndTSystableVo.getUnitName());
                        }
                    }
                    //默认以平台为主
                    if (StringUtils.isEmpty(subPreNew.getSubUnitId())){
                        //防止无数据
                        subPreNew.setSubUnitId(unit.getId());
                    }
                    if (document.getApplyTime() != null) {
                        subPreNew.setStatusConf("1");
                    }
                    if (subPreNew.getNum1() == null) {
                        subPreNew.setNum1(flow.getNum1());
                    }
                    if (subPreNew.getNum2() == null) {
                        subPreNew.setNum2(flow.getNum2());
                    }
                    if (subPreNew.getNumStage() == null) {
                        subPreNew.setNumStage(flow.getNumStage());
                    }
                    if (document.getEndforTime() != null) {
                        subPreNew.setStatusConf("2");
                        subPreNew.setNum3(DateUtils.differentDaysByMillisecond(document.getEndforTime(), document.getApplyTime()));
                    }
                    /*if (document.getState().equals("3")) {
                        subPreNew.setLogicDeleteFlag(1);
                    }*/

                    subPreNewMapper.updateById(subPreNew);
                } else {
                    subPreNew.setSubId(subInfo.getId());
                    subPreNew.setPreFlowId(flow.getId());
                    subPreNew.setCreateTime(new Date());
                    subPreNew.setFileAddre(document.getFileUrl());
                    subPreNew.setFileType(document.getFileType());
                    subPreNew.setDatePlan(document.getApplyTime());
                    subPreNew.setDateConfirm(document.getEndforTime());
                    subPreNew.setTransactors(document.getUserName());
                    subPreNew.setTransactorsPhone(document.getMobile());
                    subPreNew.setLogicDeleteFlag(0);
                    subPreNew.setLastUpdateTime(new Date());
                    subPreNew.setUnitDesc(unitAndTSystableVo.getUnitName());
                    subPreNew.setSubUnitId(unit.getId());
                    if (document.getApplyTime() != null) {
                        subPreNew.setStatusConf("1");
                    }
                    subPreNew.setNum1(flow.getNum1());
                    subPreNew.setNum2(flow.getNum2());
                    subPreNew.setNumStage(flow.getNumStage());
                    if (document.getEndforTime() != null) {
                        subPreNew.setStatusConf("2");
                        subPreNew.setNum3(DateUtils.differentDaysByMillisecond(document.getEndforTime(), document.getApplyTime()));
                    }
                    if (document.getState().equals("3")) {
                        subPreNew.setLogicDeleteFlag(1);
                    }
                    subPreNewMapper.insert(subPreNew);
                }
                this.setSubInfoStatus(subInfo);

            }
            SyncLog log = new SyncLog();
            log.setCat("4").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(document)).setState("2");
            log.setCreateTime(DateUtil.date()).setCompany(company).setIsHandle("2").setRemark(String.format("同步前期办理手续:项目名称【%s】和项目代码【%s】已找到,手续【%s】已同步", document.getProjectName(), document.getCode(), document.getSxzxName()));
            syncLogMapper.insert(log);
            return true;

        } else {
            SyncLog log = new SyncLog();
            log.setCat("4").setId(UUID.randomUUID().toString()).setContent(JSONUtil.toJsonStr(document)).setState("1");
            log.setCreateTime(DateUtil.date()).setCompany(company).setIsHandle("1").setRemark(String.format("同步前期办理手续:项目名称【%s】和项目代码【%s】未找到,手续【%s】未同步", document.getProjectName(), document.getCode(), document.getSxzxName()));
            syncLogMapper.insert(log);
            return false;
        }
    }


    @Override
    public boolean SyncDocLog(DocLog tenderLog, String company) {
        //批复文件名称
        List<SubInfo> lstSubInfo = subInfoMapper.selectList(new LambdaQueryWrapper<SubInfo>().eq(SubInfo::getSubName, tenderLog.getTitle()).eq(SubInfo::getLogicDeleteFlag, "0"));
        if (lstSubInfo == null || lstSubInfo.size() == 0) {
            lstSubInfo = subInfoMapper.selectList(new LambdaQueryWrapper<SubInfo>().eq(SubInfo::getSubCode, tenderLog.getCode()).eq(SubInfo::getLogicDeleteFlag, "0"));
        }
        if (lstSubInfo.size() > 0) {
            for (SubInfo subInfo : lstSubInfo) {
                SubPreFlow flow = subFlowMapper.selectOne(new LambdaQueryWrapper<SubPreFlow>().eq(SubPreFlow::getTitle, tenderLog.getDocName()).eq(SubPreFlow::getLogicDeleteFlag, 0));
                if (flow == null) {
                    //自动创建
                    SyncLog log = new SyncLog();
                    log.setCat("4").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(tenderLog)).setState("1");
                    log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步前期办理手续失败:项目名称【%s】和项目代码【%s】已找到,手续【%s】未找到", tenderLog.getTitle(), tenderLog.getCode(), tenderLog.getDocName()));
                    syncLogMapper.insert(log);
                    return false;
                }
                SubPreLog subPreLog = subPreLogMapper.selectOne(new LambdaQueryWrapper<SubPreLog>().eq(SubPreLog::getCreateUserId, tenderLog.getLsh()));
                boolean isUpdate = true;
                if (subPreLog == null) {
                    isUpdate = false;
                    subPreLog = new SubPreLog();
                    subPreLog.setId(UUID.randomUUID().toString());
                }
                subPreLog.setCat(tenderLog.getCat());
                subPreLog.setSubId(subInfo.getId());
                subPreLog.setCreateUserId(tenderLog.getLsh());
                subPreLog.setOpDate(tenderLog.getOpDate());
                subPreLog.setContent(tenderLog.getContent());
                subPreLog.setFlowId(flow.getId());
                subPreLog.setCreateTime(new Date());
                if (isUpdate) {
                    subPreLogMapper.updateById(subPreLog);
                } else {
                    subPreLogMapper.insert(subPreLog);
                }
            }
            SyncLog log = new SyncLog();
            log.setCat("3").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(tenderLog)).setState("2");
            log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步前期办理手续审批记录:项目名称【%s】和项目代码【%s】未找到,手续【%s】已同步", tenderLog.getTitle(), tenderLog.getCode(), "招标投标"));
            syncLogMapper.insert(log);
        } else {
            //将需要手动处理的放入到正式库里面
            SyncLog log = new SyncLog();
            log.setCat("3").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(tenderLog)).setState("1");
            log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步前期办理手续审批记录:项目名称【%s】和项目代码【%s】未找到,手续【%s】未同步", tenderLog.getTitle(), tenderLog.getCode(), "招标投标"));
            syncLogMapper.insert(log);
            return false;
        }
        return true;
    }


    private void setSubInfoStatus(SubInfo subInfo) {
        //如果政府项目办理了项目投资建议书 进入新建库   企业核准或备案 进入新建库
        boolean isHave = false;
        subInfo.setStatus("1");
        if ("1".equals(subInfo.getKindNature())) { //政府投资
            //如果政府项目办理了项目投资建议书  则进入新建库
            int cnt = subPreNewMapper.selectCount(new LambdaQueryWrapper<SubPreNew>().eq(SubPreNew::getSubId, subInfo.getId()).eq(SubPreNew::getLogicDeleteFlag, 0).eq(SubPreNew::getPreFlowId, 1).eq(SubPreNew::getStatusConf, "2"));
            if (cnt > 0) {
                isHave = true;
                subInfo.setStatus("6");
            }
        } else {
            //企业核准或备案 进入新建库
            int cnt = subPreNewMapper.selectCount(new LambdaQueryWrapper<SubPreNew>().eq(SubPreNew::getSubId, subInfo.getId()).eq(SubPreNew::getLogicDeleteFlag, 0).eq(SubPreNew::getPreFlowId, "3").eq(SubPreNew::getStatusConf, "2"));
            if (cnt > 0) {
                subInfo.setStatus("6");
                isHave = true;
            }
            cnt = subPreNewMapper.selectCount(new LambdaQueryWrapper<SubPreNew>().eq(SubPreNew::getSubId, subInfo.getId()).eq(SubPreNew::getLogicDeleteFlag, 0).eq(SubPreNew::getPreFlowId, "5").eq(SubPreNew::getStatusConf, "2"));
            if (cnt > 0) {
                isHave = true;
                subInfo.setStatus("6");
            }
        }
        //如果办理了招投标  自动进入在建库
        int cnt = subPreNewMapper.selectCount(new LambdaQueryWrapper<SubPreNew>().eq(SubPreNew::getSubId, subInfo.getId()).eq(SubPreNew::getLogicDeleteFlag, 0).eq(SubPreNew::getPreFlowId, "16").eq(SubPreNew::getStatusConf, "2"));
        if (cnt > 0) {
            subInfo.setStatus("7");
            subInfo.setLastUpdateTime(new Date());
        } else {
            if (isHave) {
                subInfo.setStatus("6");
            } else {
                subInfo.setStatus("1");
            }
            subInfo.setLastUpdateTime(new Date());
        }

        cnt = subPreNewMapper.selectCount(new LambdaQueryWrapper<SubPreNew>().eq(SubPreNew::getSubId, subInfo.getId()).eq(SubPreNew::getLogicDeleteFlag, 0).in(SubPreNew::getPreFlowId, new int[]{17, 34, 50}).eq(SubPreNew::getStatusConf, "2"));
        if (cnt > 0) {
            subInfo.setStatus("A");
            subInfo.setLastUpdateTime(new Date());
        }
        subInfoMapper.updateById(subInfo);
    }


    @Override
    public boolean syncTender(Tender tender, String company) {
        //批复文件名称
        List<SubInfo> lstSubInfo = subInfoMapper.selectList(new LambdaQueryWrapper<SubInfo>().eq(SubInfo::getSubName, tender.getTitle()).eq(SubInfo::getLogicDeleteFlag, "0"));
        if (lstSubInfo == null || lstSubInfo.size() == 0) {
            lstSubInfo = subInfoMapper.selectList(new LambdaQueryWrapper<SubInfo>().eq(SubInfo::getSubCode, tender.getCode()).eq(SubInfo::getLogicDeleteFlag, "0"));
        }
        if (lstSubInfo.size() > 0) {
            for (SubInfo subInfo : lstSubInfo) {
                SubPreNew subPreNew = null;
                subPreNew = subPreNewMapper.selectOne(new LambdaQueryWrapper<SubPreNew>().eq(SubPreNew::getSubId, subInfo.getId()).eq(SubPreNew::getPreFlowId, "16").eq(SubPreNew::getLogicDeleteFlag, 0));
                boolean isUpdate = true;
                if (subPreNew == null) {
                    isUpdate = false;
                    subPreNew = new SubPreNew();
                    subPreNew.setId(UUID.randomUUID().toString());
                }
                if (isUpdate) {
                    if(StringUtils.isEmpty(subPreNew.getSubId())){
                        subPreNew.setSubId(subInfo.getId());
                    }
                    if (StringUtils.isEmpty(subPreNew.getPreFlowId())){
                        subPreNew.setPreFlowId("16");
                    }
                    if (subPreNew.getCreateTime()==null){
                        subPreNew.setCreateTime(new Date());
                    }
                    if(StringUtils.isEmpty(subPreNew.getFileAddre())) {
                        subPreNew.setFileAddre(tender.getFileUrl());
                    }
                    if (subPreNew==null){
                        subPreNew.setDatePlan(DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", tender.getSiteDate()));
                    }
                    if (subPreNew.getDateConfirm()==null){
                        subPreNew.setDateConfirm(DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", tender.getPublishDate()));
                    }
                    if (StringUtils.isEmpty(subPreNew.getTransactors())){
                        subPreNew.setTransactors(tender.getUser());
                    }
                    if (StringUtils.isEmpty(subPreNew.getTransactors())) {
                        subPreNew.setTransactorsPhone(tender.getPhone());
                    }
                    if (subPreNew.getLogicDeleteFlag()==null){
                        subPreNew.setLogicDeleteFlag(0);
                    }
                    subPreNewMapper.updateById(subPreNew);
                } else {
                    subPreNew.setSubId(subInfo.getId());
                    subPreNew.setPreFlowId("16");
                    subPreNew.setCreateTime(new Date());
                    subPreNew.setFileAddre(tender.getFileUrl());
                    subPreNew.setDatePlan(DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", tender.getSiteDate()));
                    subPreNew.setDateConfirm(DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", tender.getPublishDate()));
                    subPreNew.setTransactors(tender.getUser());
                    subPreNew.setTransactorsPhone(tender.getPhone());
                    subPreNew.setLogicDeleteFlag(0);
                    if (StringUtils.isNotEmpty(tender.getPublishDate())) {
                        subPreNew.setStatusConf("2"); //废标后设置未办理
                    }
                    if (tender.getState().equals("2") || tender.getState().equals("3")) {
                        subPreNew.setLogicDeleteFlag(1);
                    }
                    subPreNewMapper.insert(subPreNew);
                }
                this.setSubInfoStatus(subInfo);
                SyncLog log = new SyncLog();
                log.setCat("2").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(tender)).setState("2");
                log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步招投标信息:项目名称【%s】和项目代码【%s】已同步", tender.getTitle(), tender.getCode()));
                syncLogMapper.insert(log);
            }
        } else {
            SyncLog log = new SyncLog();
            log.setCat("2").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(tender)).setState("1");
            log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步招投标信息异常:项目名称【%s】和项目代码【%s】未找到", tender.getTitle(), tender.getCode()));
            syncLogMapper.insert(log);
            return false;
        }
        return true;
    }

    @Override
    public boolean saveOrUpdate(SubInfo entity) {
        return super.saveOrUpdate(entity);
    }


    @Override
    public boolean SyncTenderLog(TenderLog tenderLog, String company) {
        //批复文件名称
        List<SubInfo> lstSubInfo = subInfoMapper.selectList(new LambdaQueryWrapper<SubInfo>().eq(SubInfo::getSubName, tenderLog.getTitle()).eq(SubInfo::getLogicDeleteFlag, "0"));
        if (lstSubInfo == null || lstSubInfo.size() == 0) {
            lstSubInfo = subInfoMapper.selectList(new LambdaQueryWrapper<SubInfo>().eq(SubInfo::getSubCode, tenderLog.getCode()).eq(SubInfo::getLogicDeleteFlag, "0"));
        }
        if (lstSubInfo.size() > 0) {
            for (SubInfo subInfo : lstSubInfo) {
                SubPreLog subPreLog = new SubPreLog();
                subPreLog.setCat(tenderLog.getCat());
                subPreLog.setSubId(subInfo.getId());
                subPreLog.setOpDate(tenderLog.getOpDate());
                subPreLog.setContent(tenderLog.getContent());
                subPreLog.setFlowId("16");
                subPreLog.setCreateTime(new Date());
                subPreLogMapper.updateById(subPreLog);
            }
            SyncLog log = new SyncLog();
            log.setCat("3").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(tenderLog)).setState("2");
            log.setCreateTime(DateUtil.date()).setIsHandle("2").setRemark(String.format("同步前期办理手续审批记录:项目名称【%s】和项目代码【%s】已找到,手续【%s】已同步", tenderLog.getTitle(), tenderLog.getCode(), "招标投标"));
            syncLogMapper.insert(log);
        } else {
            //将需要手动处理的放入到正式库里面
            SyncLog log = new SyncLog();
            log.setCat("3").setId(UUID.randomUUID().toString()).setCompany(company).setContent(JSONUtil.toJsonStr(tenderLog)).setState("1");
            log.setCreateTime(DateUtil.date()).setIsHandle("1").setRemark(String.format("同步前期办理手续审批记录:项目名称【%s】和项目代码【%s】未找到,手续【%s】未同步", tenderLog.getTitle(), tenderLog.getCode(), "招标投标"));
            syncLogMapper.insert(log);
            return false;
        }
        return true;
    }
}
