package com.ssm.manage.service.impl;

import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.BigDecimalUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.core.utils.StoreParaUtils;
import com.ssm.manage.dao.SsmCallNumberDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.extendEntity.CallEntity;
import com.ssm.manage.query.CashListRequest;
import com.ssm.manage.query.StaffRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.DateUtils;
import com.ssm.util.RedisClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class SsmCallNumberServiceImpl extends BaseServiceImpl<CallEntity> implements SsmCallNumberService {
    @Autowired
    private RedisClient<CallEntity> redisClient;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmCashService ssmCashService;

    @Autowired
    private SsmStoreParaService ssmStoreParaService;

    @Autowired
    private SsmMemberOrderService ssmMemberOrderService;

    @Autowired
    private SsmCallNumberDao dao;

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

    private static String key = "callNum";

    @Override
    public List<CallEntity> selectList(CallEntity callEntity) {
        BaseStore store = ssmBaseStoreService.selectByPrimaryKey(callEntity.getStoreId());
        String key = getKey(store.getStoreNum());
        List<CallEntity> list = new ArrayList<>();
        if (redisClient.hasKey(key)){
            list = redisClient.lRange(key,Long.parseLong("0"),Long.parseLong("-1"));
        }
        return list;
    }

    @Override
    public int addNumber(CallEntity callEntity) {
        BaseStore store = ssmBaseStoreService.selectByPrimaryKey(callEntity.getStoreId());
        String key = getKey(store.getStoreNum());
        int i = 0;
        int num = 0;
        String path = "";
        List<CallEntity> list = new ArrayList<>();
        if (redisClient.hasKey(key)){
            list = redisClient.lRange(key,Long.parseLong("0"),Long.parseLong("-1"));
            //列表最后一个号码 + 1
            num = list.get(list.size()-1).getNum() + 1;
        }else {
            num = num + 1;
        }
        //设置文件读取路径   94号，94号-迅捷PDF转换器.mp3
        path = "demay/voice/" + num + "号，" + num + "号-迅捷PDF转换器.mp3";
        callEntity.setNum(num);
        callEntity.setPath(path);
        //默认未叫号状态
        callEntity.setState(0);
        i = redisClient.rightPush(key,callEntity).intValue();
        return i;
    }

    @Override
    public void callNumber(CallEntity callEntity) {
        BaseStore store = ssmBaseStoreService.selectByPrimaryKey(callEntity.getStoreId());
        String key = getKey(store.getStoreNum());
        List<CallEntity> list = new ArrayList<>();
        if (redisClient.hasKey(key)){
            list = redisClient.lRange(key,Long.parseLong("0"),Long.parseLong("-1"));
            for (int i = 0; i < list.size(); i++) {
                CallEntity entity = list.get(i);
                if (entity.getNum() == callEntity.getNum()){
                    //已叫号
                    entity.setState(1);
                    redisClient.lSet(key,Long.parseLong(String.valueOf(i)),entity);
                }
            }


        }
    }

    @Override
    public int addCashList(List<CashListRequest> listRequests, Long storeId, String storeName) throws SmsException {
        int i = 0;
        //单据号
        CashListRequest cashListRequest = new CashListRequest();
        cashListRequest.setCashDate(new Date());
        cashListRequest.setSelectDate(DateUtils.YMFormat(new Date()));
        cashListRequest.setStoreId(storeId);
        String docNum = ssmCashService.getDocNum(cashListRequest,null);
        //查询最低价控制门店参数
        StoreParament storeParament = StoreParaUtils.getStorePara(storeId, Constant.minimum);
        for (CashListRequest listRequest : listRequests) {
            //有最低价控制  校验成交单价
            if ("1".equals(storeParament.getParamentValue())){
                //会员最低价校验
                if (null != listRequest.getMemberId() && BigDecimalUtils.compareTo(listRequest.getTransactionPrice(),listRequest.getMinumumPriceMember()) == -1){
                    throw new SmsException(ResponseCode.MINUMUM_PRICE_LOW,"成交价");
                }else if (null == listRequest.getMemberId() && BigDecimalUtils.compareTo(listRequest.getTransactionPrice(),listRequest.getMinumumPrice()) == -1){
                    //散客最低价校验
                    throw new SmsException(ResponseCode.MINUMUM_PRICE_LOW,"成交价");
                }
            }
            CashList cashList = new CashList();
            //设置开单时间
            listRequest.setCashDate(cashListRequest.getCashDate());
            //不走补单 正常开单 补单时间默认为开单时间
            if (0 == listRequest.getIsAddition()) {
                listRequest.setAdditionDate(new Date());
            }
            listRequest.setStoreId(storeId);
            listRequest.setStoreName(storeName);
            BeanUtils.copyProperties(listRequest,cashList);

            //主键ID
            Long cashId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
            cashList.setId(cashId);
            //单据号不存在 直接赋值 单据号存在 即当前单据增加项目 单据号不变
            if (null == listRequest.getCashNum()) {
                cashList.setCashNum(docNum);
            }
//            //设置业务员
//            List<StaffRequest> staffRequests = listRequest.getStaffLists();
//            if (null != staffRequests && staffRequests.size() > 0){
//                for (StaffRequest staffRequest : staffRequests) {
//                    //1:美发师/2:技术/3:助理/4:收银员/5:美容师
//                    if (staffRequest.getJob() == 5){//大工
//                        cashList.setLargeOneNumber(staffRequest.getBrandNumber());
//                        cashList.setServiceLargeOneStaffId(staffRequest.getId());
//                        cashList.setServiceLargeOneStaffName(staffRequest.getStaffName());
//                        cashList.setServiceLargeOneIdentityCard(staffRequest.getIdentityCard());
//                    }else if (staffRequest.getJob() == 1){//中工
//                        cashList.setZhonggongOneNumber(staffRequest.getBrandNumber());
//                        cashList.setServiceZhonggongOneStaffId(staffRequest.getId());
//                        cashList.setServiceZhonggongOneStaffName(staffRequest.getStaffName());
//                        cashList.setServiceZhonggongOneIdentityCard(staffRequest.getIdentityCard());
//                    }else if (staffRequest.getJob() == 2){//技术
//                        cashList.setTechnicianOneNumber(staffRequest.getBrandNumber());
//                        cashList.setServiceTechnicianOneStaffId(staffRequest.getId());
//                        cashList.setServiceTechnicianOneStaffName(staffRequest.getStaffName());
//                        cashList.setServiceTechnicianOneIdentityCard(staffRequest.getIdentityCard());
//                    }else if (staffRequest.getJob() == 3){//小工
//                        cashList.setSmallOneNumber(staffRequest.getBrandNumber());
//                        cashList.setServiceSmallOneStaffId(staffRequest.getId());
//                        cashList.setServiceSmallOneStaffName(staffRequest.getStaffName());
//                        cashList.setServiceSmallOneIdentityCard(staffRequest.getIdentityCard());
//                    }
//                }
//            }
            i = ssmCashService.addCashList(cashList);
            if (i > 0){
                //预约记录修改为开单状态
                if (null != listRequest.getOrderId()){
                    MemberOrder memberOrder = new MemberOrder();
                    memberOrder.setId(listRequest.getOrderId());
                    memberOrder.setState(1);
                    ssmMemberOrderService.updateNotNull(memberOrder);
                }
                //叫号信息从redis缓存中删除
                BaseStore store = ssmBaseStoreService.selectByPrimaryKey(storeId);
                String key = getKey(store.getStoreNum());
                List<CallEntity> list = redisClient.lRange(key,Long.parseLong("0"),Long.parseLong("-1"));
                for (int j = 0; j < list.size(); j++) {
                    CallEntity entity = list.get(j);
                    if (entity.getNum() == listRequest.getNum()) {
                        redisClient.lRem(key, Long.parseLong(String.valueOf(j)), entity);
                    }
                }
            }
        }
        return i;
    }

    @Override
    public void deleteCallNum(Long storeId) {
        BaseStore store = ssmBaseStoreService.selectByPrimaryKey(storeId);
        String key = getKey(store.getStoreNum());
        List<CallEntity> list = new ArrayList<>();
        if (redisClient.hasKey(key)){
            list = redisClient.lRange(key,Long.parseLong("0"),Long.parseLong("-1"));
            for (int i = 0; i < list.size(); i++) {
                CallEntity entity = list.get(i);
                redisClient.lRem(key,Long.parseLong(String.valueOf(i)),entity);
            }
        }

    }

    public String getKey(String storeNum){
        return key + "-" + storeNum;
    }


    public StoreParament getStorePara(Long storeId, String key){
        StoreParament storeParament = new StoreParament();
        storeParament.setStoreId(storeId);
        storeParament.setParamentName(key);
        storeParament = ssmStoreParaService.selectOne(storeParament);
        return storeParament;
    }
}
