package com.ssm.manage.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.*;
import com.ssm.manage.dao.SsmRefundOrderDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.extendEntity.RecDocList;
import com.ssm.manage.extendEntity.StoreDaily;
import com.ssm.manage.mapper.RefundOrderListMapper;
import com.ssm.manage.query.*;
import com.ssm.manage.response.RefundCourseResponse;
import com.ssm.manage.response.RefundDayVo;
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.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 org.springframework.transaction.interceptor.TransactionAspectSupport;
import springfox.documentation.spring.web.json.Json;
import tk.mybatis.mapper.entity.Example;

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

@Service
@Slf4j
public class SsmRefundOrderServiceImpl extends BaseServiceImpl<RefundOrderList> implements SsmRefundOrderService {
    @Autowired
    private SsmRefundRechargeService ssmRefundRechargeService;

    @Autowired
    private SsmRefundCourseService ssmRefundCourseService;

    @Autowired
    private SsmRefundCashService ssmRefundCashService;

    @Autowired
    private SsmRefundRoomCashService ssmRefundRoomCashService;
    @Autowired
    private SsmCourseService ssmCourseService;

    @Autowired
    private SsmUploadFilesService ssmUploadFilesService;

    @Autowired
    private SsmRechargeAccountService ssmRechargeAccountService;
    @Autowired
    private SsmSalesmanService ssmSalesmanService;

    @Autowired
    private SsmCourseAccountService ssmCourseAccountService;


    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmDebtService ssmDebtService;

    @Autowired
    private RedisClient<StaffResponse> redisClient;

    @Autowired
    private SsmRefundOrderDao dao;

    @Autowired
    private SsmRechargeService ssmRechargeService;

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

    @Override
    public PageInfo<RefundOrderList> selectPage(RefundOrderResquest refundOrderResquest) {
        return dao.selectPage(refundOrderResquest);
    }

    @Override
    public PageInfo<RefundOrderList> selectPageNew(RefundOrderResquest refundOrderResquest) {
        return dao.selectPageNew(refundOrderResquest);
    }

    @Override
    public PageInfo<RefundOrderList> memberPageNew(RefundOrderResquest refundOrderResquest) {
        return dao.memberPageNew(refundOrderResquest);
    }

    @Override
    public List<RefundOrderList> refundCourseCash(RefundOrderResquest refundOrderResquest) {
        return dao.refundCourseCash(refundOrderResquest);
    }

    @Override
    public PageInfo<RefundOrderList> selectPageFd(RefundOrderResquest refundOrderResquest) {
        return dao.selectPageFd(refundOrderResquest);
    }
    @Override
    public PageInfo<RefundOrderList> pageDetail(RefundOrderResquest refundOrderResquest) {
        return dao.pageDetail(refundOrderResquest);
    }

    @Override
    public List<RefundOrderList> selectFKJ(RefundOrderList refundOrderResquest) {
        return dao.selectFKJ(refundOrderResquest);

    }
    @Override
    public List<RefundOrderList> selectFKJByDate(RefundOrderList refundOrderResquest) {
        return mapper.selectFKJByDate(refundOrderResquest);

    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int addRefundOrder(RefundOrderResquest refundOrderResquest) throws SmsException {
        int i = 0;
        RefundOrderList refundOrderList = new RefundOrderList();
        BeanUtils.copyProperties(refundOrderResquest, refundOrderList);
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(refundOrderList.getStoreId());
        refundOrderList.setStoreNum(baseStore.getStoreNum());
        Long refundId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        refundOrderList.setId(refundId);
        String refundNum = this.getDocNum(refundOrderList);
        refundOrderList.setRefundNum(refundNum);
//        CourseList courseList1 = new CourseList();
//        courseList1.setMemberId(refundOrderList.getMemberId());
//        courseList1.setStoreId(refundOrderList.getStoreId());
//
//        CourseList courseList = ssmCourseService.selectOne();
//        refundOrderList.setRefundNum(refundOrderList.getSourceDocNum());
        refundOrderList.setRefundDate(new Date());
        refundOrderList.setState(0);
        //添加高管的当前单据门店信息
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(Long.valueOf(String.valueOf(refundOrderResquest.getSession().getAttribute("storeId"))));
        BaseStore baseStore1 = ssmBaseStoreService.selectOne(storeRequest);
        //设置录单人信息
        if (redisClient.hasKey(getKey(refundOrderResquest.getStaffPhone()))) {
            refundOrderList.setInputId(redisClient.get(getKey(refundOrderResquest.getStaffPhone())).getId());
            refundOrderList.setInputBy(redisClient.get(getKey(refundOrderResquest.getStaffPhone())).getStaffName());
        }
        Set<String> keys = redisClient.keys(getKey(refundOrderResquest.getStaffPhone()) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            StaffResponse staffResponse = redisClient.get(key);
            refundOrderList.setInputId(staffResponse.getId());
            refundOrderList.setInputBy(staffResponse.getStaffName());
        }
        if (0 == refundOrderList.getType()) {//充值退
            RefundRechargeRequest rechargeRequest = JSON.parseObject(refundOrderResquest.getRechargeRequest(),RefundRechargeRequest.class);

            //校验退款的赠送金额

            //查询退款充值类型的所有充值单

            //查询退款充值类型的所有退款单

            //校验充值退款金额和充值账户剩余可用金额大小
            if (BigDecimalUtils.compareTo(rechargeRequest.getRecRefundMoney(), rechargeRequest.getCardConsumeMoney()) == 1
                    && rechargeRequest.getRecRefundMoney().compareTo(rechargeRequest.getCardRestMoney())!=0) {
                throw new SmsException(ResponseCode.PRICE_COMPARE_MORE_THAN, "账户可用余额为："+rechargeRequest.getCardConsumeMoney()+",退款金额比充值账户剩余可用金额");
            }

            List<Salesman> salesmens = rechargeRequest.getSalesmens();
            for (Salesman salesmen : salesmens) {
                salesmen.setStoreNum(baseStore1.getStoreNum());
                salesmen.setStoreName(baseStore1.getStoreName());
                salesmen.setStoreIdOrder(baseStore1.getId());
                salesmen.setOperatorBy(refundOrderList.getInputBy());
            }
            rechargeRequest.setStoreId(refundOrderResquest.getStoreId());
            rechargeRequest.setStoreName(rechargeRequest.getStoreName());
            refundOrderList.setStoreId(refundOrderResquest.getStoreId());
            refundOrderList.setSourceDocNum(rechargeRequest.getRechargeNum());
//            refundOrderList.setRefundNum(rechargeRequest.getRechargeNum());
//            rechargeRequest.setRechargeAccountGiveList(refundOrderResquest.getRechargeAccountGiveList());
            ssmRefundRechargeService.addRefundRecharge(rechargeRequest, refundOrderList);
            //修改或者删除充值卡信息
//            RechargeListRequest request = JSON.parseObject(refundOrderResquest.getRechargeRequest(), RechargeListRequest.class);
//            System.out.println(request);

//            ssmRechargeService.updateStaff(rechargeRequest);

        }
        else if (1 == refundOrderList.getType()) {
            //疗程退

//            List<RefundCourseRequest> courseListRequest = ObjectMapperUtil.toObject(refundOrderResquest.getCourseListRequest(),List.class);
//            String st = refundOrderResquest.getCourseListRequest();
//            List<RefundCourseRequest> refundCourseRequests = JSON.parseArray(st, RefundCourseRequest.class);

            JSONArray jsonArray = JSONObject.parseArray(refundOrderResquest.getCourseListRequest());
            List<RefundCourseRequest> courseListRequest = new ArrayList<>();
            if (jsonArray.size() > 0) {
                for (int j = 0; j < jsonArray.size(); j++) {
                    JSONObject refundCourseObject = jsonArray.getJSONObject(j);
                    RefundCourseRequest refundCourseRequest = refundCourseObject.toJavaObject(RefundCourseRequest.class);
                    JSONArray staffArray = refundCourseObject.getJSONArray("staffLists");
                    List<StaffRequest> staffLists = staffArray.toJavaList(StaffRequest.class);
                    refundCourseRequest.setStaffLists(staffLists);
                    courseListRequest.add(refundCourseRequest);
                }
            }
            for (RefundCourseRequest refundCourseRequest : courseListRequest) {
                refundCourseRequest.setStoreId(refundOrderResquest.getStoreId());
//                DebtList debtList = new DebtList();
//                debtList.setAccountId(refundCourseRequest.getCourseAccountId());
//                DebtList debtList1 = ssmDebtService.selectOne(debtList);
//                if(null != debtList1){
//                    if(debtList1.getState()==0){
//                        throw new SmsException(ResponseCode.DATA_NOT_ALLOW_UPDATESSSS, "该账户存在欠款，不支持疗程退，请先还款或者取消欠款");
//                    }
//                }
                List<Salesman> salesmens = refundCourseRequest.getSalesmens();
                for (Salesman salesmen : salesmens) {
                    salesmen.setStoreNum(baseStore1.getStoreNum());
                    salesmen.setStoreName(baseStore1.getStoreName());
                    salesmen.setStoreIdOrder(baseStore1.getId());
                    salesmen.setOperatorBy(refundOrderList.getInputBy());
                }
            }

            refundOrderList.setStoreId(refundOrderResquest.getStoreId());
//            for (RefundCourseRequest refundCourseRequest : courseListRequest) {
//                //设置退款项目的金额
//                refundCourseRequest.setCourseProjectMoney(refundCourseRequest.getCourseProjectMoney());
//                //补偿金额，
//                refundCourseRequest.setCourseCompensation(refundCourseRequest.getCourseCompensation());
//                //疗程开卡的标准次数
//                refundCourseRequest.setCourseCount(refundCourseRequest.getCourseCount());
//                //疗程剩余次数
//                refundCourseRequest.setCourseRestCount(refundCourseRequest.getCourseRestCount());
//                //
//            }
            ssmRefundCourseService.addRefundCourse(courseListRequest, refundOrderList);
        }
        else  if (2 == refundOrderList.getType()) {
            //消费退
//            List<RefundCashReqest> cashRequestList = ObjectMapperUtil.toObject(refundOrderResquest.getCashRequestList(),List.class);
            JSONArray jsonArray = JSONObject.parseArray(refundOrderResquest.getCashRequestList());
            List<RefundCashReqest> cashRequestList = new ArrayList<>();
            if (jsonArray.size() > 0) {
                for (int j = 0; j < jsonArray.size(); j++) {
                    JSONObject refundCashObject = jsonArray.getJSONObject(j);
                    RefundCashReqest refundCashRequest = refundCashObject.toJavaObject(RefundCashReqest.class);
                    List<StaffRequest> largeList = refundCashObject.getJSONArray("largeList").toJavaList(StaffRequest.class);
                    List<StaffRequest> zhonggongList = refundCashObject.getJSONArray("zhonggongList").toJavaList(StaffRequest.class);
                    List<StaffRequest> technicianList = refundCashObject.getJSONArray("technicianList").toJavaList(StaffRequest.class);
                    List<StaffRequest> smallList = refundCashObject.getJSONArray("smallList").toJavaList(StaffRequest.class);
                    List<Salesman> salesmens = new ArrayList<>();
                    salesmens = refundCashObject.getJSONArray("salesmens").toJavaList(Salesman.class);
                    refundCashRequest.setLargeList(largeList);
                    refundCashRequest.setZhonggongList(zhonggongList);
                    refundCashRequest.setTechnicianList(technicianList);
                    refundCashRequest.setSmallList(smallList);
                    refundCashRequest.setSalesmens(salesmens);
                    cashRequestList.add(refundCashRequest);
                }
            }
            for (RefundCashReqest refundCashReqest : cashRequestList) {
                RefundCash refundCash = new RefundCash();
                refundCash.setCashId(refundCashReqest.getCashId());
                List<RefundCash> select = ssmRefundCashService.select(refundCash);
                if(select.size()>0){
                    throw new SmsException(ResponseCode.MSG,"该收银单已经存在退款记录");
                }
            }
            //ssmRefundCashService.addRefundCash(cashRequestList, refundOrderList);
            ssmRefundCashService.addRefundCashSalem(cashRequestList, refundOrderList,baseStore1);
        }
        else  if (3 == refundOrderList.getType()) {
            //消费退
//            List<RefundCashReqest> cashRequestList = ObjectMapperUtil.toObject(refundOrderResquest.getCashRequestList(),List.class);
            JSONArray jsonArray = JSONObject.parseArray(refundOrderResquest.getCashRoomRequestList());
            List<RefundRoomCashRequest> cashRequestList = new ArrayList<>();
            if (jsonArray.size() > 0) {
                for (int j = 0; j < jsonArray.size(); j++) {
                    JSONObject refundCashObject = jsonArray.getJSONObject(j);
                    RefundRoomCashRequest refundCashRequest = refundCashObject.toJavaObject(RefundRoomCashRequest.class);
//                    List<StaffRequest> largeList = refundCashObject.getJSONArray("largeList").toJavaList(StaffRequest.class);
//                    List<StaffRequest> zhonggongList = refundCashObject.getJSONArray("zhonggongList").toJavaList(StaffRequest.class);
//                    List<StaffRequest> technicianList = refundCashObject.getJSONArray("technicianList").toJavaList(StaffRequest.class);
//                    List<StaffRequest> smallList = refundCashObject.getJSONArray("smallList").toJavaList(StaffRequest.class);
//                    List<Salesman> salesmens = new ArrayList<>();
//                    salesmens = refundCashObject.getJSONArray("salesmens").toJavaList(Salesman.class);
//                    refundCashRequest.setLargeList(largeList);
//                    refundCashRequest.setZhonggongList(zhonggongList);
//                    refundCashRequest.setTechnicianList(technicianList);
//                    refundCashRequest.setSmallList(smallList);
//                    refundCashRequest.setSalesmens(salesmens);
                    cashRequestList.add(refundCashRequest);
                }
            }
            for (RefundRoomCashRequest refundCashReqest : cashRequestList) {
                RefundRoomCash refundCash = new RefundRoomCash();
                refundCash.setRoomCashId(refundCashReqest.getRoomCashId());
                List<RefundRoomCash> select = ssmRefundRoomCashService.select(refundCash);
                if(select.size()>0){
                    throw new SmsException(ResponseCode.MSG,"该收银单已经存在退款记录");
                }
            }
            //ssmRefundCashService.addRefundCash(cashRequestList, refundOrderList);
            ssmRefundRoomCashService.addRefundCashSalem(cashRequestList, refundOrderList,baseStore1);
        }
        try {
            i = dao.saveNotNull(refundOrderList);
        } catch (Exception e) {
            log.error("SsmRefundOrderServiceImpl.addRefundOrder", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        //将文件上传信息保存到数据库
        List<UploadFiles> list = refundOrderResquest.getUploadFiles();
        for (UploadFiles uploadFiles : list) {
            uploadFiles.setDocId(refundId);
            uploadFiles.setDocNum(refundNum);
            if (0 == refundOrderList.getType()) {
                uploadFiles.setDocType(Constant.doc_type_refund_recharge);
            } else if (1 == refundOrderList.getType()) {
                uploadFiles.setDocType(Constant.doc_type_refund_course);
            } else {
                uploadFiles.setDocType(Constant.doc_type_refund_cash);
            }

            ssmUploadFilesService.add(uploadFiles);
        }
        return i;
    }


    @Override
    public int updateRefundOrder(RefundOrderResquest refundOrderResquest) throws SmsException, IOException {
        int i = 0;
        RefundOrderList refundOrderList = new RefundOrderList();
        BeanUtils.copyProperties(refundOrderResquest, refundOrderList);
        refundOrderList.setRefundDate(new Date());
        refundOrderList.setStoreId(refundOrderResquest.getStoreId());
        //设置录单人信息
        if (redisClient.hasKey(getKey(refundOrderResquest.getStaffPhone()))) {
            refundOrderList.setInputId(redisClient.get(getKey(refundOrderResquest.getStaffPhone())).getId());
            refundOrderList.setInputBy(redisClient.get(getKey(refundOrderResquest.getStaffPhone())).getStaffName());
        }
        Set<String> keys = redisClient.keys(getKey(refundOrderResquest.getStaffPhone()) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            StaffResponse staffResponse = redisClient.get(key);
            refundOrderList.setInputId(staffResponse.getId());
            refundOrderList.setInputBy(staffResponse.getStaffName());
        }
        if (0 == refundOrderList.getType()) {//充值退
            RefundRechargeRequest rechargeRequest =  JSON.parseObject(refundOrderResquest.getRechargeRequest(),RefundRechargeRequest.class);
            //校验充值退款金额和充值账户剩余可用金额大小
            if (BigDecimalUtils.compareTo(rechargeRequest.getRecRefundMoney(), rechargeRequest.getCardConsumeMoney()) == 1) {
                throw new SmsException(ResponseCode.PRICE_COMPARE_MORE_THAN, "退款金额比充值账户剩余可用金额");
            }



//            StoreParament storeParament = StoreParaUtils.getStorePara(rechargeRequest.getStoreId(), Constant.editOrderNum);
//            int days = (int) DateUtils.getDayDiff(rechargeRequest.getRefundDate(), new Date());
//            if(!"0".equals(storeParament.getParamentValue())) {
//                if (Integer.parseInt(storeParament.getParamentValue()) < days) {
//                    throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSIONS, "单据超过允许修改时间");
//                }
//            }


            ssmRefundRechargeService.updateRefundRecharge(rechargeRequest, refundOrderList);
        }
        else if (1 == refundOrderList.getType()) {
            //疗程退
//            List<RefundCourseRequest> courseListRequest = ObjectMapperUtil.toObject(refundOrderResquest.getCourseListRequest(),List.class);
            JSONArray jsonArray = JSONObject.parseArray(refundOrderResquest.getCourseListRequest());
            List<RefundCourseRequest> courseListRequest = new ArrayList<>();
            if (jsonArray.size() > 0) {
                for (int j = 0; j < jsonArray.size(); j++) {
                    JSONObject refundCourseObject = jsonArray.getJSONObject(j);
                    RefundCourseRequest refundCourseRequest = refundCourseObject.toJavaObject(RefundCourseRequest.class);
                    JSONArray staffArray = refundCourseObject.getJSONArray("staffLists");
                    List<StaffRequest> staffLists = staffArray.toJavaList(StaffRequest.class);
                    refundCourseRequest.setStaffLists(staffLists);
                    courseListRequest.add(refundCourseRequest);
                }
            }
            BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(refundOrderResquest.getStoreId());
            for (RefundCourseRequest refundCourseRequest : courseListRequest) {
                refundCourseRequest.setStoreId(refundOrderResquest.getStoreId());
                List<Salesman> salesmens = refundCourseRequest.getSalesmens();
                for (Salesman salesmen : salesmens) {
                    salesmen.setStoreNum(baseStore1.getStoreNum());
                    salesmen.setStoreName(baseStore1.getStoreName());
                    salesmen.setStoreIdOrder(baseStore1.getId());
                    salesmen.setOperatorBy(refundOrderList.getInputBy());
                }
            }
            ssmRefundCourseService.updateRefundCourse(courseListRequest, refundOrderList);
        }
        else  if (2 == refundOrderList.getType()){
            //消费退
//            List<RefundCashReqest> cashRequestList = ObjectMapperUtil.toObject(refundOrderResquest.getCashRequestList(),List.class);
            JSONArray jsonArray = JSONObject.parseArray(refundOrderResquest.getCashRequestList());
            List<RefundCashReqest> cashRequestList = new ArrayList<>();
            if(jsonArray==null||jsonArray.size()==0){
                throw new SmsException(ResponseCode.MSG,"请选择要退的项目！");
            }
            if (jsonArray.size() > 0) {
                for (int j = 0; j < jsonArray.size(); j++) {
                    JSONObject refundCourseObject = jsonArray.getJSONObject(j);
                    RefundCashReqest refundCashRequest = refundCourseObject.toJavaObject(RefundCashReqest.class);
                    List<StaffRequest> largeList = refundCourseObject.getJSONArray("largeList").toJavaList(StaffRequest.class);
                    List<StaffRequest> zhonggongList = refundCourseObject.getJSONArray("zhonggongList").toJavaList(StaffRequest.class);
                    List<StaffRequest> technicianList = refundCourseObject.getJSONArray("technicianList").toJavaList(StaffRequest.class);
                    List<StaffRequest> smallList = refundCourseObject.getJSONArray("smallList").toJavaList(StaffRequest.class);
                    refundCashRequest.setLargeList(largeList);
                    refundCashRequest.setZhonggongList(zhonggongList);
                    refundCashRequest.setTechnicianList(technicianList);
                    refundCashRequest.setSmallList(smallList);
                    cashRequestList.add(refundCashRequest);
                }
            }

//            StoreParament storeParament = StoreParaUtils.getStorePara(cashRequestList.get(0).getStoreId(), Constant.editOrderNum);
//            int days = (int) DateUtils.getDayDiff(cashRequestList.get(0).getRefundDate(), new Date());
//            if(!"0".equals(storeParament.getParamentValue())) {
//                if (Integer.parseInt(storeParament.getParamentValue()) < days) {
//                    throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSIONS, "单据超过允许修改时间");
//                }
//            }

            ssmRefundCashService.updateRefundCash(cashRequestList, refundOrderList);
        }
        else  if (3 == refundOrderList.getType()){
            //消费退
//            List<RefundCashReqest> cashRequestList = ObjectMapperUtil.toObject(refundOrderResquest.getCashRequestList(),List.class);
            JSONArray jsonArray = JSONObject.parseArray(refundOrderResquest.getCashRoomRequestList());
            List<RefundRoomCashRequest> cashRequestList = new ArrayList<>();
//            StoreParament storeParament = StoreParaUtils.getStorePara(cashRequestList.get(0).getStoreId(), Constant.editOrderNum);
//            int days = (int) DateUtils.getDayDiff(cashRequestList.get(0).getRefundDate(), new Date());
//            if(!"0".equals(storeParament.getParamentValue())) {
//                if (Integer.parseInt(storeParament.getParamentValue()) < days) {
//                    throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSIONS, "单据超过允许修改时间");
//                }
//            }

            ssmRefundRoomCashService.updateRefundCash(cashRequestList, refundOrderList);
        }
        try {
//            refundOrderList.setStoreId(null);
//            refundOrderList.setStoreNum(null);
//            refundOrderList.setStoreName(null);
            i = dao.updateByPrimaryKeySelective(refundOrderList);

        } catch (Exception e) {
            log.error("SsmRefundOrderServiceImpl.updateRefundOrder", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }


        //获取修改后文件上传list 新增信息
        List<UploadFiles> list = refundOrderResquest.getUploadFiles();
        //存在文件更新信息 文件先删除 后新增
        if (null != list && list.size() > 0) {
            UploadFiles files = new UploadFiles();
            files.setDocId(refundOrderList.getId());
            files.setDocNum(refundOrderList.getRefundNum());
            if (0 == refundOrderList.getType()) {
                files.setDocType(Constant.doc_type_refund_recharge);
            } else if (1 == refundOrderList.getType()) {
                files.setDocType(Constant.doc_type_refund_course);
            } else {
                files.setDocType(Constant.doc_type_refund_cash);
            }
            //查询原来对应单据的文件list
            List<UploadFiles> oldList = ssmUploadFilesService.select(files);
            //数据库文件信息删除
            FtpUtils ftpUtils = new FtpUtils();
//        oldList.stream().forEach(uploadFiles -> ssmUploadFilesService.deleteByPrimaryKey(uploadFiles.getId()));
//        //文件服务器文件删除
//        oldList.stream().forEach(uploadFiles -> {
//            try {
//                ftpUtils.deleteFile(uploadFiles.getFilePath(),uploadFiles.getFileName());
//            } catch (IOException e) {
//                log.error("SsmRefundOrderServiceImpl.updateRefundOrder",e);
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            }
//        });
            for (UploadFiles uploadFiles : oldList) {
                ssmUploadFilesService.deleteByPrimaryKey(uploadFiles.getId());
                ftpUtils.deleteFile(uploadFiles.getFilePath(), uploadFiles.getFileName());
            }

            for (UploadFiles uploadFiles : list) {
                uploadFiles.setDocId(refundOrderList.getId());
                uploadFiles.setDocNum(refundOrderList.getRefundNum());
                if (0 == refundOrderList.getType()) {
                    uploadFiles.setDocType(Constant.doc_type_refund_recharge);
                } else if (1 == refundOrderList.getType()) {
                    uploadFiles.setDocType(Constant.doc_type_refund_course);
                } else {
                    uploadFiles.setDocType(Constant.doc_type_refund_cash);
                }
                ssmUploadFilesService.add(uploadFiles);
            }
        }
        return i;
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public int sendAudit(RefundOrderResquest refundOrderResquest) throws SmsException {
        int i = 0;
        RefundOrderList refundOrderList = dao.selectByPrimaryKey(refundOrderResquest.getId());
        //校验用户上传文件记录单
        //this.checkFile(refundOrderList);
        //校验单据状态
        if(refundOrderList.getState()==null){
            refundOrderList.setState(0);
        }
        if ( refundOrderList.getState() == 3 || refundOrderList.getState() == 1) {
            throw new SmsException(ResponseCode.NOT_ALLOW_UPDATE_STATE, "送审");
        }
        refundOrderList.setState(1);//送审 修改状态
        //锁定账户
        //ssmRechargeAccountService.
        if (0 == refundOrderList.getType()) {
            RefundRecharge refundRecharge = new RefundRecharge();
            refundRecharge.setRefundNum(refundOrderList.getRefundNum());
            //refundRecharge.setStoreId(refundOrderList.getStoreId());
            List<RefundRecharge> select = ssmRefundRechargeService.select(refundRecharge);
            refundRecharge =select.get(0);
           /* if(BigDecimalUtils.compareTo(refundOrderList.getRecRefundMoney(),refundRecharge.get)){

            }*/
            //通过账号可以余额和充值退金额，判断是否部分退还是全额退
            StoreRequest storeRequest = new StoreRequest();
            storeRequest.setId(refundRecharge.getStoreId());
            List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
            List<Long> objects = new ArrayList<>();
            for (BaseStores pagesorganization : pagesorganizations) {
                objects.add(pagesorganization.getId());
            }


            RechargeAccountRequest rechargeAccountRequest = new RechargeAccountRequest();
            rechargeAccountRequest.setMemberId(refundRecharge.getMemberId());
            rechargeAccountRequest.setStoreIdl(objects);
            rechargeAccountRequest.setRechargeTypeId(refundRecharge.getRechargeTypeId());
            List<RechargeAccount> rechargeAccounts = ssmRechargeAccountService.newcashSelectList(rechargeAccountRequest);
            //账户余额 > 退金额 == 部分退
            if(!(BigDecimalUtils.compareTo(rechargeAccounts.get(0).getCardConsumeMoney(),refundRecharge.getRecRefundMoney())==1)){
                ssmRechargeAccountService.updateState(refundRecharge.getRecAccountId(), 0);
            }
        }
        else if (1 == refundOrderList.getType()) {
            RefundCourse refundCourse = new RefundCourse();
            refundCourse.setRefundNum(refundOrderList.getRefundNum());
            refundCourse.setStoreId(refundOrderList.getStoreId());
            List<RefundCourse> refundCourseList = ssmRefundCourseService.select(refundCourse);
            refundCourseList.stream().forEach(refundCourse1 -> ssmCourseAccountService.updateState(refundCourse1.getCourseAccountId(), 0));
            ssmRefundCourseService.sendAudit(refundOrderList);
        }
        i = dao.updateByPrimaryKeySelective(refundOrderList);
        return i;
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public int revokeAudit(RefundOrderResquest refundOrderResquest) throws SmsException {
        int i = 0;
        RefundOrderList refundOrderList = dao.selectByPrimaryKey(refundOrderResquest.getId());
        //this.checkFile(refundOrderList);
        //校验单据状态 0123
//        if (refundOrderList.getState() != 1 || refundOrderList.getState() != 4) {
        if (refundOrderList.getState() == 3) {
            throw new SmsException(ResponseCode.NOT_ALLOW_UPDATE_STATE, "回收");
        }
        refundOrderList.setState(2);//回收 修改状态
        //解锁账户
        if (0 == refundOrderList.getType()) {
            RefundRecharge refundRecharge = new RefundRecharge();
            refundRecharge.setRefundNum(refundOrderList.getRefundNum());
            refundRecharge.setStoreId(refundOrderList.getStoreId());
            refundRecharge = ssmRefundRechargeService.select(refundRecharge).get(0);
            ssmRechargeAccountService.updateState(refundRecharge.getRecAccountId(), 1);
        } else if (1 == refundOrderList.getType()) {
            RefundCourse refundCourse = new RefundCourse();
            refundCourse.setRefundNum(refundOrderList.getRefundNum());
            refundCourse.setStoreId(refundOrderList.getStoreId());
            List<RefundCourse> refundCourseList = ssmRefundCourseService.select(refundCourse);
            refundCourseList.stream().forEach(refundCourse1 -> ssmCourseAccountService.updateState(refundCourse1.getCourseAccountId(), 1));
            //进行次数增加
            ssmRefundCourseService.revokeAudit(refundOrderList);
        }
        i = dao.updateByPrimaryKeySelective(refundOrderList);
        return i;
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public int audit(RefundOrderResquest refundOrderResquest) throws SmsException {
        int i = 0;
        RefundOrderList refundOrderList = dao.selectByPrimaryKey(refundOrderResquest.getId());
        //this.checkFile(refundOrderList);

        //设置审核人人信息
        if (redisClient.hasKey(getKey(refundOrderResquest.getStaffPhone()))) {
            refundOrderList.setAuditId(redisClient.get(getKey(refundOrderResquest.getStaffPhone())).getId());
            refundOrderList.setAuditBy(redisClient.get(getKey(refundOrderResquest.getStaffPhone())).getStaffName());
            refundOrderList.setAuditDate(new Date());
        }
        Set<String> keys = redisClient.keys(getKey(refundOrderResquest.getStaffPhone()) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            StaffResponse staffResponse = redisClient.get(key);
            refundOrderList.setAuditId(staffResponse.getId());
            refundOrderList.setAuditBy(staffResponse.getStaffName());
            refundOrderList.setAuditDate(new Date());
        }
        refundOrderList.setState(3);
        //退款类别
        if (refundOrderList.getType() == 0) {
            int audit = ssmRefundRechargeService.audit(refundOrderList);
            if(audit==9 || "9".equals(audit)){
                //当前单据作废
                refundOrderList.setState(5);
            }
            Salesman salesman = new Salesman();
            salesman.setOrderNum(String.valueOf(refundOrderList.getRefundNum()));
            salesman.setOrderType(4);
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            for (Salesman salesman1 : salesmen) {
                salesman1.setState(0);
                salesman1.setOrderDate(new Date());
                int i1 = ssmSalesmanService.updateByPrimaryKey(salesman1);
                System.out.println(i1);
            }
        } else if (refundOrderList.getType() == 1) {
            ssmRefundCourseService.audit(refundOrderList);

            Salesman salesman = new Salesman();
            salesman.setOrderNum(String.valueOf(refundOrderList.getRefundNum()));
            salesman.setOrderType(5);
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            for (Salesman salesman1 : salesmen) {
                salesman1.setState(0);
                salesman1.setOrderDate(new Date());
                int i1 = ssmSalesmanService.updateByPrimaryKey(salesman1);
                System.out.println(i1);
            }
        } else  if (refundOrderList.getType() == 2) {
            ssmRefundCashService.audit(refundOrderList);
            Salesman salesman = new Salesman();
            salesman.setOrderNum(String.valueOf(refundOrderList.getRefundNum()));
            salesman.setOrderType(6);
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            for (Salesman salesman1 : salesmen) {
                salesman1.setState(0);
                salesman1.setOrderDate(new Date());
                int i1 = ssmSalesmanService.updateByPrimaryKey(salesman1);
                System.out.println(i1);
            }
        }else  if (refundOrderList.getType() == 3) {
            ssmRefundRoomCashService.audit(refundOrderList);
        }
        try {
            i = dao.updateByPrimaryKeySelective(refundOrderList);
        } catch (Exception e) {
            log.error("SsmRefundOrderServiceImpl.audit", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        if(refundOrderList.getState()==5){
            i=9;
        }
        return i;
    }

    @Override
    public StoreDaily selectDayRecord(StoreDailyRequest storeDailyRequest) {
        return dao.selectDayRecord(storeDailyRequest);
    }

    @Override
    public List<StoreDaily> selectRefund(StoreDailyRequest storeDailyRequest) {
        return dao.selectRefund(storeDailyRequest);
    }

    @Override
    public List<RefundDayVo> selectByDay(List<Long> storeIds, Date startTime, Date endTime) {
        return dao.selectByDay(storeIds,startTime,endTime);
    }
@Autowired
private RefundOrderListMapper mapper;
    @Override
    public List<RefundOrderList> selectNew(RefundOrderResquest refundOrderList1) {
        return mapper.selectNew(refundOrderList1);
    }

    @Override
    public PageInfo<RefundOrderList> refundByMemberId(RefundOrderResquest refundOrderResquest) {
        return dao.refundByMemberId(refundOrderResquest);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int delete(RefundOrderResquest refundOrderResquest) throws SmsException {
        RefundOrderList refundOrderList = dao.selectByPrimaryKey(refundOrderResquest.getId());
        //this.checkFile(refundOrderList);
        //退款类别
        if (refundOrderList.getType() == 0) {
            RefundRecharge refundRecharge = new RefundRecharge();
            refundRecharge.setRefundNum(refundOrderList.getRefundNum());
            List<RefundRecharge> select = ssmRefundRechargeService.select(refundRecharge);
            for (RefundRecharge recharge : select) {
                int delete = ssmRefundRechargeService.delete(recharge);
                if(delete>0){
                    Salesman salesman = new Salesman();
                    salesman.setOrderNum(String.valueOf(refundOrderList.getRefundNum()));
                    salesman.setOrderType(4);
                    List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
                    for (Salesman salesman1 : salesmen) {
                        ssmSalesmanService.delete(salesman1);
                    }
                }
            }

        } else if (refundOrderList.getType() == 1) {
            RefundCourse refundCourseRequest = new RefundCourse();
            refundCourseRequest.setRefundNum(refundOrderList.getRefundNum());
            List<RefundCourse> refundCourseResponses = ssmRefundCourseService.select(refundCourseRequest);
            for (RefundCourse refundCourseRespons : refundCourseResponses) {
                int delete = ssmRefundCourseService.delete(refundCourseRespons);
                if(delete>0){
                    Salesman salesman = new Salesman();
                    salesman.setOrderNum(String.valueOf(refundOrderList.getRefundNum()));
                    salesman.setOrderType(5);
                    List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
                    for (Salesman salesman1 : salesmen) {
                        int i1 = ssmSalesmanService.delete(salesman1);
                    }
                }

            }

        } else if (refundOrderList.getType() == 2) {
            RefundCash refundCash = new RefundCash();
            refundCash.setRefundNum(refundOrderList.getRefundNum());
            List<RefundCash> select = ssmRefundCashService.select(refundCash);
            for (RefundCash cash : select) {
                int delete = ssmRefundCashService.delete(cash);
                if(delete>0){
                    Salesman salesman = new Salesman();
                    salesman.setOrderNum(String.valueOf(refundOrderList.getRefundNum()));
                    salesman.setOrderType(6);
                    List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
                    for (Salesman salesman1 : salesmen) {
                        int i1 = ssmSalesmanService.delete(salesman1);
                    }
                }
            }

        } else if (refundOrderList.getType() == 3 ) {
            RefundRoomCash refundCash = new RefundRoomCash();
            refundCash.setRefundNum(refundOrderList.getRefundNum());
            List<RefundRoomCash> select = ssmRefundRoomCashService.select(refundCash);
            for (RefundRoomCash cash : select) {
                int delete = ssmRefundRoomCashService.delete(cash);
            }
        }
        return dao.delete(refundOrderList);


    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int unAudit(RefundOrderResquest refundOrderResquest) throws SmsException {
        int i = 0;
        RefundOrderList refundOrderList = dao.selectByPrimaryKey(refundOrderResquest.getId());

        //设置审核人人信息

        refundOrderList.setState(4);
        if (redisClient.hasKey(getKey(refundOrderResquest.getStaffPhone()))) {
            refundOrderList.setAuditId(redisClient.get(getKey(refundOrderResquest.getStaffPhone())).getId());
            refundOrderList.setAuditBy(redisClient.get(getKey(refundOrderResquest.getStaffPhone())).getStaffName());
        }
        //退款类别
        if (refundOrderList.getType() == 0) {
            ssmRefundRechargeService.unAudit(refundOrderList);
            Salesman salesman = new Salesman();
            salesman.setOrderNum(String.valueOf(refundOrderList.getRefundNum()));
            salesman.setOrderType(4);
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            for (Salesman salesman1 : salesmen) {
                salesman1.setState(1);
                int i1 = ssmSalesmanService.updateByPrimaryKey(salesman1);
                System.out.println(i1);
            }
        } else if (refundOrderList.getType() == 1) {
            ssmRefundCourseService.unAudit(refundOrderList);
            Salesman salesman = new Salesman();
            salesman.setOrderNum(String.valueOf(refundOrderList.getRefundNum()));
            salesman.setOrderType(5);
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            for (Salesman salesman1 : salesmen) {
                salesman1.setState(1);
                int i1 = ssmSalesmanService.updateByPrimaryKey(salesman1);
                System.out.println(i1);
            }
        } else  if (refundOrderList.getType() == 2) {
            ssmRefundCashService.unAudit(refundOrderList);
            Salesman salesman = new Salesman();
            salesman.setOrderNum(String.valueOf(refundOrderList.getRefundNum()));
            salesman.setOrderType(6);
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            for (Salesman salesman1 : salesmen) {
                salesman1.setState(1);
                int i1 = ssmSalesmanService.updateByPrimaryKey(salesman1);
                System.out.println(i1);
            }
        }else if (refundOrderList.getType() == 3){
            ssmRefundRoomCashService.unAudit(refundOrderList);
        }
        try {
            refundOrderList.setAuditId(null);
            refundOrderList.setAuditBy("");
            refundOrderList.setAuditDate(null);
            i = dao.updateByPrimaryKeySelective(refundOrderList);
        } catch (Exception e) {
            log.error("SsmRefundOrderServiceImpl.audit", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return i;
    }



    public String getDocNum(RefundOrderList refundOrderList) {
        //查询数据库门店编码最新的一个
        String ymdDate = DateUtils.YMDFormat(new Date());
        Example example = new Example(RefundOrderList.class);
        Example.Criteria criteria = example.createCriteria();
        //按门店编码降序排列
        example.setOrderByClause("refund_num desc");
        //通过时间模糊查询
        String condition = "";
        if (refundOrderList.getType() == 0) {
            condition = "CZT";
        } else if (refundOrderList.getType() == 1) {
            condition = "LCT";
        } else if (refundOrderList.getType() == 2){
            condition = "XFT";
        }else {
            condition = "SYT";
        }
        criteria.andLike("refundNum", condition+refundOrderList.getStoreNum() + ymdDate + "%");
        criteria.andEqualTo("storeId", refundOrderList.getStoreId());
        List<RefundOrderList> lists = dao.selectByExample(example);
        String refundNum;
        String num;
        int mm = 0;
        if (lists != null && lists.size() > 0) {
            RefundOrderList refundOrder = lists.get(0);
            mm = Integer.parseInt(refundOrder.getRefundNum().substring(11+refundOrderList.getStoreNum().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);
            }
            refundNum = condition +refundOrderList.getStoreNum()+ ymdDate + num;
        } else {
            num = "0001";
            refundNum = condition +refundOrderList.getStoreNum()+ ymdDate + num;
        }
        return refundNum;
    }

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

    public void checkFile(RefundOrderList refundOrderList) throws SmsException {
        //校验用户上传文件是否存在
        UploadFilesRequest filesRequest = new UploadFilesRequest();
        filesRequest.setDocNum(refundOrderList.getRefundNum());
        if (0 == refundOrderList.getType()) {
            filesRequest.setDocType(Constant.doc_type_refund_recharge);
        } else if (1 == refundOrderList.getType()) {
            filesRequest.setDocType(Constant.doc_type_refund_course);
        } else {
            filesRequest.setDocType(Constant.doc_type_refund_cash);
        }
        List<UploadFiles> filesList = ssmUploadFilesService.selectList(filesRequest);
        if (filesList.size() == 0) {
            throw new SmsException(ResponseCode.PARAMETER_NOT_EXIST_S, "用户确认单");
        }
    }
}
