/*
 * Copyright (c) 2024 codvision.com All Rights Reserved.
 */

package com.codvision.basic.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codvision.auth.entity.vo.OrgVO;
import com.codvision.auth.mapper.OrgMapper;
import com.codvision.authcore.bean.SysUserBean;
import com.codvision.authcore.util.AuthUtil;
import com.codvision.basic.entity.Enterprise;
import com.codvision.basic.entity.inspection.InspectionTarget;
import com.codvision.basic.entity.inspection.InspectionTask;
import com.codvision.basic.entity.vo.EnterpriseVO;
import com.codvision.basic.mapper.EnterpriseMapper;
import com.codvision.basic.mapper.inspection.InspectionTargetMapper;
import com.codvision.basic.mapper.inspection.InspectionTaskMapper;
import com.codvision.basic.service.EnterpriseService;
import com.codvision.commoncore.exception.BusinessException;
import com.codvision.webcore.bean.QueryPage;
import com.codvision.webcore.util.QueryPageUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * @author KX
 */
@Service
@RequiredArgsConstructor
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, Enterprise> implements EnterpriseService {

    private final OrgMapper orgMapper;
    private final InspectionTaskMapper inspectionTaskMapper;
    private final InspectionTargetMapper inspectionTargetMapper;

    @Override
    @SuppressWarnings("all")
    public IPage<EnterpriseVO> getPageResult(QueryPage<Map<String, Object>> queryPage) {
        SysUserBean currentUser = AuthUtil.getCurrentUser();
        Map<String, Object> paraMap = QueryPageUtil.queryMap(queryPage);
        if (!paraMap.containsKey("oid") || paraMap.get("oid") == null) {
            paraMap.put("oid", currentUser.getActiveOid());
        }
        return getBaseMapper().getPageResult(queryPage.getPage(), paraMap);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addEnterprise(Enterprise enterprise) {
        if (getBaseMapper().countEnterpriseByCreditCode(enterprise) > 0) {
            throw new BusinessException("该统一社会信用代码已存在，请勿重复录入！");
        }
        updateDistrict(enterprise);
        addInspectionTarget(enterprise);
        getBaseMapper().insert(enterprise);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEnterprise(Enterprise enterprise) {
        if (getBaseMapper().countEnterpriseByCreditCode(enterprise) > 0) {
            throw new BusinessException("该统一社会信用代码已存在，请勿重复录入！");
        }
        updateDistrict(enterprise);
        addInspectionTarget(enterprise);
        getBaseMapper().updateById(enterprise);
    }

    /**
     * 根据所选组织查询行政区划编码，更新行政地区信息
     * @param enterprise 企业信息
     */
    public void updateDistrict(Enterprise enterprise) {
        OrgVO orgVO = orgMapper.getByOid(enterprise.getOid());
        if (orgVO == null || StringUtils.isEmpty(orgVO.getDistrictCode())) {
            return;
        }
        String[] split = orgVO.getPath().split("/");
        if (orgVO.getDistrictCode().length() == 15) {
            // 网格级别
            enterprise.setGridCode(orgVO.getDistrictCode());
            for (int i = split.length - 1; i >= 0; i--) {
                if (i == split.length - 1) {
                    enterprise.setGrid(split[i]);
                } else if (i == split.length - 2) {
                    enterprise.setCommunity(split[i]);
                } else if (i == split.length - 3) {
                    enterprise.setTown(split[i]);
                } else if (i == split.length - 4) {
                    enterprise.setCounty(split[i]);
                } else if (i == split.length - 5) {
                    enterprise.setCity(split[i]);
                }
            }
        } else if (orgVO.getDistrictCode().length() == 12) {
            // 社区
            for (int i = split.length - 1; i >= 0; i--) {
                if (i == split.length - 1) {
                    enterprise.setCommunity(split[i]);
                } else if (i == split.length - 2) {
                    enterprise.setTown(split[i]);
                } else if (i == split.length - 3) {
                    enterprise.setCounty(split[i]);
                } else if (i == split.length - 4) {
                    enterprise.setCity(split[i]);
                }
            }
        } else if (orgVO.getDistrictCode().length() == 9) {
            // 镇街
            for (int i = split.length - 1; i >= 0; i--) {
                if (i == split.length - 1) {
                    enterprise.setTown(split[i]);
                } else if (i == split.length - 2) {
                    enterprise.setCounty(split[i]);
                } else if (i == split.length - 3) {
                    enterprise.setCity(split[i]);
                }
            }
        } else if (orgVO.getDistrictCode().length() == 6) {
            // 区县
            for (int i = split.length - 1; i >= 0; i--) {
                if (i == split.length - 1) {
                    enterprise.setCounty(split[i]);
                } else if (i == split.length - 2) {
                    enterprise.setCity(split[i]);
                }
            }
        }
    }

    /**
     * 判断是否新增检查对象
     * @param enterprise 企业信息
     */
    private void addInspectionTarget(Enterprise enterprise) {
        if (StringUtils.isEmpty(enterprise.getEnterpriseTags())) {
            return;
        }
        for (InspectionTask inspectionTask : inspectionTaskMapper.getTaskByCheckTag("ENTERPRISE", enterprise.getEnterpriseTags())) {
            InspectionTarget exist = inspectionTargetMapper.selectOne(Wrappers.<InspectionTarget>lambdaQuery().eq(InspectionTarget::getTaskId, inspectionTask.getId()).eq(InspectionTarget::getTargetCode, enterprise.getCreditCode()));
            if (exist == null) {
                InspectionTarget inspectionTarget = new InspectionTarget();
                inspectionTarget = updateInspectionTarget(inspectionTarget, enterprise);
                inspectionTarget.setTaskId(inspectionTask.getId());
                inspectionTargetMapper.insert(inspectionTarget);
            } else {
                exist = updateInspectionTarget(exist, enterprise);
                exist.setTaskId(inspectionTask.getId());
                inspectionTargetMapper.updateById(exist);
            }
        }
    }

    public InspectionTarget updateInspectionTarget(InspectionTarget inspectionTarget, Enterprise enterprise) {
        inspectionTarget.setFlagActive(1);
        inspectionTarget.setCategory("ENTERPRISE");
        inspectionTarget.setDataSource("1");
        inspectionTarget.setTargetName(enterprise.getName());
        inspectionTarget.setTargetCode(enterprise.getCreditCode());
        inspectionTarget.setTargetAddress(enterprise.getSourceAddress());
        inspectionTarget.setTargetAlias(enterprise.getName());
        inspectionTarget.setOid(enterprise.getOid());
        inspectionTarget.setRemark(enterprise.getRemark());
        inspectionTarget.setTagIdList(enterprise.getEnterpriseTags());
        inspectionTarget.setLegalPersonName(enterprise.getLegalPersonName());
        inspectionTarget.setLegalPersonPhone(enterprise.getLegalPersonPhone());
        return inspectionTarget;
    }
}
