package com.ssm.manage.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.SsmStoreConversionDao;
import com.ssm.manage.dao.SsmStoreRoomServiceDao;
import com.ssm.manage.dao.SsmStoreTurnTreatmentDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.extendEntity.StoreDaily;
import com.ssm.manage.query.CancelDebtListRequest;
import com.ssm.manage.query.RoomSatet;
import com.ssm.manage.query.StoreRoomHandRequest;
import com.ssm.manage.query.StoreRoomRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.response.StaffResponse;
import com.ssm.manage.response.StoreSettlementResponse;
import com.ssm.manage.service.*;
import com.ssm.util.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SsmStoreRoomServiceImpl  extends BaseServiceImpl<StoreRoom> implements SsmStoreRoomService {

    @Autowired
    private SsmStoreRoomServiceDao dao;

    @Autowired
    private SsmStoreRoomHandService ssmStoreRoomHandService;

    @Autowired
    private SsmStoreSettelnmentProjectService ssmStoreSettelnmentProjectService;
    @Autowired
    private SsmStoreSettlementService ssmStoreSettlementService;

    private static String staffKey = "staffKey";
    @Autowired
    private RedisClient<StaffResponse> redisClient;

    @Override
    public SsmStoreRoomServiceDao getDao() {
        return dao;
    }


    @Override
    public PageInfo<StoreRoom> selectPage(StoreRoomRequest storeRoomRequest){
        Example example = new Example(StoreRoom.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("storeId",storeRoomRequest.getStoreId());
        if (null != storeRoomRequest.getRoomNum()){
            criteria.andLike("roomNum","%" + storeRoomRequest.getRoomNum() + "%");
        }
        if (null != storeRoomRequest.getRoomName()){
            criteria.andLike("roomName","%" + storeRoomRequest.getRoomName() + "%");
        }
        if (null != storeRoomRequest.getState()){
            criteria.andEqualTo("state",storeRoomRequest.getState());
        }
        storeRoomRequest.setSort("roomNum");
        PageHelper.startPage(storeRoomRequest.getPageNum(),storeRoomRequest.getPageSize(),storeRoomRequest.getOrderAndSort());
        List<StoreRoom> list = selectByExample(example);
        PageInfo<StoreRoom> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public PageInfo<StoreRoomRequest> selectPages(StoreRoomRequest storeRoomRequest){
        Example example = new Example(StoreRoom.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("storeId",storeRoomRequest.getStoreId());
        if (null != storeRoomRequest.getRoomNum()){
            criteria.andLike("roomNum","%" + storeRoomRequest.getRoomNum() + "%");
        }
        if (null != storeRoomRequest.getRoomName()){
            criteria.andLike("roomName","%" + storeRoomRequest.getRoomName() + "%");
        }
        if (null != storeRoomRequest.getState()){
            criteria.andEqualTo("state",storeRoomRequest.getState());
        }
        storeRoomRequest.setSort("");
        PageHelper.startPage(storeRoomRequest.getPageNum(),storeRoomRequest.getPageSize(),storeRoomRequest.getOrderAndSort());
        List<StoreRoom> list = selectByExample(example);
        List<StoreRoomRequest> storeRoomRequests = new ArrayList<>();
        for (StoreRoom roomRequest : list) {
            StoreRoomRequest storeRoomRequest1 = new StoreRoomRequest();
            BeanUtils.copyProperties(roomRequest,storeRoomRequest1);
            StoreRoomHand storeRoomHand = new StoreRoomHand();
            storeRoomHand.setRoomId(roomRequest.getId());
            storeRoomHand.setStoreId(roomRequest.getStoreId());
            List<StoreRoomHand> storeRoomHand1 = ssmStoreRoomHandService.select(storeRoomHand);
            List<StoreRoomHandRequest> storeRoomHandRequests = new ArrayList<>();
            for (StoreRoomHand roomHand : storeRoomHand1) {
                StoreRoomHandRequest storeRoomHandRequest = new StoreRoomHandRequest();
                BeanUtils.copyProperties(roomHand,storeRoomHandRequest);
                List<StoreSettlement> storeSettlements = new ArrayList<>();
                if(roomHand.getState()==1){
                    StoreSettlement storeSettlement = new StoreSettlement();
                    storeSettlement.setRoomId(roomRequest.getId());
                    storeSettlement.setRoomHandId(roomHand.getId());
                    storeSettlements = ssmStoreSettlementService.select(storeSettlement);
                }
                storeRoomHandRequest.setStoreSettlement(storeSettlements);
                storeRoomHandRequests.add(storeRoomHandRequest);
            }
            storeRoomRequest1.setStoreRoomHandList(storeRoomHandRequests);
            storeRoomRequests.add(storeRoomRequest1);
        }
        PageInfo<StoreRoomRequest> pageInfo = new PageInfo<>(storeRoomRequests);
        return pageInfo;
    }

    @Override
    public RoomSatet selectstate(StoreRoomRequest storeRoomRequest){
        RoomSatet roomSatet = new RoomSatet();
        StoreRoom storeRoom = new StoreRoom();
        storeRoom.setOnState(0);
        storeRoom.setStoreId(storeRoomRequest.getStoreId());
        List<StoreRoom> select = dao.select(storeRoom);
        roomSatet.setLeisure(select.size());

        storeRoom.setOnState(1);
        List<StoreRoom> select1 = dao.select(storeRoom);
        roomSatet.setUse(select1.size());

        storeRoom.setOnState(2);
        select = dao.select(storeRoom);
        roomSatet.setSweep(select.size());

        Example example = new Example(StoreSettlement.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("storeId",storeRoomRequest.getStoreId());
        criteria.andNotEqualTo("serviceEndDate","");
        List<StoreSettlement> storeSettlements = ssmStoreSettlementService.selectByExample(example);
        Map<Long, List<StoreSettlement>> collect = storeSettlements.stream().collect(Collectors.groupingBy(StoreSettlement::getRoomId));
        roomSatet.setAwait(collect.size());
        roomSatet.setOvertime(0);
        return roomSatet;
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public int add(StoreRoomRequest storeRoomRequest,String phone) throws SmsException {
        StoreRoom storeRoom = new StoreRoom();
        storeRoom.setStoreId(storeRoomRequest.getStoreId());
        storeRoom.setRoomNum(storeRoomRequest.getRoomNum());
        StoreRoom select = dao.selectOne(storeRoom);
        if(null != select){
            throw new SmsException(ResponseCode.MSG,"当前门店房间编码已经存在");
        }
        BeanUtils.copyProperties(storeRoomRequest,storeRoom);
        if(storeRoom.getRoomHand()==0){
            throw new SmsException(ResponseCode.MSG,"房间手牌不能为0");
        }

        StaffResponse staffResponse = new StaffResponse();
        Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }
        storeRoom.setFounderStaff(staffResponse.getStaffName());
        storeRoom.setFounderDatetime(new Date());

        storeRoom.setState(1);
        storeRoom.setOnState(0);
        storeRoom.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        int insert = dao.insert(storeRoom);
        if(insert>0){
            for (int i = 1; i <=storeRoom.getRoomHand(); i++) {
                StoreRoomHand storeRoomHand = new StoreRoomHand();
                storeRoomHand.setStoreId(storeRoomRequest.getStoreId());
                storeRoomHand.setStoreName(storeRoomRequest.getStoreName());
                storeRoomHand.setRoomId(storeRoom.getId());
                storeRoomHand.setState(0);
                storeRoomHand.setRow(i);
                if(i<10){
                    storeRoomHand.setRoomHandNum(storeRoom.getRoomNum()+"00"+i);
                }else if(i<100){
                    storeRoomHand.setRoomHandNum(storeRoom.getRoomNum()+"0"+i);
                }
                storeRoomHand.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                int i1 = ssmStoreRoomHandService.saveNotNull(storeRoomHand);
                if(i1==0){
                    throw new SmsException(ResponseCode.MSG,"新增手牌失败");
                }
            }
        }
        return insert;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int update(StoreRoomRequest storeRoomRequest,String phone) throws SmsException {
        StoreRoom storeRoom = new StoreRoom();
        storeRoom.setStoreId(storeRoomRequest.getStoreId());
        storeRoom.setRoomNum(storeRoomRequest.getRoomNum());
        StoreRoom select = dao.selectOne(storeRoom);
        if(null != select){
            if(!select.getId().equals(storeRoomRequest.getId()) ){
                throw new SmsException(ResponseCode.MSG,"当前门店房间编码已经存在");
            }
        }
        BeanUtils.copyProperties(storeRoomRequest,storeRoom);
        if(storeRoom.getRoomHand()==0){
            throw new SmsException(ResponseCode.MSG,"房间手牌不能为0");
        }
        StaffResponse staffResponse = new StaffResponse();
        Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }
        storeRoom.setModifyBy(staffResponse.getStaffName());
        storeRoom.setModifyDatetime(new Date());

        int insert = dao.updateByPrimaryKeySelective(storeRoom);
        if(insert>0){
            if(storeRoom.getRoomHand()!=select.getRoomHand()){
                StoreRoomHand storeRoomHandx = new StoreRoomHand();
                storeRoomHandx.setStoreId(storeRoom.getStoreId());
                storeRoomHandx.setRoomId(storeRoom.getId());
                ssmStoreRoomHandService.delete(storeRoomHandx);

                for (int i = 1; i <= storeRoom.getRoomHand(); i++) {
                    StoreRoomHand storeRoomHand = new StoreRoomHand();
                    storeRoomHand.setStoreId(storeRoom.getStoreId());
                    storeRoomHand.setStoreName(storeRoom.getStoreName());
                    storeRoomHand.setRoomId(storeRoom.getId());
                    storeRoomHand.setState(0);
                    storeRoomHand.setRow(i);
                    storeRoomHand.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                    int i1 = ssmStoreRoomHandService.saveNotNull(storeRoomHand);
                    if(i1==0){
                        throw new SmsException(ResponseCode.MSG,"新增手牌失败");
                    }
                }
            }

        }
        return insert;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int updateStates(StoreRoomRequest storeRoomRequest,String phone) throws SmsException {
        StoreRoom storeRoom = new StoreRoom();
        storeRoom.setId(storeRoomRequest.getId());
        StoreRoom select = dao.selectOne(storeRoom);
        if(null != storeRoomRequest.getState()){
            select.setState(storeRoomRequest.getState());

            StaffResponse staffResponse = new StaffResponse();
            Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
            //从redis查询 设置录单人信息 app使用
            if (keys.size() > 0){
                String key =  new ArrayList<>(keys).get(0);
                staffResponse = redisClient.get(key);
            }
            select.setModifyBy(staffResponse.getStaffName());
            select.setModifyDatetime(new Date());
        }
        if(null != storeRoomRequest.getOnState()){
            select.setOnState(storeRoomRequest.getOnState());
        }

        int insert = dao.updateByPrimaryKeySelective(select);
        return insert;
    }

    public String getStaffKey(String phone){
        return staffKey + phone;
    }
}
