package com.ssm.manage.service.impl;

import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.SsmModifyCourseRecordDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.query.ModifyCourseRecordRequest;
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.SsmModifyCourseRecordService;
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 tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
public class SsmModifyCourseRecordServiceImpl extends BaseServiceImpl<ModifyCourseRecord> implements SsmModifyCourseRecordService {
    @Autowired
    private SsmRechargeAccountService ssmRechargeAccountService;

    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;

    @Autowired
    private SsmCourseAccountService ssmCourseAccountService;

    @Autowired
    private RedisClient<StaffResponse> redisClient;

    @Autowired
    private SsmModifyCourseRecordDao dao;

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

    @Override
    public PageInfo<ModifyCourseRecord> selectPage(ModifyCourseRecordRequest modifyCourseRecordRequest) {
        return dao.selectPage(modifyCourseRecordRequest);
    }

    @Override
    public int add(ModifyCourseRecordRequest modifyCourseRecordRequest, String phone) throws SmsException {
        String docNum = this.getNum(modifyCourseRecordRequest.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();
        ModifyCourseRecord modifyCourseRecord = new ModifyCourseRecord();
        BeanUtils.copyProperties(modifyCourseRecordRequest, modifyCourseRecord);
        modifyCourseRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        modifyCourseRecord.setDocNum(docNum);
        modifyCourseRecord.setModifyId(staffResponse.getId());
        modifyCourseRecord.setModifyBy(staffResponse.getStaffName());
        modifyCourseRecord.setModifyTime(date);
        int i = 0;
        try {
            i = dao.saveNotNull(modifyCourseRecord);
            if (i > 0) {
                //修改充值账户

                CourseAccount courseAccount = new CourseAccount();
                BeanUtils.copyProperties(modifyCourseRecord, courseAccount);
                courseAccount.setId(modifyCourseRecord.getAccountId());
                courseAccount.setCourseRestCount(modifyCourseRecord.getCourseRestCountNew());
                courseAccount.setCourseConsumeCount(modifyCourseRecord.getCourseConsumeCountNew());
                courseAccount.setPrice(modifyCourseRecord.getCourseProjectMoney().divide(BigDecimal.valueOf(courseAccount.getCourseRestCount()),2,BigDecimal.ROUND_HALF_UP));
                ssmCourseAccountService.updateNotNull(courseAccount);
                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(modifyCourseRecord, courseAccount);
                ssmAccountTradeRecordService.addRecord(accountTradeRecord);
            }
        }catch (Exception e){
            log.error("SsmModifyCourseRecordServiceImpl.add:", e);
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return i;
    }


    public String getNum(Long storeId){
        //查询数据库门店 编码最新的一个
        String ymdDate = DateUtils.YMDFormat(new Date());
        Example example = new Example(ModifyCourseRecord.class);
        Example.Criteria criteria = example.createCriteria();
        //按会员编码降序排列
        example.setOrderByClause("doc_num desc");
        criteria.andEqualTo("storeId",storeId);
        List<ModifyCourseRecord> records = dao.selectByExample(example);
        String num;
        int mm = 0;
        if (records != null && records.size() > 0) {
            ModifyCourseRecord modifyCourseRecord = records.get(0);
            String docNum = modifyCourseRecord.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;
    }


    /*
     * 账户交易记录属性赋值 疗程
     * */
    public AccountTradeRecord setAccountTradeRecord(ModifyCourseRecord modifyCourseRecord, CourseAccount courseAccount){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(modifyCourseRecord.getStoreId());
        accountTradeRecord.setStoreName(modifyCourseRecord.getStoreName());
        accountTradeRecord.setMemberId(modifyCourseRecord.getMemberId());
        accountTradeRecord.setMemberName(modifyCourseRecord.getMemberName());
        accountTradeRecord.setAccountId(courseAccount.getId());
        accountTradeRecord.setAccountName(courseAccount.getCourseProjectName());


        accountTradeRecord.setAccountType(Constant.account_type_project);
        accountTradeRecord.setInputDate(new Date());
        if (modifyCourseRecord.getCourseRestCountModify() > 0) {
//            accountTradeRecord.setAccountInMoney(modifyCourseRecord.getCourseProjectMoney());
            accountTradeRecord.setAccountInCount(modifyCourseRecord.getCourseRestCountModify());
        }else {
//            accountTradeRecord.setAccountSpendMoney(modifyCourseRecord.getCourseProjectMoney());
            accountTradeRecord.setAccountSpendCount(modifyCourseRecord.getCourseRestCountModify());
        }
        accountTradeRecord.setDocId(modifyCourseRecord.getId());
        accountTradeRecord.setDocNum(modifyCourseRecord.getDocNum());
        accountTradeRecord.setDocType(Constant.doc_type_course_modify);
        accountTradeRecord.setTradeId(courseAccount.getCourseProjectId());
        accountTradeRecord.setTradeName(courseAccount.getCourseProjectName());
        accountTradeRecord.setTradeMoney(courseAccount.getCourseProjectMoney());
        accountTradeRecord.setTradeCount(courseAccount.getCourseCount());
        accountTradeRecord.setAccountRestCount(courseAccount.getCourseRestCount());
        accountTradeRecord.setAccountConsumeCount(courseAccount.getCourseConsumeCount());
        return accountTradeRecord;
    }
}
