package cn.com.tenlion.systembase.service.enterprise.impl;

import cn.com.tenlion.systembase.dao.enterprise.IEnterpriseDao;
import cn.com.tenlion.systembase.pojo.bos.enterprise.EnterpriseBO;
import cn.com.tenlion.systembase.pojo.dtos.bigdta.OrgEnterprise;
import cn.com.tenlion.systembase.pojo.dtos.enterprise.EnterpriseDTO;
import cn.com.tenlion.systembase.pojo.dtos.grid.GridDTO;
import cn.com.tenlion.systembase.pojo.pos.enterprise.EnterprisePO;
import cn.com.tenlion.systembase.pojo.vos.enterprise.EnterpriseVO;
import cn.com.tenlion.systembase.pojo.vos.keyareacheckrenovation.KeyAreaCheckRenovationVO;
import cn.com.tenlion.systembase.service.enterprise.IEnterpriseService;
import cn.com.tenlion.systembase.service.grid.IGridService;
import cn.com.tenlion.systembase.util.VerifyUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import ink.wgink.common.base.DefaultBaseService;
import ink.wgink.exceptions.SearchException;
import ink.wgink.pojo.ListPage;
import ink.wgink.pojo.result.SuccessResultList;
import ink.wgink.util.UUIDUtil;
import ink.wgink.util.map.HashMapUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @ClassName: EnterpriseServiceImpl
 * @Description: 非公有制经济组织
 * @Author: CodeFactory
 * @Date: 2021-11-04 15:22:05
 * @Version: 3.0
 **/
@Service
public class EnterpriseServiceImpl extends DefaultBaseService implements IEnterpriseService {

    @Autowired
    private IEnterpriseDao enterpriseDao;
    @Autowired
    private IGridService gridService;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public void save(EnterpriseVO enterpriseVO) {
        saveReturnId(enterpriseVO);
    }

    @Override
    public void save(String token, EnterpriseVO enterpriseVO) {
        saveReturnId(token, enterpriseVO);
    }

    @Override
    public String saveReturnId(EnterpriseVO enterpriseVO) {
        return saveReturnId(null, enterpriseVO);
    }

    @Override
    public String saveReturnId(String token, EnterpriseVO enterpriseVO) {
        EnterprisePO enterprisePO = getPOByBusinessRegNo(enterpriseVO.getBusinessRegNo());
        if (enterprisePO != null) {
            throw new SearchException("组织机构代码已经存在");
        }

        String enterpriseId = UUIDUtil.getUUID();
        Map<String, Object> params = HashMapUtil.beanToMap(enterpriseVO);
        params.put("enterpriseId", enterpriseId);
        if (StringUtils.isBlank(token)) {
            setSaveInfo(params);
        } else {
            setAppSaveInfo(token, params);
        }
        enterpriseDao.save(params);

        saveKafka(enterpriseId, enterpriseVO);
        return enterpriseId;
    }

    @Override
    public void remove(List<String> ids, String idsStr) {
        remove(null, ids, idsStr);
    }

    @Override
    public void remove(String token, List<String> ids, String idsStr) {
        Map<String, Object> params = getHashMap(2);
        params.put("enterpriseIds", ids);
        if (StringUtils.isBlank(token)) {
            setUpdateInfo(params);
        } else {
            setAppUpdateInfo(token, params);
        }
        enterpriseDao.remove(params);

        deleteKafka(idsStr);
    }

    @Override
    public void delete(List<String> ids) {
        Map<String, Object> params = getHashMap(2);
        params.put("enterpriseIds", ids);
        enterpriseDao.delete(params);
    }

    @Override
    public void update(String enterpriseId, EnterpriseVO enterpriseVO) {
        update(null, enterpriseId, enterpriseVO);
    }

    @Override
    public void update(String token, String enterpriseId, EnterpriseVO enterpriseVO) {
        EnterprisePO enterprisePO = getPOByBusinessRegNo(enterpriseVO.getBusinessRegNo());
        if (enterprisePO != null && !StringUtils.equals(enterpriseId, enterprisePO.getEnterpriseId())) {
            throw new SearchException("组织机构代码已经存在");
        }

        Map<String, Object> params = HashMapUtil.beanToMap(enterpriseVO);
        params.put("enterpriseId", enterpriseId);
        if (StringUtils.isBlank(token)) {
            setUpdateInfo(params);
        } else {
            setAppUpdateInfo(token, params);
        }
        enterpriseDao.update(params);

        updateKafka(enterpriseId, enterpriseVO);
    }

    @Override
    public EnterpriseDTO get(Map<String, Object> params) {
        return enterpriseDao.get(params);
    }

    @Override
    public EnterpriseDTO get(String enterpriseId) {
        Map<String, Object> params = super.getHashMap(2);
        params.put("enterpriseId", enterpriseId);
        return get(params);
    }

    @Override
    public EnterpriseBO getBO(Map<String, Object> params) {
        return enterpriseDao.getBO(params);
    }

    @Override
    public EnterpriseBO getBO(String enterpriseId) {
        Map<String, Object> params = super.getHashMap(2);
        params.put("enterpriseId", enterpriseId);
        return getBO(params);
    }

    @Override
    public EnterprisePO getPO(Map<String, Object> params) {
        return enterpriseDao.getPO(params);
    }

    @Override
    public EnterprisePO getPO(String enterpriseId) {
        Map<String, Object> params = super.getHashMap(2);
        params.put("enterpriseId", enterpriseId);
        return getPO(params);
    }

    @Override
    public EnterprisePO getPOByBusinessRegNo(String businessRegNo) {
        Map<String, Object> params = getHashMap(2);
        params.put("businessRegNo", businessRegNo);
        return getPO(params);
    }

    @Override
    public List<EnterpriseDTO> list(Map<String, Object> params) {
        if(params.get("areaCodeLike") != null && !"".equals(params.get("areaCodeLike").toString())){
            String areaCoed = params.get("areaCodeLike").toString();
            String[] areaCodeSplit = VerifyUtil.splitStringByLength(areaCoed, 2);
            String areaCodeLike = "";
            for(int i = 5 ; i >= 0; i--){
                if(!"00".equals(areaCodeSplit[i])){
                    areaCodeLike = areaCoed.substring(0, (i + 1) * 2 );
                    break;
                }
            }
            params.put("areaCodeLike",areaCodeLike);
        }
        return enterpriseDao.list(params);
    }

    @Override
    public List<EnterpriseBO> listBO(Map<String, Object> params) {
        return enterpriseDao.listBO(params);
    }

    @Override
    public List<EnterprisePO> listPO(Map<String, Object> params) {
        return enterpriseDao.listPO(params);
    }

    @Override
    public SuccessResultList<List<EnterpriseDTO>> listPage(ListPage page) {
        PageHelper.startPage(page.getPage(), page.getRows());
        List<EnterpriseDTO> enterpriseDTOs = list(page.getParams());
        PageInfo<EnterpriseDTO> pageInfo = new PageInfo<>(enterpriseDTOs);
        return new SuccessResultList<>(enterpriseDTOs, pageInfo.getPageNum(), pageInfo.getTotal());
    }

    @Override
    public Integer count(Map<String, Object> params) {
        Integer count = enterpriseDao.count(params);
        return count == null ? 0 : count;
    }

    @Override
    public void saveKafka(String uid, EnterpriseVO enterpriseVO) {
        OrgEnterprise orgEnterprise = setKafkaData(enterpriseVO);
        JSONObject jsonObject = new JSONObject();
        // 实体模板编码
        jsonObject.put("tableNumber", "C0014");
        // 数据主键
        jsonObject.put("uid", uid);
        // 设置数据操作方法
        // action: save/updete/delete
        jsonObject.put("action", "save");
        // 实体
        jsonObject.put("data", orgEnterprise.saveCheckToJson());
        kafkaTemplate.send("tableSync", jsonObject.toJSONString());
    }

    @Override
    public void updateKafka(String uid, EnterpriseVO enterpriseVO) {
        OrgEnterprise orgEnterprise = setKafkaData(enterpriseVO);
        JSONObject jsonObject = new JSONObject();
        // 实体模板编码
        jsonObject.put("tableNumber", "C0014");
        // 数据主键
        jsonObject.put("uid", uid);
        // 设置数据操作方法
        // action: save/updete/delete
        jsonObject.put("action", "update");
        // 实体
        jsonObject.put("data", orgEnterprise.updateToJson());
        kafkaTemplate.send("tableSync", jsonObject.toJSONString());
    }

    @Override
    public void deleteKafka(String uid) {
        JSONObject jsonObject = new JSONObject();
        // 实体模板编码
        jsonObject.put("tableNumber", "C0014");
        // 数据主键
        jsonObject.put("uid", uid);
        // 设置数据操作方法
        // action: save/updete/delete
        jsonObject.put("action", "delete");
        // 实体
        jsonObject.put("data", new OrgEnterprise());
        kafkaTemplate.send("tableSync", jsonObject.toJSONString());
    }

    private OrgEnterprise setKafkaData(EnterpriseVO enterpriseVO) {
        OrgEnterprise orgEnterprise = new OrgEnterprise();
        // 名称
        orgEnterprise.setenterprise_name(enterpriseVO.getEnterpriseName());
        // 类型名称
        orgEnterprise.setenterprise_type_name(enterpriseVO.getEnterpriseTypeName());
        // 地址
        orgEnterprise.setenterprise_address(enterpriseVO.getEnterpriseAddress());
        // 区域全名称(/隔开)
        String locationAll = gridService.getLocationAll(enterpriseVO.getAreaCode());
        orgEnterprise.setlocation_all(locationAll);
        // 区域编码
        orgEnterprise.setlocation_code(enterpriseVO.getAreaCode());
        // 区域旗县区名称
        String locationArea = gridService.getLocationArea(enterpriseVO.getAreaCode());
        orgEnterprise.setlocation_area(locationArea);
        // 经度
        orgEnterprise.setlongitude(enterpriseVO.getEnterpriseLng());
        // 纬度
        orgEnterprise.setlatitude(enterpriseVO.getEnterpriseLat());
        // 网格名称
        orgEnterprise.setgrid_name(enterpriseVO.getGridName());
        // 网格编码
        orgEnterprise.setgrid_code(enterpriseVO.getGridCode());
        return orgEnterprise;
    }

}