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.RegionReq;
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.conditions.query.QueryWrapper;
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 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(RegionReq req) {
        Page<Region> page = new Page<>(req.getPageNum(), req.getPageSize());
        //获取维保团队的区域列表
        IPage<Map<String, Object>> regions = this.pageMaps(page,
                new QueryWrapper<Region>()
                        .select("area_name areaName", "area_code areaCode", "city_code cityCode", "remark"
                                , "province_code provinceCode", "clerk", "mt_company_id mtCompanyId"
                                , "user_id userId", "id")
                        .eq("mt_company_id", req.getMtCompanyId())
                        .orderByDesc("create_time"));
        //如果没有区域
        if (page.getRecords().isEmpty()) {
            return RestResponse.success();
        }

        List<Map<String, Object>> records = regions.getRecords();
        List<Map<String, Object>> projects = baseMapper.selectProjects();
        List<Map<String, Object>> areaCodes = baseMapper.selectAreaCodes();
        List<Map<String, Object>> userInfos = baseMapper.selectUserInfo();

        if (records.isEmpty()) {
            return RestResponse.success();
        }

        //遍历区域列表
        for (Map<String, Object> region : records) {
            //遍历用户列表，将user_id替换为name
            if (userInfos.isEmpty()) {
                region.put("name", "无");
            } else {
                userInfos.forEach(userInfo -> {
                    if (null != userInfo.get("userId") && userInfo.get("userId").equals(region.get("userId"))) {
                        region.put("name", userInfo.get("name"));
                    }
                });
            }

            //遍历省市列表，将省市的code转化为name
            for (Map<String, Object> area : areaCodes) {
                if (null != region.get("provinceCode") && region.get("provinceCode").equals(area.get("code"))) {
                    region.put("provinceName", area.get("name"));
                }
                if (null != region.get("cityCode") && region.get("cityCode").equals(area.get("code"))) {
                    region.put("cityName", area.get("name"));
                }
            }

            long projectNum = 0;
            long num = 0;
            //遍历项目列表，获取区域下的项目个数和区域下的总电梯数
            Long id = Long.valueOf(region.get("id").toString());
            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.put("projectNum", projectNum);
            region.put("num", 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());
                }
                //如果区域的省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[] stringIds = byId.getClerk().replace(" ", "").split(",");
        List<PushUserInfo> clerks = new ArrayList<>();
        if (stringIds.length > 0) {
            List<Long> ids = new ArrayList<>();
            for (String stringId : stringIds) {
                ids.add(Long.valueOf(stringId));
            }
            clerks = pushUserService.listByUserIds(byId.getMtCompanyId(), ids);
        }
        //添加区域下的文员
        userInfos.addAll(clerks);
        //推送消息
        PushMessage
                .workReplaceRegionCharger(areaName, oldUser, newUser)
                .sendTokenOnPlatform(jmsMessagingTemplate, userInfos);
    }
}