package com.ssm.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.github.pagehelper.PageInfo;
import com.ssm.manage.response.GenericResponse;
import com.ssm.manage.response.PageResponse;
import com.ssm.manage.utils.SessionHelp;
import com.ssm.core.utils.AESUtils;
import com.ssm.core.utils.FtpUtils;
import com.ssm.manage.entity.*;
import com.ssm.manage.excelEntity.ExcelGroup;
import com.ssm.manage.query.*;
import com.ssm.manage.response.BaseGrouponCardResponse;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.SsmBaseGrouponCardService;
import com.ssm.manage.service.SsmBaseGrouponListService;
import com.ssm.manage.service.SsmBaseStoreService;
import com.ssm.manage.utils.Constant;
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.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Api(value="团购卡记录controller",tags={"团购卡记录controller相关接口"})
@RestController
@RequestMapping("/demay/ssm/baseGrouponCard")
@Slf4j
public class SsmBaseGrouponCardController {
    @Autowired
    private SsmBaseGrouponCardService ssmBaseGrouponCardService;
    @Autowired
    private SsmBaseGrouponListService ssmBaseGrouponListService;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @ApiOperation(value = "查询全部员工排班",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/page")
    public PageResponse selectPage(@RequestBody BaseGrouponCardRequest baseGrouponCardRequest, HttpSession session){
        PageResponse<BaseGrouponCardResponse> pageResponse = new PageResponse<>();
        PageInfo<BaseGrouponCardResponse> pageInfo = new PageInfo<>();
        Long storeId = SessionHelp.getStoreId(session);
        baseGrouponCardRequest.setStoreId(storeId);
        try {
            pageInfo = ssmBaseGrouponCardService.selectPage(baseGrouponCardRequest);
        }catch (Exception e){
            log.error("SsmCashController.selectPage:",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
//        pageResponse.setData(pageInfo.getList());
        return pageResponse;
    }

    @ApiOperation(value = "添加团购卡单据",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/add")
    public GenericResponse add(List<MultipartFile> fileList, BaseGrouponCardRequest baseGrouponCardRequest,HttpSession session){
        GenericResponse<BaseGrouponCard> 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 + "/" + SessionHelp.getStoreId(session);//文件上传路径
            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;
            }
        }
        baseGrouponCardRequest.setUploadFiles(uploadFilesInfo);


        if (StringUtils.isBlank(baseGrouponCardRequest.getRechargeTypeNum())){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"充值卡种项目类别");
            return genericResponse;
        }
        if(null == baseGrouponCardRequest.getQuantity()||baseGrouponCardRequest.getQuantity()<=0){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"团购份数不能为0或空");
            return genericResponse;
        }
        if(null == baseGrouponCardRequest.getRechargeMoney()&&baseGrouponCardRequest.getRechargeMoney().compareTo(BigDecimal.valueOf(0)) != -1){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"金额不能为0或空");
            return genericResponse;
        }

        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String key = SessionHelp.getLoginAccount(session);
        baseGrouponCardRequest.setStoreId(storeId);
        baseGrouponCardRequest.setStoreName(storeName);
        int i = 0;
        try {
            i = ssmBaseGrouponCardService.add(baseGrouponCardRequest,key);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmProjectTypeController.add",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0){
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "修改团购卡单据",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/update")
    public GenericResponse update(List<MultipartFile> fileList,BaseGrouponCardRequest baseGrouponCardRequest, HttpSession session){
        GenericResponse<BaseGrouponCard> genericResponse = new GenericResponse<>();
        if (StringUtils.isBlank(baseGrouponCardRequest.getRechargeTypeNum())){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"充值卡种项目类别");
            return genericResponse;
        }
        if(null == baseGrouponCardRequest.getRechargeMoney() && baseGrouponCardRequest.getRechargeMoney().compareTo(BigDecimal.valueOf(0)) != -1){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"金额不能为0或空");
            return genericResponse;
        }

        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 + "/" + SessionHelp.getStoreId(session);//文件上传路径
                uploadFiles.setFileName(saveName);
                uploadFiles.setFilePath(path);
                uploadFilesInfo.add(uploadFiles);
                baseGrouponCardRequest.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;
                }
            }
        }

        String key = SessionHelp.getLoginAccount(session);
        int i = 0;
        try {
            i = ssmBaseGrouponCardService.update(baseGrouponCardRequest,key);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmProjectTypeController.add",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0){
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }
    @ApiOperation(value = "团购卡单据修改状态",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/sendSms")
    public GenericResponse sendSms(@RequestBody BaseGrouponCardRequest baseGrouponCardRequest, HttpSession session){
        GenericResponse<BaseGrouponCard> genericResponse = new GenericResponse<>();
        String key = SessionHelp.getLoginAccount(session);
        String i = "";
        if(baseGrouponCardRequest.getMemberPhone()==null || baseGrouponCardRequest.getMemberPhone().size()==0){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"请选择需要发送短信的手机号");
            return genericResponse;
        }
        try {
            i = ssmBaseGrouponCardService.sendSms(baseGrouponCardRequest,key);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmProjectTypeController.add",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i.equals("")){
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }else {
            genericResponse.setCodeAndMsg(ResponseCode.MSG,i);
        }
        return genericResponse;
    }
    @ApiOperation(value = "团购卡单据修改状态",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/sendSmsMemberPhone")
    public GenericResponse sendSmsMemberPhone(@RequestBody BaseGrouponCardRequest baseGrouponCardRequest, HttpSession session){
        GenericResponse<BaseGrouponCard> genericResponse = new GenericResponse<>();
        String key = SessionHelp.getLoginAccount(session);
        String i = "";
        try {
            i = ssmBaseGrouponCardService.sendSmsMemberPhone(baseGrouponCardRequest,key);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmProjectTypeController.add",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i.equals("")){
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }else {
            genericResponse.setCodeAndMsg(ResponseCode.MSG,i);
        }
        return genericResponse;
    }

    @ApiOperation(value = "团购卡单据修改状态",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/updateState")
    public GenericResponse updateState(@RequestBody BaseGrouponCardRequest baseGrouponCardRequest, HttpSession session){
        GenericResponse<BaseGrouponCard> genericResponse = new GenericResponse<>();
        String key = SessionHelp.getLoginAccount(session);
        int i = 0;
        try {
            i = ssmBaseGrouponCardService.updateState(baseGrouponCardRequest,key);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmProjectTypeController.add",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0){
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "删除单据",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/delete")
    public GenericResponse delete(@RequestBody BaseGrouponCardRequest baseGrouponCardRequest, HttpSession session){
        GenericResponse<BaseGrouponCard> genericResponse = new GenericResponse<>();


        if (null == baseGrouponCardRequest.getId()){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"删除的单据Id");
            return genericResponse;
        }
        int i = 0;
        try {
            i = ssmBaseGrouponCardService.delete(baseGrouponCardRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmProjectTypeController.add",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0){
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }


    @ApiOperation(value = "记录批量导出  门店端-团购卡-团购卡批量导出", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/export")
    public void export(@RequestBody BaseGrouponCardRequest baseGrouponCardRequest, HttpSession session) {
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        ExcelWriter excelWriter = null;
        OutputStream out = null;
        baseGrouponCardRequest.setStoreId(SessionHelp.getStoreId(session));
        baseGrouponCardRequest.setStoreName(SessionHelp.getStoreName(session));
        BaseGrouponCard baseGrouponCard = new BaseGrouponCard();
        try {
            String fileName = "groupInit";
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + ".xlsx");
            out = response.getOutputStream();
            //ClassPathResource classPathResource = new ClassPathResource("static/live_room_data3.xls");
            //InputStream inputStream = classPathResource.getInputStream();
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/groupInit.xlsx");
            Long storeId = SessionHelp.getStoreId(session);
            List<BaseGrouponCard> list = new ArrayList<>();
            List<Long> storeIds;
            if(baseGrouponCardRequest.getId()==null || baseGrouponCardRequest.getId().equals("")){
                BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(storeId);
                if(baseStore.getParentId()==null){
                    List<BaseStore> select = ssmBaseStoreService.select(null);
                    storeIds = select.stream().map(BaseStore::getId).collect(Collectors.toList());
                    list.addAll(ssmBaseGrouponCardService.selectNew(storeIds));
                }
            }else {
             list.add(ssmBaseGrouponCardService.selectByPrimaryKey(baseGrouponCardRequest.getId()));
            }
            List<ExcelGroup> excelGroupList = new ArrayList<>();
            for (BaseGrouponCard init : list) {
                BaseGrouponList baseGrouponList = new BaseGrouponList();
                baseGrouponList.setGrouponCardId(init.getId());
                List<BaseGrouponList> select = ssmBaseGrouponListService.select(baseGrouponList);
                for (BaseGrouponList grouponList : select) {
                    try {
                        String decrypt = AESUtils.decrypt(grouponList.getMobilePhone());
                        grouponList.setMobilePhone(decrypt.trim());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                if(select!=null && select.size()>0){
                    for (BaseGrouponList grouponList : select) {
                        ExcelGroup excelGroup = new ExcelGroup();
                        BeanUtils.copyProperties(init, excelGroup);
                        if (init.getState() == 0){
                            excelGroup.setState("新增");
                        }else if (init.getState() == 1){
                            excelGroup.setState("送审中");
                        }else if (init.getState() == 2){
                            excelGroup.setState("已回收");
                        }else if (init.getState() == 3){
                            excelGroup.setState("已审核");
                        }else if (init.getState() == 4){
                            excelGroup.setState("反审核中");
                        }
                        excelGroup.setMemberName(grouponList.getMemberName());
                        excelGroup.setMobilePhone(grouponList.getMobilePhone());
                        excelGroupList.add(excelGroup);
                    }
                }else {
                        ExcelGroup excelGroup = new ExcelGroup();
                        BeanUtils.copyProperties(init, excelGroup);
                        if (init.getState() == 0){
                            excelGroup.setState("新增");
                        }else if (init.getState() == 1){
                            excelGroup.setState("送审中");
                        }else if (init.getState() == 2){
                            excelGroup.setState("已回收");
                        }else if (init.getState() == 3){
                            excelGroup.setState("已审核");
                        }else if (init.getState() == 4){
                            excelGroup.setState("反审核中");
                        }
                        excelGroupList.add(excelGroup);
                }


            }
            excelWriter = EasyExcel.write(out).withTemplate(inputStream).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.fill(excelGroupList, writeSheet);
            out.flush();
        } catch (Exception e) {
            log.error("SsmProjectTypeController.export:",e);
        } finally {
            //destFile.delete();
            // 别忘记关闭流
            excelWriter.finish();
        }
    }

}
