package com.ssm.manage.service.impl;

import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.BigDecimalUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.SsmModifyRechargeRecordDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.query.ModifyRechargeRecordRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.response.StaffResponse;
import com.ssm.manage.service.SsmAccountTradeRecordService;
import com.ssm.manage.service.SsmCourseAccountService;
import com.ssm.manage.service.SsmModifyRechargeRecordService;
import com.ssm.manage.service.SsmRechargeAccountService;
import com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.DateUtils;
import com.ssm.util.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
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.util.*;

@Service
@Slf4j
public class SsmModifyRechargeRecordServiceImpl extends BaseServiceImpl<ModifyRechargeRecord> implements SsmModifyRechargeRecordService {
    @Autowired
    private SsmRechargeAccountService ssmRechargeAccountService;

    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;

    @Autowired
    private SsmCourseAccountService ssmCourseAccountService;

    @Autowired
    private RedisClient<StaffResponse> redisClient;

    @Autowired
    private SsmModifyRechargeRecordDao dao;

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

    @Override
    public PageInfo<ModifyRechargeRecord> selectPage(ModifyRechargeRecordRequest modifyRechargeRecordRequest) {
        return dao.selectPage(modifyRechargeRecordRequest);
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public int add(ModifyRechargeRecordRequest modifyRechargeRecordRequest, String phone) throws SmsException {
        String docNum = this.getNum(modifyRechargeRecordRequest.getStoreId());
        StaffResponse staffResponse = new StaffResponse();
        if (redisClient.hasKey(getKey(phone))){
            staffResponse = redisClient.get(getKey(phone));
        }
        Set<String> keys = redisClient.keys(getKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0) {
            String k = new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(k);
        }
        Date date = new Date();
        ModifyRechargeRecord modifyRechargeRecord = new ModifyRechargeRecord();
        BeanUtils.copyProperties(modifyRechargeRecordRequest, modifyRechargeRecord);
        modifyRechargeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        modifyRechargeRecord.setDocNum(docNum);
        modifyRechargeRecord.setModifyId(staffResponse.getId());
        modifyRechargeRecord.setModifyBy(staffResponse.getStaffName());
        modifyRechargeRecord.setModifyTime(date);
        int i = 0;
        try {
            i = dao.saveNotNull(modifyRechargeRecord);
            if (i > 0) {
                //修改充值账户

                RechargeAccount rechargeAccount = new RechargeAccount();
                BeanUtils.copyProperties(modifyRechargeRecord, rechargeAccount);
                rechargeAccount.setId(modifyRechargeRecord.getAccountId());
                rechargeAccount.setCardRestMoney(modifyRechargeRecordRequest.getCardRestMoneyNew());
                rechargeAccount.setCardConsumeMoney(modifyRechargeRecordRequest.getCardConsumeMoneyNew());
                rechargeAccount.setCardGiftMoney(modifyRechargeRecordRequest.getCardGiftMoneyNew());
                rechargeAccount.setGiftConsumeMoney(modifyRechargeRecordRequest.getGiftConsumeMoneyNew());
                ssmRechargeAccountService.updateNotNull(rechargeAccount);
                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(modifyRechargeRecord, rechargeAccount);
                ssmAccountTradeRecordService.addRecord(accountTradeRecord);
            }
        }catch (Exception e){
            log.error("SsmModifyRechargeRecordServiceImpl.add:", e);
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }


        return i;
    }


    public AccountTradeRecord setAccountTradeRecord(ModifyRechargeRecord modifyRechargeRecord, RechargeAccount rechargeAccount){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(modifyRechargeRecord.getStoreId());
        accountTradeRecord.setStoreName(modifyRechargeRecord.getStoreName());
        accountTradeRecord.setMemberId(modifyRechargeRecord.getMemberId());
        accountTradeRecord.setMemberName(modifyRechargeRecord.getMemberName());
        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getRechargeTypeName());

        accountTradeRecord.setAccountType(Constant.account_type_recharge);
        accountTradeRecord.setInputDate(new Date());
        if (BigDecimalUtils.compareTo(modifyRechargeRecord.getCardRestMoneyModify(), BigDecimalUtils.bigDecimal("0")) >= 1){
            accountTradeRecord.setAccountInMoney(modifyRechargeRecord.getCardRestMoneyModify());
        }else {
            accountTradeRecord.setAccountSpendMoney(modifyRechargeRecord.getCardRestMoneyModify());
        }
        accountTradeRecord.setDocId(modifyRechargeRecord.getId());
        accountTradeRecord.setDocNum(modifyRechargeRecord.getDocNum());
        accountTradeRecord.setDocType(Constant.doc_type_recharge_modify);

        accountTradeRecord.setTradeId(rechargeAccount.getRechargeTypeId());
        accountTradeRecord.setTradeName(rechargeAccount.getRechargeTypeName());
        accountTradeRecord.setTradeMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
        accountTradeRecord.setAccountGiftRestMoney(rechargeAccount.getCardGiftMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        return accountTradeRecord;
    }


    public String getNum(Long storeId){
        //查询数据库门店 编码最新的一个
        String ymdDate = DateUtils.YMDFormat(new Date());
        Example example = new Example(ModifyRechargeRecord.class);
        Example.Criteria criteria = example.createCriteria();
        //按会员编码降序排列
        example.setOrderByClause("doc_num desc");
        criteria.andEqualTo("storeId",storeId);
        List<ModifyRechargeRecord> records = dao.selectByExample(example);
        String num;
        int mm = 0;
        if (records != null && records.size() > 0) {
            ModifyRechargeRecord modifyRechargeRecord = records.get(0);
            String docNum = modifyRechargeRecord.getDocNum();
            mm = Integer.parseInt(docNum.substring(docNum.length()-4, docNum.length())) + 1;
            if (mm < 10){
                num = "000" + mm;
            }else if (mm < 100){
                num = "00" + mm;
            }else if (mm < 1000){
                num = "0" + mm;
            }else {
                num = String.valueOf(mm);
            }

        }else {
            num = "0001" ;
        }
        num = ymdDate + num;
        return num;
    }

    public String getKey(String phone){
        String key = "";
        if (StringUtils.isNotBlank(phone)){
            key = Constant.staffKey + phone;
        }
        return key;
    }
}
