package cn.superdesk.uniorder.service.organisation.impl;

import cn.hutool.core.date.DateUtil;
import cn.superdesk.app.supercloud.dto.receive.organisation.OrganizationReceiveParam;
import cn.superdesk.data.extract.enums.opCenter.OpCenterBizPlatformEnum;
import cn.superdesk.uniorder.common.enums.common.CommonSoftDeleteEnum;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.lamda.AnLamdaUtils;
import cn.superdesk.uniorder.common.numerical.AnBeanUtils;
import cn.superdesk.uniorder.common.numerical.AnCollectionUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.dao.entity.organisation.SysOrganization;
import cn.superdesk.uniorder.dao.entity.organisation.SysOrganizationExample;
import cn.superdesk.uniorder.dao.mapper.organisation.SysOrganizationMapper;
import cn.superdesk.uniorder.dao.mapper.organisation.SysOrganizationMapperEx;
import cn.superdesk.uniorder.dto.param.operationCenter.base.OperationCenterParam;
import cn.superdesk.uniorder.dto.param.organisation.SysOrgQueryParam;
import cn.superdesk.uniorder.dto.vo._function.select.SelectOptionOrg;
import cn.superdesk.uniorder.dto.vo.sys.SysOrgVo;
import cn.superdesk.uniorder.dto.vo.sys.SysSelectVo;
import cn.superdesk.uniorder.event.CommonEventPublisher;
import cn.superdesk.uniorder.service.organisation.SysOrganizationService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SysOrganizationServiceImpl implements SysOrganizationService {


    @Autowired
    private SysOrganizationMapper   sysOrganizationMapper;
    @Autowired
    private SysOrganizationMapperEx sysOrganizationMapperEx;

    @Autowired
    private CommonEventPublisher commonEventPublisher;


    @Override
    public int insertSelective(SysOrganization t) {
        return sysOrganizationMapper.insertSelective(t);

    }

    @Override
    public int updateByPrimaryKeySelective(SysOrganization t) {
        return sysOrganizationMapper.updateByPrimaryKey(t);

    }

    @Override
    public void deleteObj(Long id) {


    }

    /**
     * 特指统一订单的 项目id
     *
     * @param id
     * @return
     */
    @Override
    public SysOrganization findById(Long id) {
        return sysOrganizationMapper.selectByPrimaryKey(id);
    }


    @Override
    public List<SysOrganization> findAll(Map<String, Object> queryMap) {

        return null;
    }

    @Override
    public PageInfo<SysOrganization> findByPaging(Map<String, Object> params,
                                                  Integer pageNo, Integer pageSize) {

        return null;
    }

    /**
     * 特指第三方的 项目id
     *
     * @param outOrgId
     * @return
     */
    @Override
    public List<SysOrganization> findByOutOrgId(Long outOrgId) {

        return sysOrganizationMapperEx.findByOutOrgId(outOrgId);
    }

    @Override
    public List<SysOrganization> findByOutOrgIds(List<Long> outOrgIds) {

        SysOrganizationExample example = new SysOrganizationExample();
        example.createCriteria()
                .andOrganizationIdIn(outOrgIds);
        List<SysOrganization> result = sysOrganizationMapper.selectByExample(example);
        return result;
    }

    @Override
    public List<String> convertOutOrgIds2OrgNames(List<Long> outOrgIds) {

        List<String> result = new ArrayList<>();

        List<SysOrganization> sysOrganizationList = findByOutOrgIds(outOrgIds);

        if (AnCollectionUtils.isNotEmpty(sysOrganizationList)) {
            result = sysOrganizationList.stream().filter(AnLamdaUtils.distinctByKey(o -> o.getOrganizationId())).map(SysOrganization::getOrganizationName).collect(Collectors.toList());
        }

        return result;
    }

    @Override
    public List<SysOrganization> findByOutOrgName(String outOrgName) {

        return sysOrganizationMapperEx.findByOutOrgName(outOrgName);
    }

    /**
     * 有效 经纬度
     *
     * @param outOrgName
     * @return
     */
    @Override
    public List<SysOrganization> findByTvHeadData() {

        SysOrganizationExample example = new SysOrganizationExample();
        example.createCriteria()
                .andLatIsNotNull()
                .andLngIsNotNull();
        List<SysOrganization> result = sysOrganizationMapper.selectByExample(example);
        return result;
    }

    /***
     * 项目下拉列表-daizhi 19-0808
     */
    @Override
    public R<List<SelectOptionOrg>> getProjectSelect(Map<String, Object> params, int pageNo, int pageSize) {

        PageHelper.startPage(pageNo, pageSize);

        List<SelectOptionOrg>     ls   = sysOrganizationMapperEx.getProjectSelect(params);
        PageInfo<SelectOptionOrg> page = new PageInfo<SelectOptionOrg>(ls);

        PageHelper.clearPage();

        return new R<List<SelectOptionOrg>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), ls);

    }

    /**
     * 特指第三方的 项目id
     *
     * @param outOrgId
     * @return
     */
    @Override
    public SysOrganization getByOutOrgId(Long outOrgId) {

        return sysOrganizationMapperEx.getByOutOrgId(outOrgId);
    }

    private void convertOrganizationReceiveParam2Entity(OrganizationReceiveParam organizationReceiveParam, SysOrganization sysOrganization) {

        sysOrganization.setOrganizationId(organizationReceiveParam.getId().longValue());
        sysOrganization.setOrganizationNo(organizationReceiveParam.getCode());
        sysOrganization.setOrganizationName(organizationReceiveParam.getName());

        // add 20200927
        /****************************************** add 企业 扩展信息 地理位置 start ******************************************/
        sysOrganization.setProvinceCode(organizationReceiveParam.getProvinceCode());
        sysOrganization.setProvinceName(organizationReceiveParam.getProvinceName());
        sysOrganization.setCityCode(organizationReceiveParam.getCityCode());
        sysOrganization.setCityName(organizationReceiveParam.getCityName());
        sysOrganization.setAddress(organizationReceiveParam.getAddress());
        sysOrganization.setLng(organizationReceiveParam.getLng());
        sysOrganization.setLat(organizationReceiveParam.getLat());
        /****************************************** add 企业 扩展信息 地理位置   end ******************************************/

        sysOrganization.setOtherField1(organizationReceiveParam.getCityCode());
        sysOrganization.setOtherField2(organizationReceiveParam.getCityName());

        /****************************************** 添加软删除 at 20201130 start ******************************************/
        if (null != organizationReceiveParam.getEnabled()) {
            sysOrganization.setDeleted(organizationReceiveParam.getEnabled().equals(1) ? 0 : 1);
        } else {
            // 默认为未删除
            sysOrganization.setDeleted(CommonSoftDeleteEnum.正常.getKey());
        }

        sysOrganization.setSyncTime(DateUtil.date());

        /****************************************** 添加软删除 at 20201130 start ******************************************/

        /****************************************** 添加业务平台、运营商 at 20230412 start ******************************************/
        sysOrganization.setBizPlatformCode(OpCenterBizPlatformEnum.服务之窗.getCode());
        sysOrganization.setBizPlatformName(OpCenterBizPlatformEnum.服务之窗.getName());
        sysOrganization.setBizOperatorId(organizationReceiveParam.getCompId());
        /****************************************** 添加业务平台、运营商 at 20230412 end ******************************************/
    }

    @Override
    public void mergeReceiveOrganization(String message) {

        try {
            OrganizationReceiveParam organizationReceiveParam = AnJsonUtils.toObject(message, OrganizationReceiveParam.class);

            log.info(AnJsonUtils.toJson(organizationReceiveParam));

            List<SysOrganization> sysOrganizationList = sysOrganizationMapperEx.findByOutOrgId(organizationReceiveParam.getId().longValue());

            SysOrganization sysOrganization = null;
            SysOrganization snapshot        = null;

            if (AnCollectionUtils.isNotEmpty(sysOrganizationList)) {
                sysOrganization = sysOrganizationList.get(0);
                snapshot = AnBeanUtils.copy(sysOrganization, SysOrganization.class);
            }

            if (null == sysOrganization) {

                sysOrganization = new SysOrganization();
                convertOrganizationReceiveParam2Entity(organizationReceiveParam, sysOrganization);
                sysOrganizationMapper.insert(sysOrganization);

            } else {

                convertOrganizationReceiveParam2Entity(organizationReceiveParam, sysOrganization);
                sysOrganizationMapper.updateByPrimaryKeySelective(sysOrganization);
            }

            // TODO 更新订单 项目信息-项目名
            commonEventPublisher.triggerOrganizationEvent(sysOrganization, snapshot);


        } catch (Exception e) {

            e.printStackTrace();
            log.error("新系统 同步 旧系统-Organization 失败:{}", e.getMessage());

        }

    }

    @Override
    public void deleteReceiveOrganization(String message) {

        OrganizationReceiveParam organizationReceiveParam = AnJsonUtils.toObject(message, OrganizationReceiveParam.class);

        List<SysOrganization> sysOrganizationList = sysOrganizationMapperEx.findByOutOrgId(organizationReceiveParam.getId().longValue());

        // 这样删除 好像是有点问题 mark by linjinyu at 20201130
        if (AnCollectionUtils.isNotEmpty(sysOrganizationList)) {
            for (SysOrganization item : sysOrganizationList) {

                // 修改为以下
//				sysOrganizationMapper.deleteByPrimaryKey(item.getId());

                /****************************************** 添加软删除 at 20201130 start ******************************************/

                SysOrganization update4SoftDelete = new SysOrganization();
                update4SoftDelete.setId(item.getId());
                update4SoftDelete.setDeleted(CommonSoftDeleteEnum.删除.getKey());
                sysOrganizationMapper.updateByPrimaryKeySelective(update4SoftDelete);

                /****************************************** 添加软删除 at 20201130   end ******************************************/

            }
        }
    }


    @Override
    public Long countOutOrg() {
        SysOrganizationExample example = new SysOrganizationExample();
        return sysOrganizationMapper.countByExample(example);

    }

    @Override
    public List<SysOrgVo> getOrgList(SysOrgQueryParam param) {
        return sysOrganizationMapper.getOrgList(param);
    }



    @Override
    public List<SysSelectVo> selectOrgList(Map<String, Object> params) {
        return  sysOrganizationMapper.selectOrgList(params);
    }

    @Override
    public List<SysSelectVo> getOrgListByEnterprise(SysOrgQueryParam params) {
        return sysOrganizationMapper.getOrgListByEnterprise(params);
    }

    /**
     *  福利商城 和 服务之窗
     *  项目来源不同
     *  福利商城-通过企业表 获取
     *  服务之窗-通过项目表 获取
     */
    @Override
    public List<SysSelectVo> selectOrgListByPlatform(SysOrgQueryParam params) {
        //判断 运营商 是那个平台
        //福利商城 通过企业去找项目
        if (OpCenterBizPlatformEnum.福利商城.getCode().equals(params.getBizPlatformCode())) {
            return 	getOrgListByEnterprise(params);
        }else {
            Map<String, Object> conditions = new HashMap<>();
            conditions.put("compId", params.getCompId());
            conditions.put("bizPlatformCode", params.getBizPlatformCode());

            return selectOrgList(conditions);
        }
    }
}
