package com.ssm.controller;

import com.alibaba.fastjson.util.IOUtils;
import com.github.pagehelper.PageInfo;
import com.ssm.core.bean.GenericResponse;
import com.ssm.core.bean.PageResponse;
import com.ssm.core.util.SessionHelp;
import com.ssm.core.utils.BigDecimalUtils;
import com.ssm.core.utils.ChuangLanBeanSmsUtil;
import com.ssm.core.utils.FtpUtils;
import com.ssm.manage.entity.*;
import com.ssm.manage.extendEntity.RecDocList;
import com.ssm.manage.query.RefundOrderResquest;
import com.ssm.manage.query.RefundRechargeRequest;
import com.ssm.manage.query.UploadFilesRequest;
import com.ssm.manage.response.DocPromotionResponse;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Api(value = "退款controller", tags = {"退款相关接口"})
@RestController
@RequestMapping("/demay/ssm/refOrder")
@Slf4j
public class SsmRefundOrderController {
    @Autowired
    private SsmRefundOrderService ssmRefundOrderService;
    @Autowired
    private ChuangLanBeanSmsUtil chuangLanBeanSmsUtil;

    @Autowired
    private SsmDocPromotionProjectService ssmDocPromotionProjectService;

    @Autowired
    private SsmDocPromotionService ssmDocPromotionService;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmRefundRechargeService ssmRefundRechargeService;


    @ApiOperation(value = "分页查询  app端-退款单-分页查询退款单", httpMethod = "POST", response = PageResponse.class)
    @RequestMapping("/page")
    public PageResponse selectPage(@RequestBody RefundOrderResquest refundOrderResquest) {
        PageResponse<RefundOrderList> pageResponse = new PageResponse<>();
        PageInfo<RefundOrderList> pageInfo = new PageInfo<>();
//        refundOrderResquest.setStoreId(SessionHelp.getStoreId(session));
        try {
            pageInfo = ssmRefundOrderService.selectPage(refundOrderResquest);
        } catch (Exception e) {
            log.error("SsmRefundOrderController.selectPage", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }

    @ApiOperation(value = "退款单添加  (门店端-退款单-退款单添加)", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/add")
    public GenericResponse add(@RequestBody RefundOrderResquest refundOrderResquest) {
        GenericResponse genericResponse = new GenericResponse();
//        if (null == fileList || fileList.size() == 0) {
//            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "文件");
//            return genericResponse;
//        }
//        //上传文件
////        List<MultipartFile> fileList = refundOrderResquest.getFiles();
//        //文件信息list
//        List<UploadFiles> uploadFilesInfo = new ArrayList<>();
//        FtpUtils ftp = new FtpUtils();
//        for (MultipartFile multipartFile : fileList) {
//            UploadFiles uploadFiles = new UploadFiles();
//            String fileName = multipartFile.getOriginalFilename();//获取文件名
//            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());//获取文件后缀
//            String saveName = UUID.randomUUID() + "." + suffix;//将文件名用时间重命名
//            String path = Constant.filePath + "/" + refundOrderResquest.getStoreId();//文件上传路径
//            uploadFiles.setFileName(saveName);
//            uploadFiles.setFilePath(path);
//            uploadFilesInfo.add(uploadFiles);
//
//            InputStream inputStream = null;
//            try {
//                inputStream = multipartFile.getInputStream();
//                ftp.uploadFile(path, saveName, inputStream);
//            } catch (IOException e) {
//                log.error("SsmRefundOrderController.add:", e);
//                genericResponse.setCodeAndMsg(ResponseCode.FILE_UPLOAD_FAILED);
//                return genericResponse;
//            }
//        }
//        refundOrderResquest.setUploadFiles(uploadFilesInfo);

//        Long storeId = SessionHelp.getStoreId(session);
//        String storeName = SessionHelp.getStoreName(session);
//        String staffPhone = SessionHelp.getLoginAccount(session);
//        refundOrderResquest.setStoreId(storeId);
//        refundOrderResquest.setStoreName(storeName);
//        refundOrderResquest.setStaffPhone(staffPhone);
        int i = 0;
        try {
            if(refundOrderResquest.getRefundMoney().longValue()<0){
                throw new SmsException("010000","操作失败，不能输入负数");
            }
            i = ssmRefundOrderService.addRefundOrder(refundOrderResquest);
        } catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmRefundOrderController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
            BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(refundOrderResquest.getStoreId());
            //设置短信账户 发送 否则不发送
            if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
                try {
                    chuangLanBeanSmsUtil.sendRefundSms(baseStore, refundOrderResquest.getMobilePhone());
                } catch (IOException e) {
                    log.error("SsmRechargeController.add:", e);
                } catch (SmsException e) {
                    log.error("SsmRechargeController.add:", e);
                }
            }
        }
        return genericResponse;
    }


    @ApiOperation(value = "退款单修改  (门店端-退款单-退款单修改)", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/update")
    public GenericResponse update(@RequestBody RefundOrderResquest refundOrderResquest,HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        refundOrderResquest.setStoreId(SessionHelp.getStoreId(session));
//        //上传文件
//        if (null == fileList) {
//            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "文件");
//            return genericResponse;
//        }
//        List<MultipartFile> fileList = refundOrderResquest.getFiles();
//        //文件信息list
//        if (fileList != null) {
//            List<UploadFiles> uploadFilesInfo = new ArrayList<>();
//            FtpUtils ftp = new FtpUtils();
//            for (MultipartFile multipartFile : fileList) {
//                UploadFiles uploadFiles = new UploadFiles();
//                String fileName = multipartFile.getOriginalFilename();//获取文件名
//                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());//获取文件后缀
//                String saveName = UUID.randomUUID() + "." + suffix;//将文件名用时间重命名
//                String path = Constant.filePath + "/" + refundOrderResquest.getStoreId();//文件上传路径
//                uploadFiles.setFileName(saveName);
//                uploadFiles.setFilePath(path);
//                uploadFilesInfo.add(uploadFiles);
//                refundOrderResquest.setUploadFiles(uploadFilesInfo);
//                InputStream inputStream = null;
//                try {
//                    inputStream = multipartFile.getInputStream();
//                    ftp.uploadFile(path, saveName, inputStream);
//                } catch (IOException e) {
//                    log.error("SsmRefundOrderController.update:", e);
//                    genericResponse.setCodeAndMsg(ResponseCode.FILE_UPLOAD_FAILED);
//                    return genericResponse;
//                }
//            }
//        }
//        Long storeId = SessionHelp.getStoreId(session);
//        String storeName = SessionHelp.getStoreName(session);
//        String staffPhone = SessionHelp.getLoginAccount(session);
//        refundOrderResquest.setStoreId(storeId);
//        refundOrderResquest.setStoreName(storeName);
//        refundOrderResquest.setStaffPhone(staffPhone);
        int i = 0;
        try {
            i = ssmRefundOrderService.updateRefundOrder(refundOrderResquest);
        } catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmRefundOrderController.update:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "退款单送审  (门店端-退款单-退款单送审)", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/sendAudit")
    public GenericResponse sendAudit(@RequestBody RefundOrderResquest refundOrderResquest) {
        GenericResponse genericResponse = new GenericResponse();
//        Long storeId = SessionHelp.getStoreId(session);
//        String storeName = SessionHelp.getStoreName(session);
//        refundOrderResquest.setStoreId(storeId);
//        refundOrderResquest.setStoreName(storeName);
        int i = 0;
        try {
            i = ssmRefundOrderService.sendAudit(refundOrderResquest);
        } catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmRefundOrderController.sendAudit:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "退款单回收  (门店端-退款单-退款单回收)", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/revokeAudit")
    public GenericResponse revokeAudit(@RequestBody RefundOrderResquest refundOrderResquest) {
        GenericResponse genericResponse = new GenericResponse();
//        Long storeId = SessionHelp.getStoreId(session);
//        String storeName = SessionHelp.getStoreName(session);
//        refundOrderResquest.setStoreId(storeId);
//        refundOrderResquest.setStoreName(storeName);

        int i = 0;
        try {
            i = ssmRefundOrderService.revokeAudit(refundOrderResquest);
        } catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmRefundOrderController.revokeAudit:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "退款单审核  (门店端-退款单-退款单审核)", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/audit")
    public GenericResponse audit(@RequestBody RefundOrderResquest refundOrderResquest) {
        GenericResponse genericResponse = new GenericResponse();
//        refundOrderResquest.setStaffPhone(SessionHelp.getLoginAccount(session));
        int i = 0;
        try {
            i = ssmRefundOrderService.audit(refundOrderResquest);
        } catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmRefundOrderController.audit:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }


    @ApiOperation(value = "退款单反审核  (门店端-退款单-退款单反审核)", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/unAudit")
    public GenericResponse unAudit(@RequestBody RefundOrderResquest refundOrderResquest) {
        GenericResponse genericResponse = new GenericResponse();
//        refundOrderResquest.setStaffPhone(SessionHelp.getLoginAccount(session));
        int i = 0;
        try {
            i = ssmRefundOrderService.unAudit(refundOrderResquest);
        } catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmRefundOrderController.unAudit:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }


    @ApiOperation(value = "退款单文件下载  (门店端-退款单-退款单文件下载)", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/download")
    public void download(@RequestBody UploadFilesRequest uploadFilesRequest, HttpServletResponse response) {


        FtpUtils ftpUtils = new FtpUtils();
        InputStream is = null;
        OutputStream os = null;
        try {
            byte[] b =  ftpUtils.download(uploadFilesRequest.getFilePath(), uploadFilesRequest.getFileName());

            if (response != null) {
                os = response.getOutputStream();
                // 设置响应头
                // 文件编码 处理文件名中的 '+'、' ' 特殊字符
                String encoderName = URLEncoder.encode(uploadFilesRequest.getFileName(), "UTF-8").replace("+", "%20").replace("%2B", "+");
                response.setHeader("Content-Disposition", "attachment;filename=\"" + encoderName + "\"");
                response.setContentType("application/octet-stream;charset=UTF-8");
                response.setHeader("Accept-Ranges", "bytes");

            }
            is = new ByteArrayInputStream(b);
            byte[] buffer = new byte[1024 * 5];
            int len = 0;
            while ((len = is.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
            os.flush();
        } catch (Exception e) {
            log.error("SsmRefundOrderController.download:", e);
        }finally {
            // 关闭流
            IOUtils.close(is);
            IOUtils.close(os);
        }
    }


    @ApiOperation(value = "疗程退促销活动项目展示  (门店端-退款单-疗程退促销活动项目展示)", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/promotionPro")
    public GenericResponse promotionPro(@RequestParam String courseNum, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        DocPromotion docPromotion = new DocPromotion();
        docPromotion.setStoreId(storeId);
        docPromotion.setDocNum(courseNum);
        List<DocPromotion> list = new ArrayList<>();
        DocPromotionResponse docPromotionResponse = new DocPromotionResponse();
        try {
            list = ssmDocPromotionService.select(docPromotion);
            for (DocPromotion promotion : list) {
                BeanUtils.copyProperties(promotion, docPromotionResponse);
                DocPromotionProject docPromotionProject = new DocPromotionProject();
                docPromotionProject.setStoreId(storeId);
                docPromotionProject.setDocNum(promotion.getDocNum());
                List<DocPromotionProject> promotionProjects = ssmDocPromotionProjectService.select(docPromotionProject);
                docPromotionResponse.setPromotionProjects(promotionProjects);
            }
        }catch (Exception e) {
            log.error("SsmRefundOrderController.promotionPro:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setData(docPromotionResponse);
        return genericResponse;
    }


    @ApiOperation(value = "充值退账户对应单据查询  (门店端-退款单-充值退账户对应单据查询)", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/recDocList")
    public GenericResponse recDocList(@RequestBody RefundRechargeRequest rechargeRequest) {
        GenericResponse genericResponse = new GenericResponse();
//        Long storeId = SessionHelp.getStoreId(session);
//        String storeName = SessionHelp.getStoreName(session);
//        rechargeRequest.setStoreId(storeId);
//        rechargeRequest.setStoreName(storeName);
        List<RecDocList> lists = new ArrayList<>();
        try {
            lists = ssmRefundRechargeService.recDocList(rechargeRequest);
        } catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmRefundOrderController.recDocList:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setRows(lists);
        genericResponse.setCodeAndMsg(ResponseCode.OK);

        return genericResponse;
    }

    @ApiOperation(value = "充值退账户对应历史单据查询 金额反算使用  (门店端-退款单-充值退账户对应历史单据查询 金额反算使用)", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/refundRechargeMoney")
    public GenericResponse refundRechargeList(@RequestBody RefundRechargeRequest rechargeRequest) {
        GenericResponse genericResponse = new GenericResponse();
//        Long storeId = SessionHelp.getStoreId(session);
//        String storeName = SessionHelp.getStoreName(session);
//        rechargeRequest.setStoreId(storeId);
//        rechargeRequest.setStoreName(storeName);
//        List<RechargeList> lists = new ArrayList<>();
        BigDecimal refundMoney = BigDecimalUtils.bigDecimal("0");
        try {
            refundMoney = ssmRefundRechargeService.refundRechargeMoney(rechargeRequest);
        } catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmRefundOrderController.refundRechargeMoney:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setData(refundMoney);
        genericResponse.setCodeAndMsg(ResponseCode.OK);

        return genericResponse;
    }
}
