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.github.pagehelper.PageInfo;
import com.ssm.core.bean.GenericResponse;
import com.ssm.core.bean.PageResponse;
import com.ssm.core.util.EasyExcelUtil;
import com.ssm.core.util.SessionHelp;
import com.ssm.manage.entity.MemberInit;
import com.ssm.manage.entity.SmsException;
import com.ssm.manage.excelEntity.ExcelMemberInit;
import com.ssm.manage.query.MemberInitRequest;
import com.ssm.manage.response.MemberInitResponse;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.SsmMemberInitService;
import com.ssm.manage.utils.CommonUtils;
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 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.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@Api(value="会员初始化controller",tags={"会员初始化相关接口"})
@RestController
@RequestMapping("/demay/ssm/memberInit")
@Slf4j
public class SsmMemberInitController {

    @Autowired
    private SsmMemberInitService ssmMemberInitService;

    @ApiOperation(value = "分页查询初始化记录  门店端-会员初始化-分页查询初始化记录",httpMethod = "POST",response = PageResponse.class)
    @RequestMapping("/page")
    public PageResponse selectPage(@RequestBody MemberInitRequest memberInitRequest){
        PageResponse<MemberInit> pageResponse = new PageResponse<>();
        PageInfo<MemberInit> pageInfo = new PageInfo<>();
//        memberInitRequest.setStoreId(SessionHelp.getStoreId(session));
        try {
            pageInfo = ssmMemberInitService.selectPage(memberInitRequest);
        }catch (Exception e){
            log.error("SsmMemberInitController.selectPage",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }

    @ApiOperation(value = "添加初始化记录  门店端-会员初始化-添加初始化记录", httpMethod = "POST", response = GenericResponse.class, notes = "")
    @RequestMapping("/add")
    public GenericResponse add(@RequestBody MemberInitRequest memberInitRequest,HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        if (StringUtils.isBlank(memberInitRequest.getMemberName())) {
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "会员名称");
            return genericResponse;
        }
        if (StringUtils.isBlank(memberInitRequest.getMobilePhone())) {
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "手机号码");
            return genericResponse;
        }
        if (!CommonUtils.isMobile(memberInitRequest.getMobilePhone())) {
            genericResponse.setCodeAndMsg(ResponseCode.NOT_MEET_REQUIREMENTS_S, "手机号码");
            return genericResponse;
        }

        String loginAccount = SessionHelp.getLoginAccount(session);
//        Long storeId = SessionHelp.getStoreId(session);
//        String storeName = SessionHelp.getStoreName(session);
//        memberInitRequest.setStoreId(storeId);
//        memberInitRequest.setStoreName(storeName);
        int i = 0;
        try {
            if(memberInitRequest.getCardType()==1){
                if(memberInitRequest.getCourseConsumeCount().longValue()<0
                        ||memberInitRequest.getCourseConsumePrice().longValue()<0
                        ||memberInitRequest.getCourseRestPrice().longValue()<0
                        ||memberInitRequest.getDebtMoney().longValue()<0
                        ||memberInitRequest.getStandardCount().longValue()<0
                        ||memberInitRequest.getStandardMoney().longValue()<0
                        ||memberInitRequest.getRestCount().longValue()<0){
                    throw new SmsException("010000","操作失败，不能输入负数");
                }
            }
            else if(memberInitRequest.getCardType()==0){
                if(memberInitRequest.getCardConsumeMoney().longValue()<0
                        ||memberInitRequest.getCardGiftMoney().longValue()<0
                        ||memberInitRequest.getDebtMoney().longValue()<0
                        ||memberInitRequest.getGiftConsumeMoney().longValue()<0
                        ||memberInitRequest.getRestMoney().longValue()<0) {
                    throw new SmsException("010000", "操作失败，不能输入负数");
                }
            }
            i = ssmMemberInitService.add(memberInitRequest,loginAccount);
        } catch (SmsException e){
            log.error("SsmMemberInitController.add:",e);
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e) {
            log.error("SsmMemberInitController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        } else {
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
        }
        return genericResponse;
    }


    @ApiOperation(value = "会员初始化模板下载  门店端-会员初始化-会员初始化模板下载", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/download")
    public void download(HttpSession session, HttpServletResponse response) {

        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        ExcelWriter excelWriter = null;
        OutputStream out = null;
        try {
            String fileName = "memberInit";
            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/memberInit.xlsx");

            List<ExcelMemberInit> list = new ArrayList<>();
            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("SsmMemberInitController.download:",e);
        } finally {
            //destFile.delete();
            // 别忘记关闭流
            excelWriter.finish();
        }
    }

    @ApiOperation(value = "初始化记录批量导出  门店端-会员初始化-初始化记录批量导出", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/export")
    public void export(@RequestBody MemberInitRequest memberInitRequest) {
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        ExcelWriter excelWriter = null;
        OutputStream out = null;
//        memberInitRequest.setStoreId(SessionHelp.getStoreId(session));
//        memberInitRequest.setStoreName(SessionHelp.getStoreName(session));
        MemberInit memberInit = new MemberInit();
        try {
            String fileName = "memberInit";
            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/memberInit.xlsx");
            BeanUtils.copyProperties(memberInitRequest, memberInit);
            List<MemberInit> list = ssmMemberInitService.select(memberInit);
            List<ExcelMemberInit> excelMemberInitList = new ArrayList<>();
            for (MemberInit init : list) {
                ExcelMemberInit excelMemberInit = new ExcelMemberInit();
                BeanUtils.copyProperties(init, excelMemberInit);
                if (init.getSex() == 1){
                    excelMemberInit.setSex("男");
                }else if (init.getSex() == 0){
                    excelMemberInit.setSex("女");
                }
                if (init.getCardType() == 0){
                    excelMemberInit.setCardType("充值");
                }else if (init.getCardType() == 1){
                    excelMemberInit.setCardType("疗程");
                }
                if (init.getCardState() == 0){
                    excelMemberInit.setCardState("锁定");
                }else if (init.getCardState() == 1){
                    excelMemberInit.setCardState("正常");
                }
                excelMemberInitList.add(excelMemberInit);
            }
            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(excelMemberInitList, writeSheet);
            out.flush();
        } catch (Exception e) {
            log.error("SsmMemberInitController.export:",e);
        } finally {
            //destFile.delete();
            // 别忘记关闭流
            excelWriter.finish();
        }
    }


    @ApiOperation(value = "会员初始化记录批量导入  门店端-会员初始化-会员初始化记录批量导入", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/import")
    public GenericResponse initImport(MultipartFile multipartFile, @RequestParam Long storeId, @RequestParam String storeName, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
//        Long storeId = SessionHelp.getStoreId(session);
//        String storeName = SessionHelp.getStoreName(session);
        String phone = SessionHelp.getLoginAccount(session);
        List<ExcelMemberInit> list = null;
        try {
            list = EasyExcelUtil.simpleWrite(multipartFile, ExcelMemberInit.class);
        } catch (SmsException e) {
            log.error("SsmMemberInitController.initImport:",e);
            return genericResponse;
        }
        List<MemberInit> initList = new ArrayList<>();
        for (ExcelMemberInit excelMemberInit : list) {
            MemberInit memberInit = new MemberInit();
            BeanUtils.copyProperties(excelMemberInit, memberInit);
            if (excelMemberInit.getSex().equals("男")){
                memberInit.setSex(1);
            }else if (excelMemberInit.getSex().equals("女")){
                memberInit.setSex(0);
            }
            if (excelMemberInit.getCardType().equals("充值")){
                memberInit.setCardType(0);
            }else if (excelMemberInit.getCardType().equals("疗程")){
                memberInit.setCardType(1);
            }
            if (excelMemberInit.getCardState().equals("锁定")){
                memberInit.setCardState(0);
            }else if (excelMemberInit.getCardState().equals("正常")){
                memberInit.setCardState(1);
            }
            initList.add(memberInit);
        }

        int count = ssmMemberInitService.insertBatch(initList, phone);
        if (list.size() != count) {
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;

    }

    @ApiOperation(value = "会员初始化记录修改  (门店端-会员初始化-会员初始化记录修改)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/update")
    public GenericResponse update(@RequestBody List<MemberInitRequest> memberInitRequestList) {
        GenericResponse genericResponse = new GenericResponse();
        String staffPhone = memberInitRequestList.get(0).getPhone();
        int i = 0;
        try {
            for(MemberInitRequest memberInitRequest:memberInitRequestList){
                if(memberInitRequest.getCardType()==1){
                    if(memberInitRequest.getCourseConsumeCount().longValue()<0||memberInitRequest.getCourseConsumePrice().longValue()<0||memberInitRequest.getCourseRestPrice().longValue()<0||memberInitRequest.getDebtMoney().longValue()<0||memberInitRequest.getRestCount().longValue()<0||memberInitRequest.getStandardCount().longValue()<0||memberInitRequest.getStandardMoney().longValue()<0) {
                        throw new SmsException("010000", "操作失败，不能输入负数");
                    }
                } else if(memberInitRequest.getCardType()==0){
                    if(memberInitRequest.getCardConsumeMoney().longValue()<0
                            ||memberInitRequest.getCardGiftMoney().longValue()<0
                            ||memberInitRequest.getDebtMoney().longValue()<0
                            ||memberInitRequest.getGiftConsumeMoney().longValue()<0
                            ||memberInitRequest.getRestMoney().longValue()<0) {
                        throw new SmsException("010000", "操作失败，不能输入负数");
                    }
                }
            }
            i = ssmMemberInitService.update(memberInitRequestList, staffPhone);
        }catch (Exception e){
            log.error("SsmMemberInitController.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("/check")
    public PageResponse check(@RequestBody MemberInitRequest memberInitRequest) {
        PageResponse pageResponse = new PageResponse();
//        Long storeId = SessionHelp.getStoreId(session);
//        String storeName = SessionHelp.getStoreName(session);
//        memberInitRequest.setStoreId(storeId);
//        memberInitRequest.setStoreName(storeName);
        PageInfo<MemberInitResponse> pageInfo = new PageInfo<>();
        try {
            pageInfo = ssmMemberInitService.checkList(memberInitRequest);
        }catch (Exception e){
            log.error("SsmMemberInitController.check:",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }

        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }

    @ApiOperation(value = "会员初始化账户欠款  (门店端-会员初始化-会员初始化账户欠款)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/init")
    public GenericResponse init(@RequestBody MemberInitRequest memberInitRequest) {
        GenericResponse genericResponse = new GenericResponse();
//        Long storeId = SessionHelp.getStoreId(session);
//        String storeName = SessionHelp.getStoreName(session);
//        memberInitRequest.setStoreId(storeId);
//        memberInitRequest.setStoreName(storeName);
        int i = 0;
        try {
            i = ssmMemberInitService.memberInit(memberInitRequest);
        }catch (Exception e){
            log.error("SsmMemberInitController.init:",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 MemberInitRequest memberInitRequest) {
        GenericResponse genericResponse = new GenericResponse();
//        String staffPhone = SessionHelp.getLoginAccount(session);
        int i = 0;
        try {
            i = ssmMemberInitService.delete(memberInitRequest);
        }catch (Exception e){
            log.error("SsmMemberInitController.delete:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0){
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }
}
