package com.ruoyi.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.demo.entity.Equipment;
import com.ruoyi.demo.entity.Store;
import com.ruoyi.demo.entity.bo.StoreBo;
import com.ruoyi.demo.entity.vo.StoreVo;
import com.ruoyi.demo.mapper.EquipmentMapper;
import com.ruoyi.demo.mapper.StoreMapper;
import com.ruoyi.demo.service.StoreService;
import com.ruoyi.demo.utils.InitMapUtil;
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.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class StoreServiceImpl implements StoreService {
    @Autowired
    StoreMapper storeMapper;

    @Autowired
    EquipmentMapper equipmentMapper;

    @Autowired
    InitMapUtil initMapUtil;

    @Override
    public void addStore(StoreVo storeVo) {
        Store store = new Store(storeVo);
        store.setAddrCodeInfo(initMapUtil.getInitAddrCodeMap(store.getAddrCode()));
        store.setCreateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        storeMapper.insert(store);
    }

    @Override
    public void updateStore(StoreVo storeVo) {
        storeVo.setAddrCodeInfo(initMapUtil.getInitAddrCodeMap(storeVo.getAddrCode()));
        UpdateWrapper<Store> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("store_id",storeVo.getStoreId())
        .set("store_name",storeVo.getStoreName())
            .set("addr_info",storeVo.getAddrInfo())
            .set("addr_code",storeVo.getAddrCode())
            .set("addr_code_info",storeVo.getAddrCodeInfo())
            .set("principal_name",storeVo.getPrincipalName())
            .set("principal_telephone",storeVo.getPrincipalTelephone())
            .set("lat",storeVo.getLat())
            .set("lng",storeVo.getLng())
            .set("point",storeVo.getPoint());
        storeMapper.update(null,updateWrapper);
    }

    @Override
    public void deleteStore(String[] storeIds) {
        //1.移除店铺旗下的所有店铺
        UpdateWrapper<Equipment> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("store_id",storeIds);
        updateWrapper.set("store_id",null);
        equipmentMapper.update(null,updateWrapper);

        //2.删除店铺
        storeMapper.deleteBatchIds(Arrays.asList(storeIds));
    }

    /*
    * 店铺管理设备（不支持设备上层没有店铺）
    * */
    @Override
    public HashMap getStoreList(StoreVo storeVo) {
        //1.找到所有店铺列表
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        if(storeVo.getSearchText() != null && !storeVo.getSearchText().equals("")){
            queryWrapper.like("store_name",storeVo.getSearchText());
        }

        Page<Store> page = new Page<>();
        page.setCurrent(storeVo.getPageNum());
        page.setSize(storeVo.getPageSize());
        Page<Store> pageInfo = storeMapper.selectPage(page, queryWrapper);

        //2.找到子设备
        List<String> collect = pageInfo.getRecords().stream().map(item -> {
            return item.getStoreId();
        }).collect(Collectors.toList());

        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        List<StoreBo> storeBos = new ArrayList<>();
        if (!collect.isEmpty()){
            QueryWrapper<Equipment> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.select("store_id","count(*) as state");
            queryWrapper1.in("store_id",collect);
            queryWrapper1.groupBy("store_id");
            List<Equipment> equipments = equipmentMapper.selectList(queryWrapper1);

            //组装
            for (Store store : pageInfo.getRecords()) {
                StoreBo storeBo = new StoreBo(store);
                storeBo.setCount(findEquipmentCount(store.getStoreId(),equipments));
                storeBos.add(storeBo);
            }

            pageInfo.setRecords(null);
            objectObjectHashMap.put("page",pageInfo);
            objectObjectHashMap.put("data",storeBos);
        }
        objectObjectHashMap.put("page",pageInfo);
        objectObjectHashMap.put("data",storeBos);
        return objectObjectHashMap;
    }

    private int findEquipmentCount(String storeId,List<Equipment> equipments){
        for (Equipment equipment : equipments) {
            if (equipment.getStoreId().equals(storeId))
                return equipment.getState();
        }
        return 0;
    }

    @Override
    public Store getStore(String storeId) {
        Store store = storeMapper.selectById(storeId);
        return store;
    }
}
