package com.ssm.controller;

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.core.utils.ChuangLanBeanSmsUtil;
import com.ssm.core.utils.FtpUtils;
import com.ssm.manage.entity.AccountTradeRecord;
import com.ssm.manage.entity.BaseStore;
import com.ssm.manage.entity.CashSignatureFile;
import com.ssm.manage.entity.SmsException;
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 com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.DateUtils;
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.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 java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

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

    @Autowired
    private ChuangLanBeanSmsUtil chuangLanBeanSmsUtil;

    @Autowired
    private SsmCashSignatureService ssmCashSignatureService;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmCourseAccountService ssmCourseAccountService;

    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;

    @ApiOperation(value = "查询收银服务单列表  (app端-服务单-查询收银服务单列表)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/page")
    public PageResponse selectPage(@RequestBody CashListRequest cashListRequest){
        PageResponse<CashListResponse> pageResponse = new PageResponse<>();
        PageInfo<CashListResponse> pageInfo = new PageInfo<>();
//        Long storeId = SessionHelp.getStoreId(session);
//        cashListRequest.setStoreId(storeId);
        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<>();
//        Long storeId = SessionHelp.getStoreId(session);
//        cashListRequest.setStoreId(storeId);
        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(AppCashRequest appCashRequest) {
        GenericResponse genericResponse = new GenericResponse();
        CashSignatureFile cashSignatureFile = new CashSignatureFile();
        if (null != appCashRequest.getFile()) {
            String fileName = appCashRequest.getFile().getOriginalFilename();//获取文件名
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());//获取文件后缀
            String saveName = DateUtils.getDateNowStr() + "." + suffix;//将文件名用时间重命名
//            String path = Constant.filePath + "/" + SessionHelp.getStoreId(session);//文件上传路径
            String path = Constant.filePath + "/" + appCashRequest.getStoreId();//文件上传路径
            cashSignatureFile.setFileName(saveName);
            cashSignatureFile.setFilePath(path);
            InputStream inputStream = null;
            boolean b = false;
            try {
                inputStream = appCashRequest.getFile().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(appCashRequest.getCashListRequests(),CashListRequest.class);
//        List<CashListRequest> cashListRequests = appCashRequest.getCashListRequests();
        List<AccountTradeRecord> list = new ArrayList<>();
        try {
            list = ssmCashService.doCash(cashListRequests, appCashRequest.getStaffPhone(), 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(appCashRequest.getStoreId());
            for (AccountTradeRecord accountTradeRecord : list) {
                //发送短信 充值卡支付
                if (Constant.account_type_recharge_consume.equals(accountTradeRecord.getAccountType())) {
                    //设置短信账户 发送 否则不发送
                    if (StringUtils.isNotBlank(baseStore.getSmsAccount()) && null != baseStore.getMessagingPlatform()) {
                        try {
                            chuangLanBeanSmsUtil.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()) && null != baseStore.getMessagingPlatform()) {
                        try {
//                            chuangLanBeanSmsUtil.sendSLStoreCashProjectPaySms(baseStore, accountTradeRecord.getMemberName(), accountTradeRecord.getMemberPhone(), accountTradeRecord.getTradeName(), accountTradeRecord.getAccountSpendCount(), accountTradeRecord.getAccountConsumeCount());
                            chuangLanBeanSmsUtil.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 AppCashRequest appCashRequest) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = appCashRequest.getStoreId();
        int i = 0;
        List<CashListRequest> cashListRequests = JSON.parseArray(appCashRequest.getCashListRequests(),CashListRequest.class);
        try {
            i = ssmCashService.updateStaff(cashListRequests, 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(AppCashRequest appCashRequest){
        GenericResponse genericResponse = new GenericResponse<>();
        CashSignatureFile cashSignatureFile = new CashSignatureFile();
        if (null != appCashRequest.getFile()) {
            String fileName = appCashRequest.getFile().getOriginalFilename();//获取文件名
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());//获取文件后缀
            String saveName = DateUtils.getDateNowStr() + "." + suffix;//将文件名用时间重命名
            String path = Constant.filePath + "/" + appCashRequest.getStoreId();//文件上传路径

            cashSignatureFile.setFileName(saveName);
            cashSignatureFile.setFilePath(path);
            InputStream inputStream = null;
            boolean b = false;
            try {
                inputStream = appCashRequest.getFile().getInputStream();
                b = new FtpUtils().uploadFile(path, saveName, inputStream);
            } catch (IOException e) {
                log.error("SsmCashController.addCashList:", e);
                genericResponse.setCodeAndMsg(ResponseCode.FILE_UPLOAD_FAILED);
                return genericResponse;
            }
            if (!b){
                genericResponse.setCodeAndMsg(ResponseCode.FILE_UPLOAD_FAILED);
                return genericResponse;
            }
        }
        List<CashListRequest> cashListRequests = JSON.parseArray(appCashRequest.getCashListRequests(),CashListRequest.class);
//        List<CashListRequest> cashListRequests = appCashRequest.getCashListRequests();
        Long storeId = appCashRequest.getStoreId();
        String storeName = appCashRequest.getStoreName();
        String phone = appCashRequest.getStaffPhone();
        List<AccountTradeRecord> list = new ArrayList<>();
        try {
            list = ssmCashService.addCashList(cashListRequests,storeId,storeName,phone, 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);

        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 {
                            chuangLanBeanSmsUtil.sendSLStoreCashProjectPaySms(baseStore, accountTradeRecord.getMemberName(), accountTradeRecord.getMemberPhone(), accountTradeRecord.getTradeName(), accountTradeRecord.getAccountSpendCount(), accountTradeRecord.getAccountConsumeCount());
                        } catch (IOException e) {
                            log.error("SsmCashController.doCash:", e);
                        } catch (SmsException e) {
                            genericResponse.setCodeAndMsg(ResponseCode.SMS_SEND_OK_EXCEPTION);
                            log.error("SsmCashController.doCash:", e);
                        }
                    }
                }
            }
        }
        return genericResponse;
    }


    @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;
    }

}
