package com.ssm.manage.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.FtpUtils;
import com.ssm.core.utils.SmsType;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.BaseDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.mapper.SmsRechargeListMapper;
import com.ssm.manage.query.CourseListRequest;
import com.ssm.manage.query.SmsRechargeListRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.response.StaffResponse;
import com.ssm.manage.response.UserResponse;
import com.ssm.manage.service.SmsBalanceService;
import com.ssm.manage.service.SmsRechargeListService;
import com.ssm.manage.service.SsmBaseStoreService;
import com.ssm.manage.service.SsmUploadFilesService;
import com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.DateUtils;
import com.ssm.manage.utils.SessionHelp;
import com.ssm.util.RedisClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class SmsRechargeListServiceImpl extends BaseServiceImpl<SmsRechargeList> implements SmsRechargeListService {

    @Autowired
    private SmsRechargeListMapper smsRechargeListMapper;

    @Autowired
    private SmsBalanceService smsBalanceService;


    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmUploadFilesService ssmUploadFilesService;
    @Autowired
    private RedisClient<UserResponse> userRedisClient;
    @Autowired
    private RedisClient<StaffResponse> staffRedisClient;

    private static String userKey = "userKey";
    private static String staffKey = "staffKey";

    @Override
    public BaseDao<SmsRechargeList> getDao() {
        return null;
    }

    @Override
    @Transactional
    public int saveRechargeList(SmsRechargeListRequest smsRechargeListRequest, String phone) throws SmsException {
        SmsRechargeList smsRechargeList = new SmsRechargeList();
        BeanUtils.copyProperties(smsRechargeListRequest,smsRechargeList);
        //获取登录人的信息

        if (userRedisClient.hasKey(getUserKey(phone))) {
            UserResponse staffResponse = userRedisClient.get(getUserKey(phone));
            smsRechargeList.setInputName(staffResponse.getUserName());
            smsRechargeList.setInputDate(new Date());
            smsRechargeList.setInputId(staffResponse.getId());
        }
        if(staffRedisClient.hasKey(getStaffKey(phone))){
            StaffResponse staffResponse = staffRedisClient.get(getStaffKey(phone));
            smsRechargeList.setInputName(staffResponse.getStaffName());
            smsRechargeList.setInputDate(new Date());
            smsRechargeList.setInputId(staffResponse.getId());
        }
        //查询门店的短信账号
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(smsRechargeListRequest.getStoreId());
        smsRechargeList.setSmsAccount(baseStore.getSmsAccount());
        smsRechargeList.setSmsPassword(baseStore.getSmsPassword());
        smsRechargeList.setSmsType(baseStore.getMessagingPlatform());

        String docNum = getDocNum();
        smsRechargeList.setSmsNum(docNum);
        smsRechargeList.setId(getId());
        smsRechargeListMapper.insert(smsRechargeList);



        //将文件上传信息保存到数据库
        List<UploadFiles> list = smsRechargeListRequest.getUploadFiles();
        for (UploadFiles uploadFiles : list) {
            uploadFiles.setDocId(smsRechargeList.getId());
            uploadFiles.setDocNum(docNum);
                uploadFiles.setDocType("smsRecharge");
            ssmUploadFilesService.add(uploadFiles);
        }
        return 1;
    }

    @Override
    public int updateByRechargeList(SmsRechargeListRequest smsRechargeListRequest,String phone) throws SmsException {
        //修改
        SmsRechargeList smsRechargeList = new SmsRechargeList();
        BeanUtils.copyProperties(smsRechargeList,smsRechargeList);
        smsRechargeList.setState(1);
        int updateByPrimaryKey = smsRechargeListMapper.updateByPrimaryKey(smsRechargeList);
        //查询上传的文件，将文件删除
        UploadFiles uploadFile = new UploadFiles();
        uploadFile.setDocId(smsRechargeList.getId());
        List<UploadFiles> select = ssmUploadFilesService.select(uploadFile);
        ssmUploadFilesService.deleteByDocId(smsRechargeList.getId());
        for (UploadFiles files : select) {

            String path = files.getFilePath();
            String name = files.getFileName();
            try {
                new FtpUtils().deleteFile(path,name);
            } catch (IOException e) {

            }
        }

        //将文件上传信息保存到数据库
        List<UploadFiles> list = smsRechargeListRequest.getUploadFiles();
        for (UploadFiles uploadFiles : list) {
            uploadFiles.setDocId(smsRechargeList.getId());
            uploadFiles.setDocNum(smsRechargeList.getSmsNum());
            uploadFiles.setDocType("smsRecharge");
            ssmUploadFilesService.add(uploadFiles);
        }
        return updateByPrimaryKey;
    }

    @Override
    @Transactional
    public int deleteById(Long id) {
        int deleteByPrimaryKey = smsRechargeListMapper.deleteByPrimaryKey(id);
        //查询上传的文件，将文件删除
        UploadFiles uploadFiles = new UploadFiles();
        uploadFiles.setDocId(id);
        List<UploadFiles> select = ssmUploadFilesService.select(uploadFiles);
        ssmUploadFilesService.deleteByDocId(id);
        for (UploadFiles files : select) {

            String path = files.getFilePath();
            String name = files.getFileName();
            try {
                new FtpUtils().deleteFile(path,name);
            } catch (IOException e) {

            }
        }
        return deleteByPrimaryKey;
    }

    @Override
    public PageInfo<SmsRechargeList> selectByList(SmsRechargeListRequest smsRechargeListRequest) {
        //根据门店id查询
        SmsRechargeList smsRechargeList = new SmsRechargeList();
        smsRechargeList.setStoreId(smsRechargeListRequest.getStoreId());
        PageHelper.startPage(smsRechargeListRequest.getPageNum(),smsRechargeListRequest.getPageSize(),"id desc");
        List<SmsRechargeList> select = smsRechargeListMapper.select(smsRechargeList);
        if(select!=null && select.size()>0){
            for (SmsRechargeList rechargeList : select) {
                UploadFiles uploadFiles = new UploadFiles();
                uploadFiles.setDocNum(rechargeList.getSmsNum());
                List<UploadFiles> select1 = ssmUploadFilesService.select(uploadFiles);
                rechargeList.setUploadFiles(select1);
            }
        }
        PageInfo<SmsRechargeList> smsRechargeListPageInfo = new PageInfo<>(select);
        return smsRechargeListPageInfo;
    }

    @Override
    @Transactional
    public int sendAudit(SmsRechargeListRequest smsRechargeListRequest, HttpSession session) throws SmsException{
        SmsRechargeList smsRechargeList = smsRechargeListMapper.selectByPrimaryKey(smsRechargeListRequest.getId());
        int i = 0;
        if(smsRechargeList.getState()==0||smsRechargeList.getState()==1 || smsRechargeList.getState()==5 || smsRechargeList.getState()==4){
            smsRechargeList.setState(2);
            i = smsRechargeListMapper.updateByPrimaryKey(smsRechargeList);
        }
        return i;
    }

    @Override
    @Transactional
    public int audit(SmsRechargeListRequest smsRechargeListRequest, HttpSession session) throws SmsException {
        SmsRechargeList smsRechargeList = smsRechargeListMapper.selectByPrimaryKey(smsRechargeListRequest.getId());
        int i = 0;
        if((smsRechargeList.getState()==2)&&smsRechargeListRequest.getState()==3){
            smsRechargeList.setState(3);
            String phone = SessionHelp.getLoginAccount(session);
            if (userRedisClient.hasKey(getUserKey(phone))) {
                UserResponse staffResponse = userRedisClient.get(getUserKey(phone));
                smsRechargeList.setAuditName(staffResponse.getUserName());
                smsRechargeList.setAuditDate(new Date());
                smsRechargeList.setAuditId(staffResponse.getId());
            }
            i = smsRechargeListMapper.updateByPrimaryKey(smsRechargeList);
            //进行短信账号赋值
            SmsBalance smsBalance = new SmsBalance();
            smsBalance.setSmsAccount(smsRechargeList.getSmsAccount());
            List<SmsBalance> smsBalanceList = smsBalanceService.selectBySmsBalance(smsBalance);
            //判断有没有短信余额信息，没有则进行新增
            if(smsBalanceList==null || smsBalanceList.size()==0){
                BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(smsRechargeList.getStoreId());
                smsBalance.setStoreId(smsRechargeList.getStoreId());
                smsBalance.setParentId(baseStore.getParentId());
                smsBalance.setId(getId());
                smsBalance.setSmsPassword(baseStore.getSmsPassword());
                smsBalance.setSmsUrl(baseStore.getSmsUrl());
                smsBalance.setSmsType(baseStore.getMessagingPlatform());
                smsBalance.setSmsAccountBalance(smsRechargeList.getSmsNumber());
                smsBalance.setSmsStoreBalance(smsRechargeList.getSmsNumber());
                smsBalanceService.insert(smsBalance);
            }else {
                smsBalance = smsBalanceList.get(0);
                smsBalance.setSmsStoreBalance(smsBalance.getSmsStoreBalance()+smsRechargeList.getSmsNumber());
                smsBalance.setSmsAccountBalance(smsBalance.getSmsAccountBalance()+smsRechargeList.getSmsNumber());
                smsBalanceService.updateById(smsBalance);
            }
        }
        return i;
    }

    @Override
    @Transactional
    public int unAudit(SmsRechargeListRequest smsRechargeListRequest, HttpSession session) throws SmsException {
        SmsRechargeList smsRechargeList = smsRechargeListMapper.selectByPrimaryKey(smsRechargeListRequest.getId());
        int i = 0;
        if((smsRechargeList.getState()==3)&&smsRechargeListRequest.getState()==4){
            smsRechargeList.setState(4);
            String loginAccount = SessionHelp.getLoginAccount(session);
            if(userRedisClient.hasKey(getUserKey(loginAccount))){
                UserResponse userResponse = userRedisClient.get(getUserKey(loginAccount));
                smsRechargeList.setUpdateId(userResponse.getId());
                smsRechargeList.setUpdateName(userResponse.getUserName());
                smsRechargeList.setUpdateDate(new Date());
                smsRechargeList.setAuditId(null);
                smsRechargeList.setAuditName(null);
                smsRechargeList.setAuditDate(null);
            }
            i = smsRechargeListMapper.updateByPrimaryKey(smsRechargeList);
            //进行短信账号赋值
            SmsBalance smsBalance = new SmsBalance();
            smsBalance.setSmsAccount(smsRechargeList.getSmsAccount());
            List<SmsBalance> smsBalanceList = smsBalanceService.selectBySmsBalance(smsBalance);
                smsBalance = smsBalanceList.get(0);
                int storeNumber =smsBalance.getSmsStoreBalance()- smsRechargeList.getSmsNumber();
                int accountNumber = smsBalance.getSmsAccountBalance()-smsRechargeList.getSmsNumber();
                if(accountNumber<0){
                    throw new SmsException(ResponseCode.MSG,"短信余额不足，不允许反审核");
                }
                smsBalance.setSmsStoreBalance(storeNumber);
                smsBalance.setSmsAccountBalance(accountNumber);
                smsBalanceService.updateById(smsBalance);
        }
        return i;
    }

    @Override
    public int cancel(SmsRechargeListRequest smsRechargeListRequest, HttpSession session) throws SmsException {
        //只有状态是0，1，2，4可以进行回收；审核状态不允许回收
        SmsRechargeList smsRechargeList = smsRechargeListMapper.selectByPrimaryKey(smsRechargeListRequest.getId());
        if(smsRechargeList.getState()==3){
            throw new SmsException(ResponseCode.MSG,"当前状态不允许回收");
        }
        String loginAccount = SessionHelp.getLoginAccount(session);
        if(userRedisClient.hasKey(getUserKey(loginAccount))){
            UserResponse userResponse = userRedisClient.get(getUserKey(loginAccount));
            smsRechargeList.setUpdateId(userResponse.getId());
            smsRechargeList.setUpdateDate(new Date());
            smsRechargeList.setUpdateName(userResponse.getUserName());
            smsRechargeList.setAuditId(null);
            smsRechargeList.setAuditName(null);
            smsRechargeList.setAuditDate(null);
        }
        smsRechargeList.setState(5);
        return smsRechargeListMapper.updateByPrimaryKey(smsRechargeList);
    }

    public String getUserKey(String phone){
        return userKey + phone;
    }

    public Long getId(){
        return new SnowflakeUtil(new Random().nextInt(1023)).nextId();
    }

    public String getStaffKey(String phone){
        return staffKey + phone;
    }

    /*
     * 生成疗程单号 年月日+编码 20200823
     * */
    public String getDocNum() {
        //查询数据库充值单编码最新的一个
        String ymdDate = DateUtils.YMDFormat(new Date());
        SmsRechargeListRequest smsRechargeListRequest = new SmsRechargeListRequest();
        smsRechargeListRequest.setSelectDate(ymdDate);
        List<SmsRechargeList> smsRechargeLists = smsRechargeListMapper.getDocNum(smsRechargeListRequest);
        String smsNum;
        String num;
        int mm = 0;
        if (smsRechargeLists != null && smsRechargeLists.size() > 0) {
            SmsRechargeList smsRechargeList = smsRechargeLists.get(0);
            int a = 0;
            mm = Integer.parseInt(smsRechargeList.getSmsNum().substring(8 + a)) + 1;
            if (mm < 10) {
                num = "00" + mm;
            } else if (mm < 100) {
                num = "0" + mm;
            } else {
                num = String.valueOf(mm);
            }
            smsNum =  ymdDate + num;

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