package com.usky.fire.service.impl;

import ch.qos.logback.core.pattern.FormatInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.fire.domain.DemGridMember;
import com.usky.fire.domain.DemGridMemderVice;
import com.usky.fire.mapper.DemGridMemberMapper;
import com.usky.fire.service.DemGridMemberService;
import com.usky.fire.service.DemGridMemderViceService;
import com.usky.fire.service.util.OnlineMethod;
import com.usky.fire.service.vo.DemGridMemberVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 网格员信息管理表 服务实现类
 * </p>
 *
 * @author JCB
 * @since 2022-11-15
 */
@Service
public class DemGridMemberServiceImpl extends AbstractCrudService<DemGridMemberMapper, DemGridMember> implements DemGridMemberService {

    @Autowired
    private DemGridMemderViceService demGridMemderViceService;

    @Override
    public CommonPage<DemGridMember> gridMemberList(String gridArea, String streetTown, String gridPersonnel, Integer id, Integer pageNum, Integer pageSize) {
        IPage<DemGridMember> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<DemGridMember> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DemGridMember::getDeleteFlag, 0)
                .eq(StringUtils.isNotBlank(streetTown), DemGridMember::getStreetTown, streetTown)
                .eq(id != null&&id != 0, DemGridMember::getId, id)
                .like(StringUtils.isNotBlank(gridArea), DemGridMember::getGridArea, gridArea)
                .like(StringUtils.isNotBlank(gridPersonnel), DemGridMember::getGridPersonnel, gridPersonnel)
                .orderByDesc(DemGridMember::getId);
        page = this.page(page, queryWrapper);
        if (CollectionUtils.isNotEmpty(page.getRecords())) {
            List<Integer> gridMemberId = new ArrayList<>();
            for (int i = 0; i < page.getRecords().size(); i++) {
                gridMemberId.add(page.getRecords().get(i).getId());
            }
            List<DemGridMemderVice> demGridMemderVicesList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(gridMemberId)) {
                demGridMemderVicesList = demGridMemderViceService.gridMemderViceList(gridMemberId);
            }
            if (CollectionUtils.isNotEmpty(demGridMemderVicesList)) {
                for (int i = 0; i < page.getRecords().size(); i++) {
                    List<DemGridMemderVice> gridMemderViceList = new ArrayList<>();
                    for (int j = 0; j < demGridMemderVicesList.size(); j++) {
                        if (page.getRecords().get(i).getId() == demGridMemderVicesList.get(j).getGridMemberId()) {
                            gridMemderViceList.add(demGridMemderVicesList.get(j));
                        }

                    }
                    page.getRecords().get(i).setGridMemderViceList(gridMemderViceList);
                }
            }
        }
        return new CommonPage<>(page.getRecords(), page.getTotal(), pageSize, pageNum);
    }

    @Override
    public List<DemGridMember> gridMemberScatter(String gridArea, String mapGridName, Integer gridGrade, Integer seniorGrid){
        List<DemGridMember> list = new ArrayList<>();
        LambdaQueryWrapper<DemGridMember> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DemGridMember::getDeleteFlag, 0)
                .eq(StringUtils.isNotBlank(gridArea),DemGridMember::getGridArea, gridArea)
                .eq(StringUtils.isNotBlank(mapGridName),DemGridMember::getMapGridName, mapGridName)
                .eq(gridGrade != null,DemGridMember::getGridGrade, gridGrade)
                .eq(seniorGrid != null,DemGridMember::getId, seniorGrid);
        list = this.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            List<Integer> gridMemberId = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                gridMemberId.add(list.get(i).getId());
            }
            List<DemGridMemderVice> demGridMemderVicesList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(gridMemberId)) {
                demGridMemderVicesList = demGridMemderViceService.gridMemderViceList(gridMemberId);
            }
            if (CollectionUtils.isNotEmpty(demGridMemderVicesList)) {
                QueryWrapper<DemGridMember> queryWrapper1 = Wrappers.query();
                queryWrapper1.select("senior_grid as seniorGrid","count(*) as count")
                        .groupBy("senior_grid");
                List<Map<String,Object>> map = this.listMaps(queryWrapper1);

                for (int i = 0; i < list.size(); i++) {
                    List<DemGridMemderVice> gridMemderViceList = new ArrayList<>();
                    for (int j = 0; j < demGridMemderVicesList.size(); j++) {
                        Integer id = list.get(i).getId();
                        Integer id1 = demGridMemderVicesList.get(j).getGridMemberId();
                        if (list.get(i).getId().equals(demGridMemderVicesList.get(j).getGridMemberId())) {
                            gridMemderViceList.add(demGridMemderVicesList.get(j));
                        }

                    }
                    list.get(i).setGridMemderViceList(gridMemderViceList);
                    if(map.size() > 0){
                        for (int j = 0; j < map.size(); j++) {
                            if(list.get(i).getId().equals(Integer.parseInt(map.get(j).get("seniorGrid").toString()))){
                                list.get(i).setNum(Integer.parseInt(map.get(j).get("count").toString()));
                            }
                        }
                    }
                }
            }
        }
        return list;
    }

    @Override
    public List<Map<String ,Object>> gridMemderViceStatistic(){
        QueryWrapper<DemGridMemderVice> queryWrapper = Wrappers.query();
        queryWrapper.select("personnel_type as personnelType","count(*) as count")
                .groupBy("personnel_type");
        List<Map<String,Object>> list = demGridMemderViceService.listMaps(queryWrapper);

        return list;
    }

    @Override
    public List<DemGridMemberVO> gridMemberListExport(String gridArea, String streetTown, String gridPersonnel, Integer id) {
        LambdaQueryWrapper<DemGridMember> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DemGridMember::getDeleteFlag, 0)
                .eq(StringUtils.isNotBlank(streetTown), DemGridMember::getStreetTown, streetTown)
                .eq(id != null&&id != 0, DemGridMember::getId, id)
                .like(StringUtils.isNotBlank(gridArea), DemGridMember::getGridArea, gridArea)
                .like(StringUtils.isNotBlank(gridPersonnel), DemGridMember::getGridPersonnel, gridPersonnel)
                .orderByDesc(DemGridMember::getId);
        List<DemGridMember> list1 = this.list(queryWrapper);
        List<DemGridMemberVO> list = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list1)) {
            List<Integer> gridMemberId = new ArrayList<>();
            for (int i = 0; i < list1.size(); i++) {
                gridMemberId.add(list1.get(i).getId());
            }
            List<DemGridMemderVice> demGridMemderVicesList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(gridMemberId)) {
                demGridMemderVicesList = demGridMemderViceService.gridMemderViceList(gridMemberId);
            }
            for (int i = 0; i < list1.size(); i++) {
                DemGridMemberVO demGridMemberVO = new DemGridMemberVO();
                demGridMemberVO.setGridArea(list1.get(i).getGridArea());
                demGridMemberVO.setStreetTown(list1.get(i).getStreetTown());
                StringBuffer gridPersonStr = new StringBuffer();
                StringBuffer gridPhoneStr = new StringBuffer();
                StringBuffer addPersonStr = new StringBuffer();
                StringBuffer addPhoneStr = new StringBuffer();
                gridPersonStr.append(list1.get(i).getGridPersonnel());
                gridPhoneStr.append(list1.get(i).getGridPhone());
                addPersonStr.append("");
                addPhoneStr.append("");
                if (CollectionUtils.isNotEmpty(demGridMemderVicesList)) {
                    for (int j = 0; j < demGridMemderVicesList.size(); j++) {
                        if (list1.get(i).getId() == demGridMemderVicesList.get(j).getGridMemberId()) {
                            if(demGridMemderVicesList.get(j).getPersonnelType() == 1){
                                gridPersonStr.append(",").append(demGridMemderVicesList.get(j).getPersonnelName());
                                gridPhoneStr.append(",").append(demGridMemderVicesList.get(j).getPhone());
                            }
                            if(demGridMemderVicesList.get(j).getPersonnelType() == 2){
                                addPersonStr.append(demGridMemderVicesList.get(j).getPersonnelName()).append(",");
                                addPhoneStr.append(demGridMemderVicesList.get(j).getPhone()).append(",");

                            }
                        }
                    }
                }
                String gridPerson = gridPersonStr.toString();
                String gridPhone = gridPhoneStr.toString();
                String addPerson = addPersonStr.toString();
                String addPhone = addPhoneStr.toString();

                demGridMemberVO.setGridPersonnel(gridPerson);
                demGridMemberVO.setGridPhone(gridPhone);
                if(StringUtils.isNotBlank(addPerson)){
                    demGridMemberVO.setAddPersonnel(addPerson.substring(0,addPerson.length()-1));
                }
                if(StringUtils.isNotBlank(addPhone)) {
                    demGridMemberVO.setAddPhone(addPhone.substring(0, addPhone.length() - 1));
                }
                demGridMemberVO.setCreateTime((list1.get(i).getCreateTime()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                list.add(demGridMemberVO);
            }

        }
        return list;
    }

    @Transactional
    @Override
    public void addGridMember(DemGridMember demGridMember) {
        demGridMember.setCreator(SecurityUtils.getUsername());
        demGridMember.setCreateTime(LocalDateTime.now());
        demGridMember.setDeleteFlag("0");
        this.save(demGridMember);
        Integer gridMemberId = demGridMember.getId();
        if (CollectionUtils.isNotEmpty(demGridMember.getGridMemderViceList())) {
            for (int i = 0; i < demGridMember.getGridMemderViceList().size(); i++) {
                demGridMember.getGridMemderViceList().get(i).setGridMemberId(gridMemberId);
                demGridMemderViceService.addGridMemderVice(demGridMember.getGridMemderViceList().get(i));
            }
        }
    }

    @Transactional
    @Override
    public void updateGridMember(DemGridMember demGridMember) {
        demGridMember.setUpdatePerson(SecurityUtils.getUsername());
        demGridMember.setUpdateTime(LocalDateTime.now());
        this.updateById(demGridMember);
        if (CollectionUtils.isNotEmpty(demGridMember.getGridMemderViceList())) {
            List<DemGridMemderVice> addList = new ArrayList<>();
            List<DemGridMemderVice> updateList = new ArrayList<>();
            for (int i = 0; i < demGridMember.getGridMemderViceList().size(); i++) {
                if (demGridMember.getGridMemderViceList().get(i).getId() != 0 && demGridMember.getGridMemderViceList().get(i).getId() != null) {
                    updateList.add(demGridMember.getGridMemderViceList().get(i));
                } else {
                    addList.add(demGridMember.getGridMemderViceList().get(i));
                }
            }

            if (CollectionUtils.isNotEmpty(updateList)) {
                List<String> updateIdList1 = new ArrayList<>();
                for (int i = 0; i < updateList.size(); i++) {
                    updateIdList1.add("" + updateList.get(i).getId());
                }
                List<String> updateIdList2 = demGridMemderViceService.gridMemderViceLists(demGridMember.getId());
                if (CollectionUtils.isNotEmpty(updateIdList2)) {
                    List<String> gridMemderViceList = OnlineMethod.subList1(updateIdList2, updateIdList1);
                    if (CollectionUtils.isNotEmpty(gridMemderViceList)) {
                        for (int i = 0; i < gridMemderViceList.size(); i++) {
                            demGridMemderViceService.delGridMemderVice(Integer.parseInt(gridMemderViceList.get(i)));
                        }
                    }
                }

                for (int i = 0; i < updateList.size(); i++) {
                    demGridMemderViceService.updateGridMemderVice(updateList.get(i));
                }
            }

//            新增
            if (CollectionUtils.isNotEmpty(addList)) {
                for (int i = 0; i < addList.size(); i++) {
                    addList.get(i).setGridMemberId(demGridMember.getId());
                    demGridMemderViceService.addGridMemderVice(addList.get(i));
                }
            }
        }
    }

    @Transactional
    @Override
    public void delGridMember(Integer id) {
        DemGridMember demGridMember = new DemGridMember();
        demGridMember.setId(id);
        demGridMember.setDeleteFlag("1");
        this.updateById(demGridMember);
        List<String> memderViceIdList = demGridMemderViceService.gridMemderViceLists(id);
        if (CollectionUtils.isNotEmpty(memderViceIdList)) {
            for (int i = 0; i < memderViceIdList.size(); i++) {
                demGridMemderViceService.delGridMemderVice(Integer.parseInt(memderViceIdList.get(i)));
            }
        }
    }

}
