package com.gic.haoban.manage.service.service.impl;

import com.alibaba.fastjson.JSON;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.haoban.base.api.common.Constant;
import com.gic.haoban.common.utils.StringUtil;
import com.gic.haoban.manage.api.dto.DepartmentDTO;
import com.gic.haoban.manage.api.dto.DepartmentShortDTO;
import com.gic.haoban.manage.api.enums.WelcomeSuitTypeEnum;
import com.gic.haoban.manage.service.dao.mapper.DepartmentMapper;
import com.gic.haoban.manage.service.dao.mapper.TabHaobanWelcomeSuitRangMapper;
import com.gic.haoban.manage.service.entity.TabHaobanDepartment;
import com.gic.haoban.manage.service.entity.TabHaobanWelcomeSuitRang;
import com.gic.haoban.manage.service.service.DepartmentService;
import com.github.pagehelper.Page;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class DepartmentServiceImpl implements DepartmentService {
    private static final Logger logger = LoggerFactory.getLogger(DepartmentServiceImpl.class);
    @Autowired
    private DepartmentMapper mapper;
    @Autowired
    private TabHaobanWelcomeSuitRangMapper welcomeSuitRangMapper;

    @Override
    public List<TabHaobanDepartment> listByParentId(String parentId) {

        return mapper.listByParentId(parentId);
    }

    @Override
    public TabHaobanDepartment selectById(String departmentId) {

        return mapper.selectByPrimaryKey(departmentId);
    }

    @Override
    public String add(DepartmentDTO department) {
        Date now = new Date();
        TabHaobanDepartment tab = EntityUtil.changeEntityByJSON(TabHaobanDepartment.class, department);
        tab.setDepartmentId(StringUtil.randomUUID());
        Long sort = tab.getSort();
        if (sort == null) {
            long maxSort = mapper.selectMaxSort(department.getParentDepartmentId());
            tab.setSort(maxSort + 1);

        }
        if (StringUtils.isBlank(department.getChainId())) {
            TabHaobanDepartment pDepartment = this.selectById(department.getParentDepartmentId());
            if (null == pDepartment) {
                throw new RuntimeException("父部门不存在");
            }
            tab.setChainId(pDepartment.getChainId() + Constant.ID_SEPARATOR + pDepartment.getDepartmentId());
            tab.setChainName(pDepartment.getChainName() + Constant.NAME_SEPARATOR + pDepartment.getDepartmentName());
            tab.setLevel(pDepartment.getLevel() + 1);

        }
        Integer isStore = department.getIsStore();
        if (isStore == null) {
            department.setIsStore(0);
        }
        tab.setCreateTime(now);
        tab.setUpdateTime(now);
        tab.setStatusFlag(1);
        tab.setRecycleFlag(0);
        if (department.getTempFlag() == null) {
            department.setTempFlag(0);
        }
        mapper.insert(tab);
        try {
            syncWelcomeSuitAddDepartment(tab.getParentDepartmentId(), tab.getDepartmentId(), tab.getDepartmentName(), tab.getWxEnterpriseId());
        } catch (Exception e) {
            logger.error("同步部门-新增欢迎语适用部门信息异常", e);
        }
        return tab.getDepartmentId();

    }

    private void syncWelcomeSuitAddDepartment(String parentDepartmentId, String currentDepartmentId,
                                              String currentDepartmentName, String wxEnterpriseId) {
        logger.info("同步欢迎语适用部门, parentDepartmentId:{}, currentDepartmentId:{}, wxEnterpriseId:{}",
                parentDepartmentId, currentDepartmentId, wxEnterpriseId);
        if (StringUtils.isEmpty(parentDepartmentId)) {
            return;
        }
        // 列举父部门被关联的欢迎语
        TabHaobanWelcomeSuitRang query = new TabHaobanWelcomeSuitRang();
        query.setWxEnterpriseId(wxEnterpriseId);
        query.setSuitDepartmentId(parentDepartmentId);
        query.setDeleteFlag(0);
        List<TabHaobanWelcomeSuitRang> welcomeSuitRangList = welcomeSuitRangMapper.queryAll(query);
        if (CollectionUtils.isEmpty(welcomeSuitRangList)) {
            logger.info("父部门查询为空");
            return;
        }
        logger.info("父部门匹配到的欢迎语适用部门, welcomeSuitRangList:{}", JSON.toJSONString(welcomeSuitRangList));
        // 为每一个父部门匹配到的欢迎语, 添加当前部门适用范围
        welcomeSuitRangList.forEach(one -> {
            TabHaobanWelcomeSuitRang entity = new TabHaobanWelcomeSuitRang();
            entity.setWelcomeSuitRangId(UniqueIdUtils.uniqueLong());
            entity.setWxEnterpriseId(wxEnterpriseId);
            entity.setWelcomeId(one.getWelcomeId());
            entity.setSuitType(WelcomeSuitTypeEnum.DEPARTMENT.getCode());
            entity.setSuitDepartmentId(currentDepartmentId);
            entity.setSuitDepartmentName(currentDepartmentName);
            entity.setSuitStaffId("-1");
            entity.setSuitStaffName("-1");
            entity.setStaffBelongDepartmentId("-1");
            entity.setStaffBelongDepartmentName("-1");
            entity.setSelectType(1);
            entity.setCreateTime(new Date());
            entity.setUpdateTime(new Date());
            entity.setDeleteFlag(0);
            welcomeSuitRangMapper.insert(entity);
        });
    }

    @Override
    public void edit(DepartmentDTO department) {
        Date now = new Date();
        TabHaobanDepartment tab = EntityUtil.changeEntityByJSON(TabHaobanDepartment.class, department);
        tab.setUpdateTime(now);
        mapper.updateByPrimaryKeySelective(tab);
        try {
            syncWelcomeSuitEditDepartment(tab);
        } catch (Exception e) {
            logger.error("同步部门-修改欢迎语适用部门信息异常", e);
        }
    }

    private void syncWelcomeSuitEditDepartment(TabHaobanDepartment tab) {
        if (StringUtils.isEmpty(tab.getWxEnterpriseId())) {
            return;
        }
        // 列举部门被关联的欢迎语
        TabHaobanWelcomeSuitRang query = new TabHaobanWelcomeSuitRang();
        query.setWxEnterpriseId(tab.getWxEnterpriseId());
        query.setSuitDepartmentId(tab.getDepartmentId());
        query.setDeleteFlag(0);
        List<TabHaobanWelcomeSuitRang> welcomeSuitRangList = welcomeSuitRangMapper.queryAll(query);
        if (CollectionUtils.isEmpty(welcomeSuitRangList)) {
            logger.info("部门查询为空");
            return;
        }
        // 更新名称
        welcomeSuitRangList.forEach(one -> {
            one.setUpdateTime(new Date());
            one.setSuitDepartmentName(tab.getDepartmentName());
            welcomeSuitRangMapper.update(one);
        });
    }

    @Override
    public void del(String departmentId) {
        TabHaobanDepartment tab = mapper.selectByPrimaryKey(departmentId);
        if (Objects.isNull(tab)) {
            return;
        }
        tab.setStatusFlag(0);
        tab.setUpdateTime(new Date());
        mapper.updateByPrimaryKeySelective(tab);
        try {
            syncWelcomeSuitDeleteDepartment(departmentId, tab.getWxEnterpriseId());
        } catch (Exception e) {
            logger.error("同步部门-删除欢迎语适用部门信息异常", e);
        }
    }

    private void syncWelcomeSuitDeleteDepartment(String departmentId, String wxEnterperiseId) {
        // 列举部门被关联的欢迎语
        TabHaobanWelcomeSuitRang query = new TabHaobanWelcomeSuitRang();
        query.setWxEnterpriseId(wxEnterperiseId);
        query.setSuitDepartmentId(departmentId);
        query.setDeleteFlag(0);
        List<TabHaobanWelcomeSuitRang> welcomeSuitRangList = welcomeSuitRangMapper.queryAll(query);
        if (CollectionUtils.isEmpty(welcomeSuitRangList)) {
            logger.info("部门查询为空");
            return;
        }
        // 删除
        welcomeSuitRangList.forEach(one -> {
            one.setUpdateTime(new Date());
            one.setDeleteFlag(1);
            welcomeSuitRangMapper.update(one);
        });
    }

    @Override
    public TabHaobanDepartment selectByRelatedId(String relatedId) {
        List<TabHaobanDepartment> list = mapper.selectByRelatedId(relatedId);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public TabHaobanDepartment getByWxId(String wxDepartmentId, String wxEnterpriseId) {
        List<TabHaobanDepartment> list = this.mapper.getByWxId(wxDepartmentId, wxEnterpriseId);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void recycle(String departmentId) {
        TabHaobanDepartment tab = mapper.selectByPrimaryKey(departmentId);
        if (tab != null) {
            tab.setRecycleFlag(1);
            tab.setUpdateTime(new Date());
        }
        mapper.updateByPrimaryKeySelective(tab);
    }

    @Override
    public Page<TabHaobanDepartment> pageDepartmentByParams(String wxEnterpriseId, String keyword, Integer storeFlag, Integer recycleFlag) {

        return mapper.pageDepartmentByParams(wxEnterpriseId, keyword, storeFlag, recycleFlag);
    }


    @Override
    public DepartmentDTO getRootByEnterpriseId(String wxEnterpriseId) {
        TabHaobanDepartment tab = mapper.getRootByEnterpriseId(wxEnterpriseId);
        return EntityUtil.changeEntityByJSON(DepartmentDTO.class, tab);
    }

    @Override
    public Page<TabHaobanDepartment> pageByParentId(String parentId, String keyword) {
        return mapper.pageByParentId(parentId, keyword);
    }

    @Override
    public List<TabHaobanDepartment> listByChainId(String chainId, String wxEnterpriseId) {
        if (StringUtils.isBlank(chainId)) {
            return null;
        }
        return mapper.listByChainId(chainId, wxEnterpriseId);
    }

    @Override
    public Integer departmentRecycleCount(String wxEnterpriseId) {
        return mapper.departmentRecycleCount(wxEnterpriseId);
    }

    @Override
    public int countSyncDepartmentByEnterpriseId(String enterpriseId) {
        return mapper.countSyncDepartmentByEnterpriseId(enterpriseId);
    }

    @Override
    public int countByDepartment(String departmentId) {
        return mapper.countByDepartment(departmentId);
    }

    @Override
    public Integer totalStoreCountByEnterpriseId(String wxEnterpriseId) {
        return mapper.totalStoreCountByEnterpriseId(wxEnterpriseId);
    }

    @Override
    public Integer cleanDepartment(String wxEnterpriseId, List<String> wxDepartmentList) {

        return mapper.cleanDepartment(wxEnterpriseId, wxDepartmentList);
    }

    @Override
    public List<DepartmentDTO> listDepartmentByWxDepartIds(String wxEnterpriseId, List<String> wxDepartmentList) {
        return EntityUtil.changeEntityListByJSON(DepartmentDTO.class, mapper.listDepartmentByWxDepartIds(wxEnterpriseId, wxDepartmentList));
    }

    @Override
    public List<DepartmentShortDTO> searchDepartment(String search, String wxEnterpriseId) {
        return EntityUtil.changeEntityListByJSON(DepartmentShortDTO.class, mapper.searchDepartment(search, wxEnterpriseId));
    }

    @Override
    public List<DepartmentShortDTO> listAllDepartment(String wxEnterpriseId) {
        return EntityUtil.changeEntityListByJSON(DepartmentShortDTO.class, mapper.listAllDepartment(wxEnterpriseId));
    }
}
