package com.ssm.manage.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.AESUtils;
import com.ssm.core.utils.BigDecimalUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.*;
import com.ssm.manage.entity.*;
import com.ssm.manage.mapper.SsmStoreAccountOutinMapper;
import com.ssm.manage.query.*;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.response.StaffResponse;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.DateUtils;
import com.ssm.manage.utils.StringUtils;
import com.ssm.util.RedisClient;
import io.swagger.annotations.ApiOperation;
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 org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class SsmStoreAccountOutinServiceImpl extends BaseServiceImpl<RechargeAccountOutin> implements SsmStoreAccountOutinService {

    @Autowired
    private RedisClient<StaffResponse> redisClient;
    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;
    @Autowired
    private SsmStoreAccountOutinDao dao;

    @Autowired
    private SsmStoreMemberDao ssmStoreMemberDao;

    @Autowired
    private SsmRechargeAccountGiveDao ssmRechargeAccountGiveDao;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmRechargeTypeSevice ssmRechargeTypeSevice;


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


    @Override
    public PageInfo<RechargeAccountOutinRequest> selectPage(RechargeAccountOutinRequest rechargeAccountOutinRequest) throws SmsException {
        if(rechargeAccountOutinRequest.getPhone()!=null&&!rechargeAccountOutinRequest.getPhone().trim().equals("")){
            StoreMemberList storeMemberList=new StoreMemberList();
            String phone="";
            try {
                phone= AESUtils.encrypt(rechargeAccountOutinRequest.getPhone());
            }catch (Exception e){
                e.printStackTrace();
            }
            storeMemberList.setMobilePhone(phone);
            List<StoreMemberList> memberLists=ssmStoreMemberDao.select(storeMemberList);
            if(memberLists==null || memberLists.size()==0){
                throw new SmsException(ResponseCode.MSG,"未查到此手机号的相关信息，请输入正确完整的手机号码");
            }
            rechargeAccountOutinRequest.setOutMemberId(memberLists.get(0).getId());
        }
        if(rechargeAccountOutinRequest.getDocDate()!=null){
            String docDate=DateUtils.ymdFormat(rechargeAccountOutinRequest.getDocDate());
            rechargeAccountOutinRequest.setDate(docDate);
        }
        PageInfo<RechargeAccountOutin> list= dao.selectPage(rechargeAccountOutinRequest);
        List<RechargeAccountOutinRequest> lists=new ArrayList<>();
        for(RechargeAccountOutin rechargeAccountOutin:list.getList()){
            RechargeAccountOutinRequest rechargeAccountOutinRequest1=new RechargeAccountOutinRequest();
            BeanUtils.copyProperties(rechargeAccountOutin,rechargeAccountOutinRequest1);
            rechargeAccountOutinRequest1.setDate(DateUtils.ymdhmFormat(rechargeAccountOutinRequest1.getDocDate()));
            lists.add(rechargeAccountOutinRequest1);
        }
        PageInfo<RechargeAccountOutinRequest> pageInfo = new PageInfo<>(lists);
        return pageInfo;
    }

    @Override
    public List<RechargeAccountGive> selectGiveAccount(RechargeAccountRequest rechargeAccountRequest) throws SmsException {
        Example example1 = new Example(RechargeAccountGive.class);
        Example.Criteria criteria1 = example1.createCriteria();
        if(rechargeAccountRequest.getStoreId()!=null){
            criteria1.andEqualTo("storeId",rechargeAccountRequest.getStoreId());
        }
        criteria1.andEqualTo("memberId",rechargeAccountRequest.getMemberId());
        //查询原账户的赠送金额
        List<RechargeAccountGive> List=ssmRechargeAccountGiveDao.selectByExample(example1);
        List<RechargeAccountGive> reList=new ArrayList<>();
        for(RechargeAccountGive rechargeAccountGive:List){
            if(rechargeAccountGive.getGiftConsumeMoney().compareTo(new BigDecimal(0))==1){
                reList.add(rechargeAccountGive);
            }
        }
        return reList;
    }
    private static String staffKey = "staffKey";
    public String getStaffKey(String phone) {
        return staffKey + phone;
    }
    @Override
    public int add(List<RechargeAccountOutinRequest> requestList) throws SmsException {
        List<RechargeAccountOutin> list=new ArrayList<>();
        int i=0;
        for(RechargeAccountOutinRequest rechargeAccountOutinRequest:requestList){
            Set<String> keys = redisClient.keys(getStaffKey(rechargeAccountOutinRequest.getInputBy()) + "*");
            //从redis查询 设置录单人信息 app使用
            if (keys.size() > 0) {
                String key = new ArrayList<>(keys).get(0);
                StaffResponse staffResponse = redisClient.get(key);
                rechargeAccountOutinRequest.setInputId(staffResponse.getId());
                rechargeAccountOutinRequest.setInputName(staffResponse.getStaffName());
                rechargeAccountOutinRequest.setInputDate(new Date());
            }
            RechargeAccountOutin rechargeAccountOutin=new RechargeAccountOutin();
            BeanUtils.copyProperties(rechargeAccountOutinRequest,rechargeAccountOutin);
            try {
                this.copy(rechargeAccountOutin,rechargeAccountOutinRequest.getRechargeAccountGive());
            }catch (Exception e){
                e.printStackTrace();
            }
            rechargeAccountOutin.setRechargeStoreNum(getDocNum());
            i=dao.insert(rechargeAccountOutin);
        }
        return i;
    }

    public String getDocNum() {
        //查询数据库充值单编码最新的一个
        String ymdDate = DateUtils.YMDFormat(new Date());
        String s = "CZZMD";
        RechargeAccountOutin rechargeAccountOutin = new RechargeAccountOutin();
        rechargeAccountOutin.setRechargeStoreNum(s+ymdDate);
        List<RechargeAccountOutin> rechargeAccountOutins = dao.getNum(rechargeAccountOutin);
        String num;
        int mm = 0;
        if (rechargeAccountOutins != null && rechargeAccountOutins.size() > 0) {
            RechargeAccountOutin courseList = rechargeAccountOutins.get(0);
            int a = s.length();
            mm = Integer.parseInt(courseList.getRechargeStoreNum().substring(8 + a)) + 1;
            if (mm < 10) {
                num = "00" + mm;
            } else if (mm < 100) {
                num = "0" + mm;
            } else {
                num = String.valueOf(mm);
            }
            s +=  ymdDate + num;

        } else {
            num = "001";
            s += ymdDate + num;
        }
        return s;
    }
    public String getGiveNum(String s) {
        //查询数据库充值单编码最新的一个
        String ymdDate = DateUtils.YMDFormat(new Date());
        RechargeAccountGive rechargeAccountGive = new RechargeAccountGive();
        rechargeAccountGive.setRechargeStoreNum(s+ymdDate);
        List<RechargeAccountGive> ssmRechargeAccountGiveDaoDocNum = ssmRechargeAccountGiveDao.getDocNum(rechargeAccountGive);
        String num;
        int mm = 0;
        if (ssmRechargeAccountGiveDaoDocNum != null && ssmRechargeAccountGiveDaoDocNum.size() > 0) {
            RechargeAccountGive courseList = ssmRechargeAccountGiveDaoDocNum.get(0);
            int a = s.length();
            mm = Integer.parseInt(courseList.getRechargeStoreNum().substring(8 + a)) + 1;
            if (mm < 10) {
                num = "00" + mm;
            } else if (mm < 100) {
                num = "0" + mm;
            } else {
                num = String.valueOf(mm);
            }
            s +=  ymdDate + num;

        } else {
            num = "001";
            s += ymdDate + num;
        }
        return s;
    }

    @Override
    @Transactional
    public int update(List<RechargeAccountOutinRequest> requestList) throws SmsException {
        RechargeAccountGive rechargeAccountGive=new RechargeAccountGive();
        int i=0;
        for(RechargeAccountOutinRequest rechargeAccountOutinRequestL:requestList){
            RechargeAccountOutin rechargeAccountOutin=new RechargeAccountOutin();
            BeanUtils.copyProperties(rechargeAccountOutinRequestL,rechargeAccountOutin);
            rechargeAccountOutin.setState(1);
            i=dao.updateByPrimaryKey(rechargeAccountOutin);
            //修改转出账户
            Example example1 = new Example(RechargeAccountGive.class);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("accountId",rechargeAccountOutinRequestL.getAccountId());
            criteria1.andEqualTo("storeId",rechargeAccountOutinRequestL.getOutStoreId());
            criteria1.andEqualTo("memberId",rechargeAccountOutinRequestL.getOutMemberId());
            //查询转出门店账户
            List<RechargeAccountGive> outList=ssmRechargeAccountGiveDao.selectByExample(example1);

            //修改转入账户
            Example example2 = new Example(RechargeAccountGive.class);
            Example.Criteria criteria2 = example2.createCriteria();
            criteria2.andEqualTo("accountId",rechargeAccountOutinRequestL.getAccountId());
            criteria2.andEqualTo("storeId",rechargeAccountOutinRequestL.getInStoreId());
            criteria2.andEqualTo("memberId",rechargeAccountOutinRequestL.getOutMemberId());
            //查询转入门店是否存在账户
            List<RechargeAccountGive> inList=ssmRechargeAccountGiveDao.selectByExample(example2);
            String czzrmd = this.getGiveNum("CZZRMD");
            if(inList.size()==0){//新添加
//                rechargeAccountGive=outList.get(0);
                rechargeAccountGive.setStoreId(rechargeAccountOutinRequestL.getInStoreId());
                rechargeAccountGive.setStoreName(rechargeAccountOutinRequestL.getInStoreName());
                rechargeAccountGive.setRechargeDate(new Date());
                rechargeAccountGive.setRechargeStoreNum(czzrmd);
                rechargeAccountGive.setAccountId(rechargeAccountOutin.getAccountId());
                rechargeAccountGive.setMemberId(rechargeAccountOutin.getOutMemberId());
                rechargeAccountGive.setMemberName(rechargeAccountOutin.getOutMemberName());
                rechargeAccountGive.setGiftConsumeMoney(rechargeAccountOutin.getOutGiftConsumeMoney());
                rechargeAccountGive.setRechargeNum(outList.get(0).getRechargeNum());
                rechargeAccountGive.setRechargeTypeId(outList.get(0).getRechargeTypeId());
                rechargeAccountGive.setRechargeTypeName(outList.get(0).getRechargeTypeName());
                i=ssmRechargeAccountGiveDao.insert(rechargeAccountGive);
            }else if(inList.size()==1){//修改
                rechargeAccountGive=inList.get(0);
                rechargeAccountGive.setGiftConsumeMoney(rechargeAccountGive.getGiftConsumeMoney().add(rechargeAccountOutinRequestL.getOutGiftConsumeMoney()));
                i=ssmRechargeAccountGiveDao.updateByExample(rechargeAccountGive,example2);
            }else{
                throw new SmsException(ResponseCode.MSG,"修改转入账户异常");
            }
            //添加卡转出记录


            AccountTradeRecord accountTradeRecord = new AccountTradeRecord();

            accountTradeRecord.setDocNum(czzrmd);
            accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());//交易记录id
            accountTradeRecord.setStoreId(rechargeAccountOutinRequestL.getInStoreId());//门店id
            accountTradeRecord.setMemberId(rechargeAccountGive.getMemberId());//会员id
            accountTradeRecord.setStoreName(rechargeAccountOutinRequestL.getInStoreName());//门店名字
            accountTradeRecord.setMemberName(rechargeAccountGive.getMemberName());//会员名字
            accountTradeRecord.setAccountId(rechargeAccountGive.getAccountId());//账户id
            accountTradeRecord.setInputBy(rechargeAccountOutinRequestL.getInputBy());
            StoreMemberList storeMemberList = new StoreMemberList();
            storeMemberList.setId(accountTradeRecord.getMemberId());
            storeMemberList = ssmStoreMemberDao.selectOne(storeMemberList);
            accountTradeRecord.setAccountName("充值卡转入门店");//账户名字
            accountTradeRecord.setTradeName("充值卡转入门店");//交易名字
            accountTradeRecord.setTradeMoney(rechargeAccountGive.getGiftConsumeMoney());//交易名字
            accountTradeRecord.setCardMoney(rechargeAccountGive.getGiftConsumeMoney());//交易金额
            String phone ;
            try {
                phone =  AESUtils.decrypt(storeMemberList.getMobilePhone()).replaceAll("\u0000","");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            accountTradeRecord.setMemberPhone(phone);
            accountTradeRecord.setAccountGiftRestMoney(rechargeAccountGive.getGiftConsumeMoney());//剩余金额
            accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccountGive.getGiftConsumeMoney());//可用金额
            accountTradeRecord.setIsAddition(0);//是否补单
            accountTradeRecord.setOrderStatu(0);//单据状态
//            accountTradeRecord.setAccountConsumeCount(10);//卡的剩余可用次数
            accountTradeRecord.setAccountType("CZZRMD");//交易类型为赠卡
            accountTradeRecord.setInputDate(new Date());
            accountTradeRecord.setTradeMoney(rechargeAccountOutinRequestL.getOutGiftConsumeMoney());
            accountTradeRecord.setDocId(rechargeAccountOutin.getId());
            ssmAccountTradeRecordService.addRecord(accountTradeRecord);
            //先转入再进行修改原账户
            if(outList.size()>0){
                rechargeAccountGive=outList.get(0);
                rechargeAccountGive.setGiftConsumeMoney(new BigDecimal(0));
                i=ssmRechargeAccountGiveDao.updateByExample(rechargeAccountGive,example1);
                //添加卡转出记录
                AccountTradeRecord accountTradeRecord1 = new AccountTradeRecord();
                accountTradeRecord1.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());//交易记录id
                RechargeAccountGive accountGive = outList.get(0);
                accountTradeRecord1.setDocNum(this.getGiveNum("CZCCMD"));
                accountTradeRecord1.setStoreId(rechargeAccountOutinRequestL.getOutStoreId());//门店id
                accountTradeRecord1.setMemberId(accountGive.getMemberId());//会员id
                accountTradeRecord1.setStoreName(rechargeAccountOutinRequestL.getOutStoreName());//门店名字
                accountTradeRecord1.setMemberName(accountGive.getMemberName());//会员名字
                accountTradeRecord1.setAccountId(accountGive.getAccountId());//账户id
                accountTradeRecord1.setAccountName("充值卡转出门店");//账户名字
                accountTradeRecord1.setTradeName("充值卡转出门店");//交易名字
                accountTradeRecord1.setInputBy(rechargeAccountOutinRequestL.getInputBy());
                accountTradeRecord1.setTradeMoney(rechargeAccountGive.getGiftConsumeMoney());//交易名字
                accountTradeRecord1.setCardMoney(rechargeAccountGive.getGiftConsumeMoney());//交易金额
                accountTradeRecord1.setMemberPhone(phone);
                accountTradeRecord1.setAccountGiftRestMoney(accountGive.getGiftConsumeMoney());//剩余金额
                accountTradeRecord1.setAccountGiftConsumeMoney(accountGive.getGiftConsumeMoney());//可用金额
                accountTradeRecord1.setIsAddition(0);//是否补单
                accountTradeRecord1.setOrderStatu(0);//单据状态
//                accountTradeRecord1.setAccountConsumeCount(10);//卡的剩余可用次数
                accountTradeRecord1.setAccountType("CZZCMD");//交易类型为赠卡
                accountTradeRecord1.setInputDate(new Date());
                accountTradeRecord1.setTradeMoney(accountGive.getGiftConsumeMoney());
                accountTradeRecord1.setDocId(rechargeAccountOutin.getId());
                ssmAccountTradeRecordService.addRecord(accountTradeRecord1);
            }else{
                throw new SmsException(ResponseCode.MSG,"修改转出账户异常,该充值卡不允许转入该门店");
            }

        }
        return i;
    }

    public RechargeAccountOutin copy(RechargeAccountOutin rechargeAccountOutin,RechargeAccountGive rechargeAccountGive) throws ParseException {
        rechargeAccountOutin.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        Date date=new Date();
        SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sbf.format(date));
        rechargeAccountOutin.setDocDate(date);
        rechargeAccountOutin.setAccountId(rechargeAccountGive.getAccountId());
        rechargeAccountOutin.setOutGiftConsumeMoney(rechargeAccountGive.getGiftConsumeMoney());
        rechargeAccountOutin.setOutMemberId(rechargeAccountGive.getMemberId());
        rechargeAccountOutin.setOutMemberName(rechargeAccountGive.getMemberName());

        RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeAccountGive.getRechargeTypeId());
        rechargeAccountOutin.setRechargeNum(rechargeType.getRechargeTypeNum());
        rechargeAccountOutin.setRechargeTypeId(rechargeAccountGive.getRechargeTypeId());
        rechargeAccountOutin.setRechargeTypeName(rechargeAccountGive.getRechargeTypeName());

        BaseStore outbaseStore=ssmBaseStoreService.selectByPrimaryKey(rechargeAccountOutin.getOutStoreId());
        rechargeAccountOutin.setOutStoreNum(outbaseStore.getStoreNum());
        rechargeAccountOutin.setOutStoreName(outbaseStore.getStoreName());

        BaseStore inbaseStore=ssmBaseStoreService.selectByPrimaryKey(rechargeAccountOutin.getInStoreId());
        rechargeAccountOutin.setInStoreNum(inbaseStore.getStoreNum());
        rechargeAccountOutin.setInStoreName(inbaseStore.getStoreName());

        rechargeAccountOutin.setState(0);

        return rechargeAccountOutin;
    }


}
