package com.ruoyi.system.service.task.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.system.domain.grid.*;
import com.ruoyi.system.domain.task.TkCommonYinhuan;
import com.ruoyi.system.domain.task.TkCommonYinhuanBind;
import com.ruoyi.system.domain.task.dto.TkCommonYinhuanParam;
import com.ruoyi.system.domain.task.enums.TkYinhunBindTypeEnum;
import com.ruoyi.system.domain.task.request.TkCommonYinhuanAddRequest;
import com.ruoyi.system.domain.task.request.TkCommonYinhuanQueryRequest;
import com.ruoyi.system.domain.task.vo.TkCommonYinhuanVO;
import com.ruoyi.system.mapper.task.TkCommonYinhuanBindMapper;
import com.ruoyi.system.mapper.task.TkCommonYinhuanMapper;
import com.ruoyi.system.service.grid.GridCompanyService;
import com.ruoyi.system.service.grid.GridHouseService;
import com.ruoyi.system.service.grid.GridPeopleService;
import com.ruoyi.system.service.grid.GridShopService;
import com.ruoyi.system.service.system.ISysDeptService;
import com.ruoyi.system.service.task.TkCommonYinhuanService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author User
* @description 针对表【tk_common_yinhuan(工单 隐患矛盾)】的数据库操作Service实现
* @createDate 2024-06-14 14:41:23
*/
@Service
public class TkCommonYinhuanServiceImpl extends ServiceImpl<TkCommonYinhuanMapper, TkCommonYinhuan> implements TkCommonYinhuanService{
    @Resource
    private TkCommonYinhuanBindMapper yinhuanBindMapper;
    @Resource
    private TkCommonYinhuanMapper yinhuanMapper;
    @Resource
    private ISysDeptService deptService;
    @Resource
    private GridPeopleService gridPeopleService;
    @Resource
    private GridShopService gridShopService;
    @Resource
    private GridHouseService gridHouseService;
    @Resource
    private GridCompanyService gridCompanyService;

    @Override
    @Transactional
    public void add(TkCommonYinhuanAddRequest request,String creator) {
        TkCommonYinhuan yinhuan = BeanUtil.toBean(request,TkCommonYinhuan.class);
        if (yinhuan.getId() == null){
            yinhuan.setCreateTime(LocalDateTime.now());
            yinhuan.setCreator(creator);
            yinhuan.setDeleteFlag(false);
            this.save(yinhuan);
        }else {
            yinhuan.setUpdateTime(LocalDateTime.now());
            this.updateById(yinhuan);
        }
        this.saveBind(request.getBindList(),yinhuan.getId());
    }

    private void saveBind(List<TkCommonYinhuanAddRequest.Bind> bindList,Long yinhuanId){
        yinhuanBindMapper.delete(
                Wrappers.<TkCommonYinhuanBind>lambdaQuery().eq(TkCommonYinhuanBind::getYinhuanId,yinhuanId)
        );
        if (CollectionUtils.isEmpty(bindList)){
            return;
        }
        for (TkCommonYinhuanAddRequest.Bind bind : bindList) {
            TkCommonYinhuanBind b = new TkCommonYinhuanBind();
            b.setYinhuanId(yinhuanId);
            b.setBindType(bind.getBindType());
            b.setBindId(bind.getBindId());
            b.setCreateTime(LocalDateTime.now());
            yinhuanBindMapper.insert(b);
        }
    }

    @Override
    public void cancel(Long id) {
        this.update(
                Wrappers.<TkCommonYinhuan>lambdaUpdate()
                        .eq(TkCommonYinhuan::getId,id)
                        .set(TkCommonYinhuan::getDeleteFlag,true)
        );
    }

    @Override
    public TkCommonYinhuanVO getVOById(Long id) {
        TkCommonYinhuan yinhuan = this.getById(id);
        return this.toVO(Lists.newArrayList(yinhuan)).get(0);
    }

    @Override
    public IPage<TkCommonYinhuanVO> pageVO(TkCommonYinhuanQueryRequest request) {
        TkCommonYinhuanParam param = new TkCommonYinhuanParam();
        param.setTitle(request.getTitle());
        param.setDangerFlag(request.getDangerFlag());
        param.setBindId(request.getBindId());
        param.setBindType(request.getBindType());
        IPage<TkCommonYinhuan> page = yinhuanMapper.page(
                new Page<>(request.getPageNum(),request.getPageSize()),
                param
        );
        return new Page<TkCommonYinhuanVO>(page.getCurrent(),page.getSize(),page.getTotal()).setRecords(this.toVO(page.getRecords()));
    }

    private List<TkCommonYinhuanVO> toVO(List<TkCommonYinhuan> list){
        if (CollectionUtils.isEmpty(list)){
            return Collections.emptyList();
        }
        List<Long> deptIds = list.stream().map(TkCommonYinhuan::getDepId).filter(Objects::nonNull).collect(Collectors.toList());
        List<SysDept> depts = deptService.selectDeptByIds(deptIds);
        List<TkCommonYinhuanVO.Bind> bindList = this.listBind(
                list.stream().map(TkCommonYinhuan::getId).collect(Collectors.toList())
        );
        List<TkCommonYinhuanVO> vos = Lists.newArrayList();
        for (TkCommonYinhuan yinhuan : list) {
            TkCommonYinhuanVO vo = BeanUtil.toBean(yinhuan,TkCommonYinhuanVO.class);
            if (yinhuan.getDepId()!=null){
                depts.stream().filter(d -> d.getDeptId().equals(yinhuan.getDepId())).findAny().ifPresent(dept -> vo.setDepName(dept.getDeptName()));
            }
            vo.setBindList(
                    bindList.stream().filter(b->b.getYinhuanId().equals(yinhuan.getId())).collect(Collectors.toList())
            );
            vos.add(vo);
        }
        return vos;
    }

    private List<TkCommonYinhuanVO.Bind> listBind(List<Long> yinhuanIds){
        if (CollectionUtils.isEmpty(yinhuanIds)){
            return Collections.emptyList();
        }
        List<TkCommonYinhuanBind> bindList = yinhuanBindMapper.selectList(
                Wrappers.<TkCommonYinhuanBind>lambdaQuery().in(TkCommonYinhuanBind::getYinhuanId,yinhuanIds)
        );
        //人口
        List<String> personIds = bindList.stream().filter(
                b-> TkYinhunBindTypeEnum.RK.getCode().equals(b.getBindType())
        ).map(TkCommonYinhuanBind::getBindId).collect(Collectors.toList());
        GridPeopleExample peopleExample = new GridPeopleExample();
        peopleExample.createCriteria().andIdIn(personIds);
        List<GridPeople> peopleList = personIds.isEmpty()?Collections.emptyList():gridPeopleService.selectByExample(peopleExample);
        //住宅
        List<String> houseIds = bindList.stream().filter(
                b-> TkYinhunBindTypeEnum.ZZ.getCode().equals(b.getBindType())
        ).map(TkCommonYinhuanBind::getBindId).collect(Collectors.toList());
        GridHouseExample houseExample = new GridHouseExample();
        houseExample.createCriteria().andIdIn(houseIds);
        List<GridHouse> houseList = houseIds.isEmpty()?Collections.emptyList():gridHouseService.selectByExample(houseExample);
        //企业
        List<String> companyIds = bindList.stream().filter(
                b-> TkYinhunBindTypeEnum.QY.getCode().equals(b.getBindType())
        ).map(TkCommonYinhuanBind::getBindId).collect(Collectors.toList());
        GridCompanyExample companyExample = new GridCompanyExample();
        companyExample.createCriteria().andIdIn(companyIds);
        List<GridCompany> companyList =companyIds.isEmpty()?Collections.emptyList():gridCompanyService.selectByExample(companyExample);
        //商铺
        List<Long> shopIds = bindList.stream().filter(
                b-> TkYinhunBindTypeEnum.SP.getCode().equals(b.getBindType())
        ).map(TkCommonYinhuanBind::getBindId).map(Long::valueOf).collect(Collectors.toList());
        GridShopExample shopExample = new GridShopExample();
        shopExample.createCriteria().andIdIn(shopIds);
        List<GridShop> shopList = shopIds.isEmpty()?Collections.emptyList():gridShopService.selectByExample(shopExample);

        List<TkCommonYinhuanVO.Bind> binds = Lists.newArrayList();
        for (TkCommonYinhuanBind tkCommonYinhuanBind : bindList) {
            TkCommonYinhuanVO.Bind bind = new TkCommonYinhuanVO.Bind();
            bind.setBindType(tkCommonYinhuanBind.getBindType());
            bind.setBindId(tkCommonYinhuanBind.getBindId());
            if (TkYinhunBindTypeEnum.RK.getCode().equals(tkCommonYinhuanBind.getBindType())){
                peopleList.stream().filter(p->p.getId().equals(bind.getBindId())).findFirst().ifPresent(p->{
                    bind.setBindName(p.getPersonName());
                });
            }else if (TkYinhunBindTypeEnum.ZZ.getCode().equals(tkCommonYinhuanBind.getBindType())){
                houseList.stream().filter(h->h.getId().equals(bind.getBindId())).findFirst().ifPresent(h->{
                    bind.setBindName(h.getHouseName());
                });
            }else if (TkYinhunBindTypeEnum.QY.getCode().equals(tkCommonYinhuanBind.getBindType())){
                companyList.stream().filter(c->c.getId().equals(bind.getBindId())).findFirst().ifPresent(c->{
                    bind.setBindName(c.getCompanyName());
                });
            }else if (TkYinhunBindTypeEnum.SP.getCode().equals(tkCommonYinhuanBind.getBindType())){
                shopList.stream().filter(s->String.valueOf(s.getId()).equals(bind.getBindId())).findFirst().ifPresent(s->{
                    bind.setBindName(s.getShopName());
                });
            }
            bind.setYinhuanId(tkCommonYinhuanBind.getYinhuanId());
            binds.add(bind);
        }
        return binds;
    }
}




