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.manage.response.GenericResponse;
import com.ssm.manage.response.PageResponse;
import com.ssm.core.util.EasyExcelUtil;
import com.ssm.manage.utils.SessionHelp;
import com.ssm.core.utils.AESUtils;
import com.ssm.core.utils.ChuangLanBeanSmsUtil;
import com.ssm.core.utils.FtpUtils;
import com.ssm.manage.entity.*;
import com.ssm.manage.excelEntity.ExcelStoreMemberList;
import com.ssm.manage.query.MemberRequest;
import com.ssm.manage.query.StoreMemberPhoneRequest;
import com.ssm.manage.query.StoreRequest;
import com.ssm.manage.response.MemberResponse;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.response.StaffResponse;
import com.ssm.manage.service.SsmBaseStoreService;
import com.ssm.manage.service.SsmStoreMemberFileService;
import com.ssm.manage.service.SsmStoreMemberPhoneService;
import com.ssm.manage.service.SsmStoreMemberService;
import com.ssm.manage.utils.Constant;
import com.ssm.util.RedisClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ObjectUtils;
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 tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(value="门店会员controller",tags={"门店会员相关接口"})
@RestController
@RequestMapping("/demay/ssm/storeMember")
@Slf4j
public class SsmStoreMemberController {


    @Autowired
    private SsmStoreMemberService ssmStoreMemberService;

    @Autowired
    private ChuangLanBeanSmsUtil chuangLanBeanSmsUtil;

    @Autowired
    private SsmStoreMemberPhoneService ssmStoreMemberPhoneService;

    @Autowired
    private SsmStoreMemberFileService ssmStoreMemberFileService;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private RedisClient<StaffResponse> redisClient;

    @ApiOperation(value = "分页查询门店会员信息   门店端-会员清单-分页查询门店会员信息",httpMethod = "POST",response = PageResponse.class)
    @RequestMapping("/page")
    public PageResponse selectPage(@RequestBody MemberRequest memberRequest,HttpSession session){
        PageResponse<StoreMemberList> pageResponse = new PageResponse<>();
        PageInfo<StoreMemberList> pageInfo = new PageInfo<>();
        memberRequest.setStoreId(SessionHelp.getStoreId(session));
        try {
            pageInfo = ssmStoreMemberService.selectPage(memberRequest);

        }catch (Exception e){
            log.error("SsmStoreMemberController.selectPage:",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }

    @ApiOperation(value = "分页查询门店会员信息   门店端-会员清单-分页查询门店会员信息",httpMethod = "POST",response = PageResponse.class)
    @RequestMapping("/selectListNew")
    public PageResponse selectList(@RequestBody MemberRequest memberRequest,HttpSession session){
        PageResponse<StoreMemberList> pageResponse = new PageResponse<>();
        List<StoreMemberList> pageInfo = new ArrayList<>();
        if(null == memberRequest.getStoreId()){
            memberRequest.setStoreId(SessionHelp.getStoreId(session));
        }

        try {
            pageInfo = ssmStoreMemberService.selectListNew(memberRequest);
        }catch (Exception e){
            log.error("SsmStoreMemberController.selectPage:",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setData(pageInfo);
        return pageResponse;
    }

    @ApiOperation(value = "分页查询门店会员信息   门店端-会员清单-分页查询门店会员信息",httpMethod = "POST",response = PageResponse.class)
    @RequestMapping("/pageassign")
    public PageResponse selectPageassign(@RequestBody MemberRequest memberRequest,HttpSession session){
        PageResponse<StoreMemberList> pageResponse = new PageResponse<>();
        PageInfo<StoreMemberList> pageInfo = new PageInfo<>();
        if(null == memberRequest.getStoreId()){
            memberRequest.setStoreId(SessionHelp.getStoreId(session));
        }

        try {
            pageInfo = ssmStoreMemberService.selectPageassign(memberRequest);
        }catch (Exception e){
            log.error("SsmStoreMemberController.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("/update")
    public GenericResponse updateMember(@RequestBody MemberRequest memberRequest, HttpSession session){
        GenericResponse<StoreMemberList> genericResponse = new GenericResponse<>();
        String phone = SessionHelp.getLoginAccount(session);
        memberRequest.setStoreId(SessionHelp.getStoreId(session));
        int i = 0;
        try {
            i = ssmStoreMemberService.updateStoreMember(memberRequest,phone);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmMemberController.updateMember:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;

    }


    @ApiOperation(value = "门店会员支付密码修改  会员端-门店会员支付密码修改",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/upcashPassword")
    public GenericResponse upcashPassword(@RequestBody MemberRequest memberRequest, HttpSession session){
        GenericResponse<StoreMemberList> genericResponse = new GenericResponse<>();
        String phone = SessionHelp.getLoginAccount(session);
        memberRequest.setOldPhone(phone);
        memberRequest.setStoreId(SessionHelp.getStoreId(session));
        int i = 0;
        try {
            i = ssmStoreMemberService.upcashPassword(memberRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmMemberController.updateMember:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }


    @ApiOperation(value = "重置会员登录密码",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/passwordReset")
    public GenericResponse passwordReset(@RequestBody MemberRequest memberRequest, HttpSession session){
        GenericResponse<StoreMemberList> genericResponse = new GenericResponse<>();
        String phone = SessionHelp.getLoginAccount(session);
        memberRequest.setStoreId(SessionHelp.getStoreId(session));
        memberRequest.setPassword(String.valueOf(Integer.valueOf((int) ((Math.random()*9+1)*100000))));
        memberRequest.setOldPhone(phone);
        int i = 0;
        try {


            i = ssmStoreMemberService.passwordReset(memberRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmMemberController.updateMember:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(memberRequest.getStoreId());
            //设置短信账户 发送 否则不发送
            if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
                try {
                    chuangLanBeanSmsUtil.sendMemberRestPwdSms(baseStore, memberRequest.getMemberName(), memberRequest.getMobilePhone(), Integer.parseInt(memberRequest.getPassword()));
                } catch (IOException e) {
                    log.error("SsmStoreMemberController.addMember:", e);
                } catch (SmsException e) {
                    log.error("SsmStoreMemberController.addMember:", e);
                }
            }
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "重置会员支付密码",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/cashPasswordReset")
    public GenericResponse cashPasswordReset(@RequestBody MemberRequest memberRequest, HttpSession session){
        GenericResponse<StoreMemberList> genericResponse = new GenericResponse<>();
        String phone = SessionHelp.getLoginAccount(session);
        memberRequest.setStoreId(SessionHelp.getStoreId(session));
        memberRequest.setOldPhone(phone);
        memberRequest.setCashPassword(String.valueOf(Integer.valueOf((int) ((Math.random()*9+1)*100000))));
        int i = 0;
        try {
            i = ssmStoreMemberService.CashpasswordReset(memberRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmMemberController.updateMember:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(memberRequest.getStoreId());
            //设置短信账户 发送 否则不发送
            if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
                try {
                    chuangLanBeanSmsUtil.sendMemberRestCashPwdSms(baseStore, memberRequest.getMemberName(), memberRequest.getMobilePhone(), Integer.parseInt(memberRequest.getCashPassword()));
                    genericResponse.setCodeAndMsg(ResponseCode.OK);
                } catch (IOException e) {
                    log.error("SsmStoreMemberController.addMember:", e);
                } catch (SmsException e) {
                    genericResponse.setCodeAndMsg(ResponseCode.MSG,e.getMessage());
                    log.error("SsmStoreMemberController.addMember:", e);
                }
            }else{
                genericResponse.setCodeAndMsg(ResponseCode.OK);
            }
        }
        return genericResponse;
    }

    @ApiOperation(value = "门店会员添加  门店端-开单页面-门店会员添加",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/add")
    public GenericResponse addMember(@RequestBody MemberRequest memberRequest, HttpSession session){
        GenericResponse<StoreMemberList> genericResponse = new GenericResponse<>();
        memberRequest.setConnStoreId(SessionHelp.getStoreId(session));
        memberRequest.setConnStoreName(SessionHelp.getStoreName(session));

        //if(memberRequest.getStoreId()==null){
        memberRequest.setStoreId(SessionHelp.getStoreId(session));
        memberRequest.setStoreName(SessionHelp.getStoreName(session));
        //}

        String phone = SessionHelp.getLoginAccount(session);
        String password = ObjectUtils.toString((int)((Math.random()*9+1)*1000));
        memberRequest.setPassword(password);
        memberRequest.setMemberStoreId(SessionHelp.getStoreId(session));
        memberRequest.setMemberStoreName(SessionHelp.getStoreName(session));
        memberRequest.setMemberStoreNum(SessionHelp.getStoreNum(session));
        int i = 0;
        try {
            i = ssmStoreMemberService.addStoreMember(memberRequest, phone);
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStoreMemberController.addMember:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
//        if (i > 0) {
//            genericResponse.setCodeAndMsg(ResponseCode.OK);
//            BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(memberRequest.getStoreId());
//            //设置短信账户 发送 否则不发送
//            if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
//                try {
//                    chuangLanBeanSmsUtil.sendMemberInitPwdSms(baseStore, memberRequest.getMemberName(), memberRequest.getMobilePhone(), Integer.parseInt(password));
//                } catch (IOException e) {
//                    log.error("SsmStoreMemberController.addMember:", e);
//                } catch (SmsException e) {
//                    log.error("SsmStoreMemberController.addMember:", e);
//                }
//            }
//        }
        return genericResponse;
    }

    @ApiOperation(value = "门店会员停用启用  门店端-会员清单-门店会员停用启用",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/updateState")
    public GenericResponse updateState(@RequestBody MemberRequest memberRequest, HttpSession session){
        GenericResponse<StoreMemberList> genericResponse = new GenericResponse<>();
        memberRequest.setStoreId(SessionHelp.getStoreId(session));
        memberRequest.setStoreName(SessionHelp.getStoreName(session));
        String phone = SessionHelp.getLoginAccount(session);
        if (memberRequest.getState() != 0) {
            if (StringUtils.isBlank(memberRequest.getPassword()) && StringUtils.isBlank(memberRequest.getPassCode())) {
                genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "密码和验证码");
                return genericResponse;
            }
        }
        int i = 0;
        try {
            i = ssmStoreMemberService.updateState(memberRequest,phone);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStoreMemberController.updateState:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "门店会员分派  门店端-会员分派-分派",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/assign")
    public GenericResponse assign(@RequestBody MemberRequest memberRequest){
        GenericResponse<StoreMemberList> genericResponse = new GenericResponse<>();
        int i = 0;
        try {
            i = ssmStoreMemberService.assignStoreMember(memberRequest);
        }catch (Exception e){
            log.error("SsmStoreMemberController.assign:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "查询员工跟进的会员明细list  门店端-员工会员统计表-查询员工跟进的会员明细list",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/listByStaff")
    public GenericResponse listByStaff(@RequestBody MemberRequest memberRequest,HttpSession session){
        GenericResponse<StoreMemberList> genericResponse = new GenericResponse<>();
        memberRequest.setStoreId(SessionHelp.getStoreId(session));
        List<StoreMemberList> lists = new ArrayList<>();
        try {
            lists = ssmStoreMemberService.listByStaff(memberRequest);
        }catch (Exception e){
            log.error("SsmStoreMemberController.listByStaff:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setRows(lists);
        return genericResponse;
    }

    @ApiOperation(value = "查询单个门店会员  门店端-门店开单页面-查询单个门店会员",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/one")
    public GenericResponse selectOne(@RequestBody MemberRequest memberRequest,HttpSession session){
        GenericResponse<MemberResponse> genericResponse = new GenericResponse<>();
        memberRequest.setStoreId(SessionHelp.getStoreId(session));
//        if(memberRequest.getMobilePhone()==null || memberRequest.getMobilePhone().equals("")){
//            genericResponse.setCodeAndMsg(ResponseCode.MSG,"请输入会员手机号");
//            return genericResponse;
//        }
        MemberResponse memberResponse = new MemberResponse();
        try {
            memberResponse = ssmStoreMemberService.selectOne(memberRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStoreMemberController.selectOne:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setData(memberResponse);
        return genericResponse;
    }

    @ApiOperation(value = "校验门店会员收银密码  门店端-门店所有付款页面-校验门店会员收银密码",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/checkCashWord")
    public GenericResponse checkCashWord(@RequestBody MemberRequest memberRequest,HttpSession session){
        GenericResponse genericResponse = new GenericResponse<>();
        memberRequest.setStoreId(SessionHelp.getStoreId(session));
        boolean flag = true;
        try {
            flag = ssmStoreMemberService.checkCashWord(memberRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStoreMemberController.checkCashWord:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setData(flag);
        return genericResponse;
    }



    @ApiOperation(value = "会员换号启用  (门店端-会员-会员换号启用)", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/changePhoneToUpdateState")
    public GenericResponse changePhoneToUpdateState(List<MultipartFile> fileList, MemberRequest memberRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        if (null == fileList || fileList.size() == 0) {
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "文件");
            return genericResponse;
        }
        //文件信息list
        List<StoreMemberFile> uploadFilesInfo = new ArrayList<>();
        FtpUtils ftp = new FtpUtils();
        for (MultipartFile multipartFile : fileList) {
            StoreMemberFile storeMemberFile = new StoreMemberFile();
            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);//文件上传路径
            storeMemberFile.setFileName(saveName);
            storeMemberFile.setFilePath(path);
            uploadFilesInfo.add(storeMemberFile);

            InputStream inputStream = null;
            try {
                inputStream = multipartFile.getInputStream();
                ftp.uploadFile(path, saveName, inputStream);
            } catch (IOException e) {
                log.error("SsmStoreMemberController.changePhoneToUpdateState:", e);
                genericResponse.setCodeAndMsg(ResponseCode.FILE_UPLOAD_FAILED);
                return genericResponse;
            }
        }
        memberRequest.setUploadFiles(uploadFilesInfo);

        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        memberRequest.setStoreId(storeId);
        memberRequest.setStoreName(storeName);

        int i = 0;
        try {
            i = ssmStoreMemberService.changePhoneToUpdateState(memberRequest, staffPhone);
        } catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmStoreMemberController.changePhoneToUpdateState:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }


    @ApiOperation(value = "门店会员启用  门店端-会员激活-门店会员启用",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/start")
    public GenericResponse start(@RequestBody MemberRequest memberRequest, HttpSession session){
        GenericResponse<StoreMemberList> genericResponse = new GenericResponse<>();
        memberRequest.setStoreId(SessionHelp.getStoreId(session));
        memberRequest.setStoreName(SessionHelp.getStoreName(session));
        String phone = SessionHelp.getLoginAccount(session);

        int i = 0;
        try {
            i = ssmStoreMemberService.start(memberRequest,phone);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStoreMemberController.start:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }


    @ApiOperation(value = "门店会员启用时一个启用 同手机号的另一个停用  门店端-会员激活-门店会员启用时一个启用 同手机号的另一个停用",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/bothOperation")
    public GenericResponse bothOperation(@RequestBody List<MemberRequest> list, HttpSession session){
        GenericResponse<StoreMemberList> genericResponse = new GenericResponse<>();

        String phone = SessionHelp.getLoginAccount(session);

        int i = 0;
        try {
            i = ssmStoreMemberService.bothOperation(list,phone);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStoreMemberController.bothOperation:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }


    @ApiOperation(value = "分页查询门店会员修改手机号 换号激活记录   门店端-会员激活-分页查询门店会员修改手机号 换号激活记录",httpMethod = "POST",response = PageResponse.class)
    @RequestMapping("/phonePage")
    public PageResponse phonePage(@RequestBody StoreMemberPhoneRequest memberPhoneRequest, HttpSession session){
        PageResponse<StoreMemberPhone> pageResponse = new PageResponse<>();
        PageInfo<StoreMemberPhone> pageInfo = new PageInfo<>();
        memberPhoneRequest.setStoreId(SessionHelp.getStoreId(session));
        try {
            pageInfo = ssmStoreMemberPhoneService.selectPage(memberPhoneRequest);
        }catch (Exception e){
            log.error("SsmStoreMemberController.phonePage:",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }

    @ApiOperation(value = "门店会员激活记录 文件查询  门店端-会员激活-门店会员激活记录 文件查询",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/selectFile")
    public GenericResponse selectFile(@RequestBody StoreMemberFile storeMemberFile){
        GenericResponse<StoreMemberFile> genericResponse = new GenericResponse<>();
        List<StoreMemberFile> lists = new ArrayList<>();
        if (null == storeMemberFile.getDocId()){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"记录ID");
            return genericResponse;
        }
        try {
            lists = ssmStoreMemberFileService.select(storeMemberFile);
        }catch (Exception e){
            log.error("SsmMemberController.selectFile:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setRows(lists);
        return genericResponse;
    }

    @ApiOperation(value = "通过手机号和密码查询会员所属门店  门店端-通过手机号和密码查询会员所属门店",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/list")
    public GenericResponse list(@RequestBody MemberRequest memberRequest){
        GenericResponse<StoreMemberList> genericResponse = new GenericResponse<>();
        List<StoreMemberList> lists = new ArrayList<>();
        try {
            lists = ssmStoreMemberService.selectList(memberRequest);
        }catch (Exception e){
            log.error("SsmMemberController.list:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setRows(lists);
        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 = "member";
            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/member.xlsx");

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

    @ApiOperation(value = "会员隐私信息导出验证码获取", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/authCode")
    public GenericResponse authCode(HttpSession session) {

        GenericResponse<BaseStore> genericResponse = new GenericResponse<>();
        BaseStore baseStores = new BaseStore();
        Long storeId = SessionHelp.getStoreId(session);
        String loginAccount = SessionHelp.getLoginAccount(session);



        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(storeId);
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            if(null == pagesorganization.getParentId()){
                BeanUtils.copyProperties(pagesorganization,baseStores);
            }
        }

//        try {


//            StaffResponse staffResponse = new StaffResponse();
//            if (redisClient.hasKey(Constant.staffKey + loginAccount)){
//                staffResponse = redisClient.get(Constant.staffKey + loginAccount);
//            }
//            String s = String.valueOf(((Math.random() * 9 + 1) * 100000));
//            chuangLanBeanSmsUtil.sendStoreCode(baseStores,s,staffResponse.getStaffName(),staffResponse.getStaffName());
//            session.setAttribute("code",s);
//        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setData(baseStores);
        return genericResponse;
    }

    @ApiOperation(value = "会员隐私信息导出验证码获取", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/authCodes")
    public GenericResponse authCodes(@RequestBody StoreRequest storeRequest, HttpSession session) {

        GenericResponse<BaseStore> genericResponse = new GenericResponse<>();
        BaseStore baseStores = new BaseStore();
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String loginAccount = SessionHelp.getLoginAccount(session);
        baseStores.setId(storeId);
        baseStores = ssmBaseStoreService.selectOne(baseStores);
        try {
            StaffResponse staffResponse = new StaffResponse();
            if (redisClient.hasKey(Constant.staffKey + loginAccount)){
                staffResponse = redisClient.get(Constant.staffKey + loginAccount);
            }
            int i1 = new Random().nextInt(99999);
            int i2 = (int) (Math.random() * 9 + 1) * 100000;
            String s = String.valueOf(i1+i2);
            System.out.println("验证码："+s);
            try {
                chuangLanBeanSmsUtil.sendStoreCode(baseStores,s,staffResponse.getStaffName(),storeName,storeRequest.getRegistrantMobilePhone());
            }catch (SmsException e) {
                e.printStackTrace();
                genericResponse.setCodeAndMsg(ResponseCode.MSG,e.getMessage());
                return genericResponse;
            }
            session.setAttribute("code",s);
        } catch (IOException e) {
            e.printStackTrace();
            genericResponse.setCodeAndMsg(ResponseCode.MSG,e.getMessage());
            return genericResponse;
        } catch (Exception e) {
            e.printStackTrace();
            genericResponse.setCodeAndMsg(ResponseCode.MSG,e.getMessage());
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setData(baseStores);
        return genericResponse;
    }


    @ApiOperation(value = "门店会员批量导出  门店端-会员-门店会员批量导出", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/export")
    public GenericResponse export(@RequestBody MemberRequest memberRequest, HttpSession session) {
        GenericResponse<StoreMemberList> genericResponse = new GenericResponse<>();
        if(memberRequest.getIsMessage()==1){
            String code = String.valueOf(session.getAttribute("code"));
            if(null == code){
                genericResponse.setCodeAndMsg(ResponseCode.MSG,"如需导出会员隐私数据，请先获取总店店长手机验证码");
                return genericResponse;
            }
            if(!code.equals(memberRequest.getCode())){
                genericResponse.setCodeAndMsg(ResponseCode.MSG,"验证码错误");
                return genericResponse;
            }
        }

        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        ExcelWriter excelWriter = null;
        OutputStream out = null;
        memberRequest.setStoreId(SessionHelp.getStoreId(session));
        memberRequest.setStoreName(SessionHelp.getStoreName(session));
        StoreMemberList storeMemberList = new StoreMemberList();

        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(SessionHelp.getStoreId(session));
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            if(null == pagesorganization.getParentId()){
                memberRequest.setStoreId(pagesorganization.getId());
            }
        }
        try {
            List<StoreMemberList> list = new ArrayList<>();
            String fileName = "member";
            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/member.xlsx");
            if(SessionHelp.getStoreId(session).equals(memberRequest.getStoreId())){//总店
//            BeanUtils.copyProperties(memberRequest, storeMemberList);
//            List<StoreMemberList> list = ssmStoreMemberService.select(storeMemberList);
                Example example = new Example(StoreMemberList.class);
                Example.Criteria criteria = example.createCriteria();
                example.setOrderByClause("member_num desc");
                if (memberRequest.getState() != null){
                    criteria.andEqualTo("state",memberRequest.getState());
                }
                if (memberRequest.getAssignState() != null){
                    criteria.andEqualTo("assignState",memberRequest.getAssignState());
                }
                if (memberRequest.getMemberName() != null){
                    criteria.andLike("memberName","%" + memberRequest.getMemberName() + "%");
                }
                if (memberRequest.getMobilePhone() != null){
                    criteria.andEqualTo("mobilePhone", memberRequest.getMobilePhone());
                }
//                criteria.andEqualTo("storeId",memberRequest.getStoreId());
                list = ssmStoreMemberService.selectByExample(example);
            }else{
                memberRequest.setStoreId(SessionHelp.getStoreId(session));

//            BeanUtils.copyProperties(memberRequest, storeMemberList);
//            List<StoreMemberList> list = ssmStoreMemberService.select(storeMemberList);
                Example example = new Example(StoreMemberList.class);
                Example.Criteria criteria = example.createCriteria();
                example.setOrderByClause("member_num desc");
                if (memberRequest.getState() != null){
                    criteria.andEqualTo("state",memberRequest.getState());
                }
                if (memberRequest.getAssignState() != null){
                    criteria.andEqualTo("assignState",memberRequest.getAssignState());
                }
                if (memberRequest.getMemberName() != null){
                    criteria.andLike("memberName","%" + memberRequest.getMemberName() + "%");
                }
                if (memberRequest.getMobilePhone() != null){
                    criteria.andEqualTo("mobilePhone", memberRequest.getMobilePhone());
                }
                criteria.andEqualTo("memberStoreId",memberRequest.getStoreId());
                list = ssmStoreMemberService.selectByExample(example);
            }

            List<ExcelStoreMemberList> excelStoreMemberLists = new ArrayList<>();
            for (StoreMemberList memberList : list) {
                ExcelStoreMemberList excelStoreMemberList = new ExcelStoreMemberList();
                BeanUtils.copyProperties(memberList, excelStoreMemberList);
                if(null != memberList.getSex()){
                    if (memberList.getSex() == 1){
                        excelStoreMemberList.setSex("男");
                    }else if (memberList.getSex() == 0){
                        excelStoreMemberList.setSex("女");
                    }
                }
                if (memberList.getState() == 1){
                    excelStoreMemberList.setState("启用");
                }else if (memberList.getState() == 0){
                    excelStoreMemberList.setState("停用");
                }else if (memberList.getState() == 2){
                    excelStoreMemberList.setState("启用中");
                }
                if (null != memberList.getHairLong() && memberList.getHairLong() == 1){
                    excelStoreMemberList.setHairLong("长");
                }else if (null != memberList.getHairLong() && memberList.getHairLong() == 2){
                    excelStoreMemberList.setHairLong("中");
                }else if (null != memberList.getHairLong() && memberList.getHairLong() == 3){
                    excelStoreMemberList.setHairLong("短");
                }
                if (null != memberList.getSkinType() && memberList.getSkinType() == 1){
                    excelStoreMemberList.setSkinType("油性");
                }else if (null != memberList.getSkinType() && memberList.getSkinType() == 2){
                    excelStoreMemberList.setSkinType("中性");
                }else if (null != memberList.getSkinType() && memberList.getSkinType() == 3){
                    excelStoreMemberList.setSkinType("干性");
                }

                if(null != memberList.getMemberStoreId()){
                    BaseStore store = new BaseStore();
                    store.setId(memberList.getMemberStoreId());
                    BaseStore baseStore = ssmBaseStoreService.selectOne(store);
                    excelStoreMemberList.setMemberStoreNum(baseStore.getStoreNum());
                }
                if(null != memberList.getInputDate()){
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String format = simpleDateFormat.format(memberList.getInputDate());
                    excelStoreMemberList.setInputDate(format);
                }


                excelStoreMemberList.setMemberNum(memberList.getMemberNum());
                if(null != memberRequest.getIsMessage() && memberRequest.getIsMessage()==1){
                    excelStoreMemberList.setMobilePhone(AESUtils.decrypt(memberList.getMobilePhone()));
                    excelStoreMemberList.setPassword(AESUtils.decrypt(memberList.getPassword()));
                    excelStoreMemberList.setCashPassword(AESUtils.decrypt(memberList.getCashPassword()));
                    session.removeAttribute("code");
                }else{
                    excelStoreMemberList.setMobilePhone(null);
                    excelStoreMemberList.setPassword(null);
                    excelStoreMemberList.setCashPassword(null);
                }
                excelStoreMemberLists.add(excelStoreMemberList);

            }
            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(excelStoreMemberLists, writeSheet);
            out.flush();
        } catch (Exception e) {
            log.error("SsmMemberController.export:",e);
        } finally {
            //destFile.delete();
            // 别忘记关闭流
            excelWriter.finish();
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
//        return genericResponse;
        return null;
    }


    @ApiOperation(value = "门店会员批量导入  门店端-会员-门店会员批量导入", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/import")
    public GenericResponse memImport(MultipartFile multipartFile, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String key = SessionHelp.getLoginAccount(session);
        List<ExcelStoreMemberList> list = null;
        try {
            list = EasyExcelUtil.simpleWrite(multipartFile, ExcelStoreMemberList.class);
        } catch (SmsException e) {
            log.error("SsmMemberController.memImport:",e);
            return genericResponse;
        }

        List<StoreMemberList> memberLists = new ArrayList<>();
        for (ExcelStoreMemberList excelStoreMemberList : list) {
            StoreMemberList memberList = new StoreMemberList();
            BeanUtils.copyProperties(excelStoreMemberList, memberList);
            if (excelStoreMemberList.getSex().equals("男")){
                memberList.setSex(1);
            }else if (excelStoreMemberList.getSex().equals("女")){
                memberList.setSex(0);
            }
            if (excelStoreMemberList.getState().equals("启用")){
                memberList.setState(1);
            }else if (excelStoreMemberList.getState().equals("停用")){
                memberList.setState(0);
            }else if (excelStoreMemberList.getState().equals("启用中")){
                memberList.setState(2);
            }
            if (StringUtils.isNotBlank(excelStoreMemberList.getHairLong()) && excelStoreMemberList.getHairLong().equals("长")){
                memberList.setHairLong(1);
            }else if (StringUtils.isNotBlank(excelStoreMemberList.getHairLong()) && excelStoreMemberList.getHairLong().equals("中")){
                memberList.setHairLong(2);
            }else if (StringUtils.isNotBlank(excelStoreMemberList.getHairLong()) && excelStoreMemberList.getHairLong().equals("短")){
                memberList.setHairLong(3);
            }
            if (StringUtils.isNotBlank(excelStoreMemberList.getSkinType()) && excelStoreMemberList.getSkinType().equals("油性")){
                memberList.setSkinType(1);
            }else if (StringUtils.isNotBlank(excelStoreMemberList.getSkinType()) && excelStoreMemberList.getSkinType().equals("中性")){
                memberList.setSkinType(2);
            }else if (StringUtils.isNotBlank(excelStoreMemberList.getSkinType()) && excelStoreMemberList.getSkinType().equals("干性")){
                memberList.setSkinType(3);
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date parse =null;
            try {
                parse = simpleDateFormat.parse(excelStoreMemberList.getInputDate());
                memberList.setInputDate(parse);
            } catch (ParseException e) {
                e.printStackTrace();
            }


            memberLists.add(memberList);
        }
        List<StoreMemberList> list1 = new ArrayList<>();
        try {
            list1 = ssmStoreMemberService.insertBatch(memberLists,storeId, storeName, key);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (!list1.isEmpty()){
            genericResponse.setRows(list1);
        }
        return genericResponse;

    }

    @ApiOperation(value = "重算会员等级",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/resetClass")
    public GenericResponse resetClass(@RequestBody MemberRequest memberRequest, HttpSession session){
        GenericResponse<StoreMemberList> genericResponse = new GenericResponse<>();
        memberRequest.setStoreId(SessionHelp.getStoreId(session));
        memberRequest.setStoreName(SessionHelp.getStoreName(session));
        String phone = SessionHelp.getLoginAccount(session);

        int i = 0;
        try {
            i = ssmStoreMemberService.resetClass(memberRequest,phone);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStoreMemberController.start:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "清空会员等级",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/emptyClass")
    public GenericResponse emptyClass(@RequestBody MemberRequest memberRequest, HttpSession session){
        GenericResponse<StoreMemberList> genericResponse = new GenericResponse<>();
        memberRequest.setStoreId(SessionHelp.getStoreId(session));
        memberRequest.setStoreName(SessionHelp.getStoreName(session));
        String phone = SessionHelp.getLoginAccount(session);

        int i = 0;
        try {
            i = ssmStoreMemberService.emptyClass(memberRequest,phone);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStoreMemberController.start:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "门店会员修改信息  会员端-门店会员修改信息",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/updateMobile")
    public GenericResponse updateMobile(@RequestBody MemberRequest memberRequest, HttpSession session){
        GenericResponse<StoreMemberList> genericResponse = new GenericResponse<>();
        String phone = SessionHelp.getLoginAccount(session);
        memberRequest.setStoreId(SessionHelp.getStoreId(session));
        int i = 0;
        try {
            i = ssmStoreMemberService.updateMobile(memberRequest,phone);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmMemberController.updateMember:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "分页查询门店会员信息   门店端-会员清单-分页查询门店会员信息",httpMethod = "POST",response = PageResponse.class)
    @RequestMapping("/memberUpdatePage")
    public PageResponse memberUpdatePage(@RequestBody MemberRequest memberRequest,HttpSession session){
        PageResponse<StoreMemberListUpdate> pageResponse = new PageResponse<>();
        PageInfo<StoreMemberListUpdate> pageInfo = new PageInfo<>();
        memberRequest.setStoreId(SessionHelp.getStoreId(session));
        try {
            pageInfo = ssmStoreMemberService.memberUpdatePage(memberRequest);

        }catch (Exception e){
            log.error("SsmStoreMemberController.selectPage:",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }



}
