package com.ssm.manage.service.impl;

import ch.qos.logback.classic.jmx.MBeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mchange.v1.util.ArrayUtils;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.SsmSalesmanDao;
import com.ssm.manage.dao.SsmServiceOrderDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.query.ServiceOrderRequest;
import com.ssm.manage.query.StoreRoomRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.mbeans.MBeanUtils;
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.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SsmServiceOrderServiceImpl extends BaseServiceImpl<ServiceOrder> implements SsmServiceOrderService {


    public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    public static final String YYYY_MM_DD = "yyyy-MM-dd";

    @Autowired
    private SsmServiceOrderDao dao;
    @Autowired
    private SsmStoreSettlementService ssmStoreSettlementService;

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


    @Autowired
    private SsmStoreRoomService ssmStoreRoomService;


    @Autowired
    private SsmStoreRoomHandService ssmStoreRoomHandService;


    @Override
    public PageInfo<ServiceOrder> selectPage(ServiceOrderRequest serviceOrderRequest){
        Example example = new Example(ServiceOrder.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("storeId",serviceOrderRequest.getStoreId());
        if (null != serviceOrderRequest.getStaffNum()){
            criteria.andLike("staffNum","%" + serviceOrderRequest.getStaffNum() + "%");
        }
        if (null != serviceOrderRequest.getStaffName()){
            criteria.andLike("staffName","%" + serviceOrderRequest.getStaffName() + "%");
        }
        if (null != serviceOrderRequest.getState()){
            criteria.andEqualTo("state",serviceOrderRequest.getState());
        }else{
            criteria.andEqualTo("state",0);
        }
        serviceOrderRequest.setSort("row");
        PageHelper.startPage(serviceOrderRequest.getPageNum(),serviceOrderRequest.getPageSize(),serviceOrderRequest.getOrderAndSort());
        List<ServiceOrder> list = selectByExample(example);
        for (ServiceOrder serviceOrder : list) {

        }
        PageInfo<ServiceOrder> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public List<ServiceOrder> selectList(ServiceOrderRequest serviceOrderRequest) throws SmsException, ParseException {
        Example example = new Example(ServiceOrder.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("storeId",serviceOrderRequest.getStoreId());
        if (null != serviceOrderRequest.getStaffNum()){
            criteria.andLike("staffNum","%" + serviceOrderRequest.getStaffNum() + "%");
        }
        if (null != serviceOrderRequest.getStaffName()){
            criteria.andLike("staffName","%" + serviceOrderRequest.getStaffName() + "%");
        }
        criteria.andEqualTo("state",0);
        example.setOrderByClause("row asc");
        List<ServiceOrder> serviceOrders = dao.selectByExample(example);
        return serviceOrders;
    }

    @Override
    public List<ServiceOrder> selectLists(ServiceOrderRequest serviceOrderRequest) throws SmsException, ParseException {
        Example example = new Example(ServiceOrder.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("storeId",serviceOrderRequest.getStoreId());
        if (null != serviceOrderRequest.getStaffNum()){
            criteria.andLike("staffNum","%" + serviceOrderRequest.getStaffNum() + "%");
        }
        if (null != serviceOrderRequest.getStaffName()){
            criteria.andLike("staffName","%" + serviceOrderRequest.getStaffName() + "%");
        }
        example.setOrderByClause("row");
        List<ServiceOrder> serviceOrders = selectByExample(example);
        serviceOrders.stream();
        Collections.sort(serviceOrders, new Comparator<ServiceOrder>() {
            @Override
            public int compare(ServiceOrder o1, ServiceOrder o2) {
                return o1.getState()-o2.getState();
            }
        });
        return serviceOrders;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int add(List<ServiceOrderRequest> serviceOrderRequest) throws SmsException {
        int i=0;
        int count=0;
        for (ServiceOrderRequest orderRequest : serviceOrderRequest) {
            count++;
            SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD);
            String format = sdf.format(new Date());

            ServiceOrder serviceOrder = new ServiceOrder();

            serviceOrder.setStaffId(orderRequest.getStaffId());
            serviceOrder.setStoreId(orderRequest.getStoreId());
            serviceOrder.setDate(format);
            ServiceOrder serviceOrder1 = dao.selectOne(serviceOrder);
            if(serviceOrder1 != null){
                continue;
            }
            BeanUtils.copyProperties(orderRequest,serviceOrder);
            serviceOrder.setStaffNum(orderRequest.getStaffNum());
            serviceOrder.setStaffName(orderRequest.getStaffName());
            serviceOrder.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            //查询当前上钟前面有多少位进行排序
            Example example = new Example(ServiceOrder.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("storeId",orderRequest.getStoreId());
            criteria.andEqualTo("date",format);
            example.setOrderByClause("`row` desc");
            List<ServiceOrder> list = selectByExample(example);
            if(list.size()==0){
                if(count==1){
                    dao.deleteall(orderRequest.getStoreId());
                }
                BeanUtils.copyProperties(serviceOrder,orderRequest);
                serviceOrder.setState(0);
                serviceOrder.setDate(format);
                serviceOrder.setRow(count);
            }else{
                BeanUtils.copyProperties(serviceOrder,orderRequest);
                serviceOrder.setState(0);
                serviceOrder.setDate(format);
                serviceOrder.setRow(list.get(0).getRow()+1);
            }
            int insert = dao.insert(serviceOrder);
            i=i+insert;
        }
        return i;
    }

    @Override
    public int down(ServiceOrderRequest serviceOrderRequest) throws SmsException {
        ServiceOrder serviceOrder = new ServiceOrder();
        serviceOrder.setStoreId(serviceOrderRequest.getStoreId());
        List<ServiceOrder> select = dao.select(serviceOrder);


        serviceOrder.setStaffId(serviceOrderRequest.getStaffId());
        ServiceOrder serviceOrder1 = dao.selectOne(serviceOrder);
        serviceOrder1.setState(0);
        serviceOrder1.setRow(select.get(-1).getRow()+1);
        int updates = dao.updateByPrimaryKeySelective(serviceOrder1);
        if(updates>0){
            StoreSettlement serviceOrders = ssmStoreSettlementService.selectByPrimaryKey(serviceOrderRequest.getDocId());
            int i = ssmStoreSettlementService.deleteByPrimaryKey(serviceOrderRequest.getDocId());
            if(i>0){
//修改手牌床位状态
                StoreRoomHand storeRoomHand = new StoreRoomHand();
                storeRoomHand.setId(serviceOrders.getRoomHandId());
                StoreRoomHand storeRoomHand1 = ssmStoreRoomHandService.selectOne(storeRoomHand);
                if(storeRoomHand1.getState() != 1){
                    storeRoomHand1.setState(0);
                    int update = ssmStoreRoomHandService.updateNotNull(storeRoomHand1);
                    if(update==0){
                        throw new SmsException(ResponseCode.MSG,"释放占用手牌位失败");
                    }
                }else{
                    throw new SmsException(ResponseCode.MSG,"该房间床位正在使用");
                }

                //修改房间状态
                StoreRoom storeRoom = new StoreRoom();
                storeRoom.setId(serviceOrders.getRoomId());
                StoreRoom storeRoom1 = ssmStoreRoomService.selectOne(storeRoom);

                StoreRoomHand storeRoomHand2 = new StoreRoomHand();
                storeRoomHand1.setRoomId(serviceOrders.getRoomId());
                storeRoomHand1.setStoreId(serviceOrders.getStoreId());
                List<StoreRoomHand> selects = ssmStoreRoomHandService.select(storeRoomHand2);
                Boolean state= true;
                for (StoreRoomHand roomHand : selects) {
                    if(roomHand.getState()==1){
                        state=false;
                    }
                }
                if(state){
                    storeRoom1.setOnState(2);
                    int update = ssmStoreRoomService.updateNotNull(storeRoom1);
                    if(update==0){
                        throw new SmsException(ResponseCode.MSG,"修改房间状态（打扫中）失败");
                    }
                }
            }
        }
        return 0;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int update(ServiceOrderRequest serviceOrderRequest) throws SmsException {
        int update =0;
        SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD);
        String format = sdf.format(new Date());
        if(serviceOrderRequest.getMoveType()==0){//前
            ServiceOrder storeRoom = new ServiceOrder();
            storeRoom.setId(serviceOrderRequest.getMoveId());
            ServiceOrder serviceOrder = dao.selectOne(storeRoom);
            storeRoom.setId(serviceOrderRequest.getId());
            ServiceOrder serviceOrder1 = dao.selectOne(storeRoom);
            Example example = new Example(ServiceOrder.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("storeId",serviceOrderRequest.getStoreId());
            criteria.andEqualTo("date",format);
            criteria.andGreaterThan("row",serviceOrder.getRow());
            criteria.andLessThan("row",serviceOrder1.getRow());
            List<ServiceOrder> list = selectByExample(example);

            //修改需要换位的数据
            serviceOrder1.setRow(serviceOrder.getRow());
            update = dao.updateByPrimaryKeySelective(serviceOrder1);
            if(update>0){
                for (ServiceOrder order : list) {
                    order.setRow(order.getRow()+1);
                    int update1 = dao.updateByPrimaryKeySelective(order);
                    if(update1==0){
                        throw new SmsException(ResponseCode.MSG,"调整排序失败");
                    }
                }
            }
        }else{//后
            ServiceOrder storeRoom = new ServiceOrder();
            storeRoom.setId(serviceOrderRequest.getMoveId());
            ServiceOrder serviceOrder = dao.selectOne(storeRoom);
            storeRoom.setId(serviceOrderRequest.getId());
            ServiceOrder serviceOrder1 = dao.selectOne(storeRoom);
            Example example = new Example(ServiceOrder.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("storeId",serviceOrderRequest.getStoreId());
            criteria.andEqualTo("date",format);
            criteria.andGreaterThan("row",serviceOrder1.getRow());
            criteria.andLessThan("row",serviceOrder.getRow());
            List<ServiceOrder> list = selectByExample(example);

            //修改需要换位的数据
            serviceOrder1.setRow(serviceOrder.getRow());
            update = dao.updateByPrimaryKeySelective(serviceOrder1);
            if(update>0){
                for (ServiceOrder order : list) {
                    order.setRow(order.getRow()-1);
                    int update1 = dao.updateByPrimaryKeySelective(order);
                    if(update1==0){
                        throw new SmsException(ResponseCode.MSG,"调整排序失败");
                    }
                }
            }
        }
        return update;
    }

    @Override
    public int updates(ServiceOrder serviceOrderRequest) {
        ServiceOrder serviceOrder = dao.selectByPrimaryKey(serviceOrderRequest.getId());
        serviceOrder.setState(serviceOrderRequest.getState());
        int update = dao.updateByPrimaryKey(serviceOrder);
        return update;
    }
}
