package cn.com.ty.lift.enterprise.region.service.impl;

import cn.com.ty.lift.common.model.PushMessage;
import cn.com.ty.lift.common.model.PushUserInfo;
import cn.com.ty.lift.enterprise.push.PushUserService;
import cn.com.ty.lift.enterprise.region.dao.entity.AreaCode;
import cn.com.ty.lift.enterprise.region.dao.entity.Region;
import cn.com.ty.lift.enterprise.region.dao.entity.model.RegionRequest;
import cn.com.ty.lift.enterprise.region.dao.entity.model.RegionResponse;
import cn.com.ty.lift.enterprise.region.dao.mapper.RegionMapper;
import cn.com.ty.lift.enterprise.region.service.RegionService;
import cn.com.xwy.boot.web.dto.RestResponse;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 区域表 服务实现类
 * </p>
 *
 * @author wang-hai-cheng
 * @since 2019-12-09
 */
@Service
@AllArgsConstructor
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements RegionService {
    private final AreaCodeServiceImpl areaCodeService;
    private final PushUserService pushUserService;
    private final JmsMessagingTemplate jmsMessagingTemplate;

    public RestResponse<?> regions(RegionRequest req) {
        Page<RegionResponse> page = new Page<>(req.getPageNum(), req.getPageSize());
        //获取维保团队的区域列表
        IPage<RegionResponse> regions = this.baseMapper.regions(page, req.getMtCompanyId(), req.getName());

        List<RegionResponse> records = regions.getRecords();
        //如果没有区域
        if (records.isEmpty()) {
            return RestResponse.success(page);
        }
        List<Map<String, Object>> projects = baseMapper.selectProjects(req.getMtCompanyId());
        List<Map<String, Object>> areaCodes = baseMapper.selectAreaCodes();

        //遍历区域列表
        for (RegionResponse region : records) {
            region.setProvinceName("无");
            region.setCityName("无");
            //遍历省市列表，将省市的code转化为name
            for (Map<String, Object> area : areaCodes) {
                if (null != region.getProvinceCode() && region.getProvinceCode().equals(area.get("code"))) {
                    region.setProvinceName(area.get("name").toString());
                    continue;
                }
                if (null != region.getCityCode() && region.getCityCode().equals(area.get("code"))) {
                    region.setCityName(area.get("name").toString());
                }
            }

            long projectNum = 0;
            long num = 0;
            //遍历项目列表，获取区域下的项目个数和区域下的总电梯数
            Long id = region.getId();
            for (Map<String, Object> project : projects) {
                if (null != project.get("regionId")) {
                    if (project.get("regionId").equals(id)) {
                        projectNum += 1;
                        //如果项目电梯数量为null,就设置0
                        num += null != project.get("num") ? (long) project.get("num") : 0;
                    }
                }
            }
            region.setProjectNum(projectNum);
            region.setNum(num);
        }
        return RestResponse.success(regions);
    }

    //删除区域，如果区域下没有关联项目
    public RestResponse delete(Region region) {
        Long projectCount = (Long) baseMapper.selectProjectCount(region.getId()).get("count");
        if (projectCount.equals(0L)) {
            if (this.removeById(region.getId())) {
                return RestResponse.success(null, "成功");
            }
        }
        return RestResponse.fail("区域内有项目，无法删除");
    }

    //项目模块用，查询区域列表和它属于的省市名称和code
    public RestResponse projectRegions(Region region) {
        List<Map<String, Object>> regions = this.baseMapper.selectProjectRegions(region.getId());
        if (regions.isEmpty()) {
            return RestResponse.success();
        }
        List<AreaCode> areas = areaCodeService.list();
        for (Map<String, Object> r : regions) {
            for (AreaCode area : areas) {
                //如果区域的城市code等于区中的code，put名字到区域中
                if (null != r.get("cityCode") && r.get("cityCode").equals(area.getCode())) {
                    r.put("city", area.getName());
                    continue;
                }
                //如果区域的省code等于区中的code，put名字到区域中
                if (null != r.get("provinceCode") && r.get("provinceCode").equals(area.getCode())) {
                    r.put("province", area.getName());
                }
            }
        }
        return RestResponse.success(regions);
    }

    //项目模块用，查询区域下的成员列表
    public RestResponse selectRegionUser(Region region) {
        region = this.getById(region.getId());
        if (region == null) {
            return RestResponse.success();
        }
        HashMap<String, Object> result = new HashMap<>();
        if (null != region.getUserId()) {
            List<Map<String, Object>> regionUser = baseMapper.selectRegionMember(region.getUserId().toString());
            if (regionUser.isEmpty()) {
                result.put("regionUser", null);
            } else {
                //区域下，只会有一个区域主管，所以查出来列表，只需要第一个
                result.put("regionUser", regionUser.get(0));
            }
        }
        if (null != region.getClerk() && !"".equals(region.getClerk())) {
            List<Map<String, Object>> regionClerk = baseMapper.selectRegionMember(region.getClerk());
            result.put("regionClerk", regionClerk);
        } else {
            result.put("regionClerk", null);
        }
        return RestResponse.success(result);
    }

    public List<Map<String, Object>> areas(String cityCode) {
        return baseMapper.areas(cityCode);
    }

    public void push(String areaName, String oldUser, String newUser, Region byId, Region region) {
        List<PushUserInfo> userInfos = new ArrayList<>(10);
        //添加企业管理员
        userInfos.addAll(pushUserService.listEnterpriseAdmin(byId.getMtCompanyId()));
        //添加新老区域主管
        userInfos.add(pushUserService.listByUserId(byId.getMtCompanyId(), byId.getUserId()));
        userInfos.add(pushUserService.listByUserId(byId.getMtCompanyId(), region.getUserId()));
        String[] clerkIds = byId.getClerk().replace(" ", "").split(",");
        List<PushUserInfo> clerks = new ArrayList<>();
        if (clerkIds.length > 0 && !"".equals(clerkIds[0])) {
            List<Long> ids = new ArrayList<>();
            for (String clerkId : clerkIds) {
                ids.add(Long.valueOf(clerkId));
            }
            clerks = pushUserService.listByUserIds(byId.getMtCompanyId(), ids);
        }
        //添加区域下的文员
        userInfos.addAll(clerks);
        //推送消息
        PushMessage
                .workReplaceRegionCharger(areaName, oldUser, newUser)
                .sendTokenOnPlatform(jmsMessagingTemplate, userInfos);
    }

    /**
     * 修改区域时，检测新老区域主管，有修改时发送推送消息，修改project_user表内的区域主管信息
     *
     * @param region 区域信息
     * @return 操作结果
     */
    @Transactional(rollbackFor = Exception.class)
    public RestResponse<?> updateByRegionId(Region region) {
        Region byId = this.getById(region);
        //如果区域主管更改了，发推送消息，修改project_user表内的区域主管信息
        if (!byId.getUserId().equals(region.getUserId())) {
            List<Long> projects = baseMapper.selectProjectIdByRegionDirectorId(byId.getUserId(), byId.getMtCompanyId());
            baseMapper.updateRegionDirector(projects, region.getUserId(), byId.getMtCompanyId());
            String oldUser = baseMapper.selectNameByUserId(byId.getUserId());
            String newUser = baseMapper.selectNameByUserId(region.getUserId());
            String areaName = byId.getAreaName();
            this.push(areaName, oldUser, newUser, byId, region);
        }
        return RestResponse.success(this.updateById(region));
    }
}