package com.ssm.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.ssm.core.bean.GenericResponse;
import com.ssm.core.bean.PageResponse;
import com.ssm.manage.entity.*;
import com.ssm.manage.query.AppCashRequest;
import com.ssm.manage.query.CashListRequest;
import com.ssm.manage.response.CashListResponse;
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.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 javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@Api(value="收银controller",tags={"美发版收银相关接口"})
@RestController
@RequestMapping("/demay/ssm/cash")
@Slf4j
public class SsmCashController {
    @Autowired
    private SsmCashService ssmCashService;

    @Autowired
    private SsmCashSignatureService ssmCashSignatureService;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmCourseAccountService ssmCourseAccountService;

    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;

    @ApiOperation(value = "查询收银服务单列表  (门店端-服务单-查询收银服务单列表)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/page")
    public PageResponse selectPage(@RequestBody CashListRequest cashListRequest){
        PageResponse<CashListResponse> pageResponse = new PageResponse<>();
        PageInfo<CashListResponse> pageInfo = new PageInfo<>();
        try {
            pageInfo = ssmCashService.selectPage(cashListRequest);
        }catch (SmsException e){
            pageResponse.setCodeAndMsg(e);
            return pageResponse;
        }catch (Exception e){
            log.error("SsmCashController.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("/cashList")
    public PageResponse selectCashList(@RequestBody CashListRequest cashListRequest){
        PageResponse<CashListResponse> pageResponse = new PageResponse<>();
        PageInfo<CashListResponse> pageInfo = new PageInfo<>();
        try {
            pageInfo = ssmCashService.selectCashList(cashListRequest);
        }catch (SmsException e){
            pageResponse.setCodeAndMsg(e);
            return pageResponse;
        }catch (Exception e){
            log.error("SsmCashController.selectCashList:",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }


//    @ApiOperation(value = "服务单收银  (门店端-服务单-服务单收银)",httpMethod = "POST",response = GenericResponse.class)
//    @RequestMapping("/doCash")
//    public GenericResponse doCash(MultipartFile file, @RequestParam String cashListRequestList, HttpSession session) {
//        GenericResponse genericResponse = new GenericResponse();
//        CashSignatureFile cashSignatureFile = new CashSignatureFile();
//        if (null != file) {
//            String fileName = file.getOriginalFilename();//获取文件名
//            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());//获取文件后缀
//            String saveName = DateUtils.getDateNowStr() + "." + suffix;//将文件名用时间重命名
//            String path = Constant.filePath + "/" + SessionHelp.getStoreId(session);//文件上传路径
//
//            cashSignatureFile.setFileName(saveName);
//            cashSignatureFile.setFilePath(path);
//            InputStream inputStream = null;
//            boolean b = false;
//            try {
//                inputStream = file.getInputStream();
//                b = new FtpUtils().uploadFile(path, saveName, inputStream);
//            } catch (IOException e) {
//                log.error("SsmCashController.doCash:", e);
//                genericResponse.setCodeAndMsg(ResponseCode.FILE_UPLOAD_FAILED);
//                return genericResponse;
//            }
//            if (!b){
//                genericResponse.setCodeAndMsg(ResponseCode.FILE_UPLOAD_FAILED);
//                return genericResponse;
//            }
//        }
//
//        Long storeId = SessionHelp.getStoreId(session);
//        String storeName = SessionHelp.getStoreName(session);
//        String staffPhone = SessionHelp.getLoginAccount(session);
//        List<CashListRequest> cashListRequests = JSON.parseArray(cashListRequestList,CashListRequest.class);
//        List<AccountTradeRecord> list = new ArrayList<>();
//        try {
//            list = ssmCashService.doCash(cashListRequests, staffPhone, cashSignatureFile);
//        }catch (SmsException e){
//            genericResponse.setCodeAndMsg(e);
//            return genericResponse;
//        }catch (Exception e){
//            log.error("SsmCashController.doCash:",e);
//            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
//            return genericResponse;
//        }
//        if (list.size() > 0){
//            BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(storeId);
//            for (AccountTradeRecord accountTradeRecord : list) {
//                //发送短信 充值卡支付
//                if (Constant.account_type_recharge_consume.equals(accountTradeRecord.getAccountType())) {
//                    //设置短信账户 发送 否则不发送
//                    if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
//                        try {
//                            ChuangLanSmsUtil.sendCashByRechargeSms(baseStore, accountTradeRecord.getMemberPhone(), accountTradeRecord.getAccountSpendMoney(), accountTradeRecord.getAccountConsumeMoney());
//                        } catch (IOException e) {
//                            log.error("SsmCashController.doCash:", e);
//                        } catch (SmsException e) {
//                            log.error("SsmCashController.doCash:", e);
//                            genericResponse.setCodeAndMsg(e);
//                        }
//                    }
//                } else if (Constant.account_type_project_consume.equals(accountTradeRecord.getAccountType())) {//疗程卡支付
//                    //设置短信账户 发送 否则不发送
//                    if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
//                        try {
////                            ChuangLanSmsUtil.sendSLStoreCashProjectPaySms(baseStore, accountTradeRecord.getMemberName(), accountTradeRecord.getMemberPhone(), accountTradeRecord.getTradeName(), accountTradeRecord.getAccountSpendCount(), accountTradeRecord.getAccountConsumeCount());
//                            ChuangLanSmsUtil.sendCashByCourseSms(baseStore, accountTradeRecord.getMemberPhone(), accountTradeRecord.getTradeName(), accountTradeRecord.getAccountSpendCount(), accountTradeRecord.getAccountConsumeCount());
//                        } catch (IOException e) {
//                            log.error("SsmCashController.doCash:", e);
//                        } catch (SmsException e) {
//                            log.error("SsmCashController.doCash:", e);
//                            genericResponse.setCodeAndMsg(e);
//                        }
//                    }
//                }
//            }
//
//        }
//        genericResponse.setCodeAndMsg(ResponseCode.OK);
//        return genericResponse;
//    }

    @ApiOperation(value = "服务单收银作废  (门店端-服务单-服务单收银作废)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/cancel")
    public GenericResponse cancel(@RequestBody AppCashRequest appCashRequest) {
        GenericResponse genericResponse = new GenericResponse();
        String staffPhone = appCashRequest.getStaffPhone();
        int i = 0;
        List<CashListRequest> cashListRequests = JSON.parseArray(appCashRequest.getCashListRequests(),CashListRequest.class);
        try {
            i = ssmCashService.cancel(cashListRequests, staffPhone);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmCashController.cancel:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0){
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "服务单收银业务人员修改  (门店端-服务单-服务单明细业务人员修改)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/updateStaff")
    public GenericResponse updateStaff(@RequestBody List<CashListRequest> cashListRequestList) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = cashListRequestList.get(0).getStoreId();
        int i = 0;
        try {
            i = ssmCashService.updateStaff(cashListRequestList, storeId);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmCashController.updateStaff:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0){
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "直接收银 (门店端-服务单-直接收银)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/addCashList")
    public GenericResponse addCashList(@RequestBody List<CashListRequest> cashListRequestList){
        GenericResponse genericResponse = new GenericResponse<>();
        Long storeId = cashListRequestList.get(0).getStoreId();
        String storeName =cashListRequestList.get(0).getStoreName();
        String phone = cashListRequestList.get(0).getStaffPhone();
        List<AccountTradeRecord> list = new ArrayList<>();
        try {
            list = ssmCashService.addCashList(cashListRequestList,storeId,storeName,phone, new CashSignatureFile());
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmCashController.addCashList:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setData(list.get(0).getDocId());
        if (list.size() > 0) {
//            BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(storeId);
//            for (AccountTradeRecord accountTradeRecord : list) {
//                //发送短信 充值卡支付
//                if (Constant.account_type_recharge_consume.equals(accountTradeRecord.getAccountType())) {
//
//                } else if (Constant.account_type_project_consume.equals(accountTradeRecord.getAccountType())) {//疗程卡支付
//                    //设置短信账户 发送 否则不发送
//                    if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
//                        try {
//                            ChuangLanSmsUtil.sendSLStoreCashProjectPaySms(baseStore, accountTradeRecord.getMemberName(), accountTradeRecord.getMemberPhone(), accountTradeRecord.getTradeName(), accountTradeRecord.getAccountSpendCount(), accountTradeRecord.getAccountConsumeCount());
//                        } catch (IOException e) {
//                            log.error("SsmCashController.doCash:", e);
//                        } catch (SmsException e) {
//                            log.error("SsmCashController.doCash:", e);
//                            genericResponse.setCodeAndMsg(e);
//                        }
//                    }
//                }
//            }
        }
        return genericResponse;
    }

//    @ApiOperation(value = "会员查询消费记录 (会员小程序-会员查询消费记录)",httpMethod = "POST",response = GenericResponse.class)
//    @RequestMapping("/selectByMember")
//    public PageResponse selectByMember(@RequestBody CashListRequest cashListRequest){
//        PageResponse<CashListResponse> pageResponse = new PageResponse<>();
//        PageInfo<CashListResponse> pageInfo = new PageInfo<>();
//
//        try {
//            pageInfo = ssmCashService.selectByMember(cashListRequest);
//        }catch (SmsException e){
//            pageResponse.setCodeAndMsg(e);
//            return pageResponse;
//        }catch (Exception e){
//            log.error("SsmCashController.selectByMember:",e);
//            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
//            return pageResponse;
//        }
//
//        pageResponse.setCodeAndMsg(ResponseCode.OK);
//        pageResponse.setPageInfo(pageInfo);
//        return pageResponse;
//    }

    @ApiOperation(value = "签名文件查询 (门店收银-签名文件查询)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/signature")
    public GenericResponse signature(@RequestBody CashSignatureFile cashSignatureFile){
        GenericResponse<CashSignatureFile> genericResponse = new GenericResponse<>();
        List<CashSignatureFile> list = new ArrayList<>();
        try {
            list = ssmCashSignatureService.select(cashSignatureFile);
        }catch (Exception e){
            log.error("SsmCashController.signature:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

        genericResponse.setCodeAndMsg(ResponseCode.OK);
        if (list.size() > 0) {
            genericResponse.setData(list.get(0));
        }
        return genericResponse;
    }

    @ApiOperation(value = "收银单据批量导出  美发版-收银-收银单据批量导出", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/export")
    public void export(@RequestBody CashListRequest cashListRequest) {
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        ExcelWriter excelWriter = null;
        OutputStream out = null;
        RechargeType rechargeType = new RechargeType();
        try {
            String fileName = "cashList";
            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/cashList.xlsx");

            List<CashList> list = ssmCashService.selectDownloadRecord(cashListRequest);

            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
            //EasyExcel.write(out, LiveRoomData.class).sheet("模板").doWrite(list);
            excelWriter = EasyExcel.write(out).withTemplate(inputStream).build();
            //FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.fill(list, writeSheet);
            out.flush();
        } catch (Exception e) {
            log.error("SsmCashController.export:",e);
        } finally {
            //destFile.delete();
            // 别忘记关闭流
            excelWriter.finish();
        }
    }

}
