package com.ssm.controller;

import com.ssm.core.bean.GenericResponse;
import com.ssm.core.utils.FtpUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.MemberLoginImageDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.query.MemberRequest;
import com.ssm.manage.query.RefundOrderResquest;
import com.ssm.manage.response.MemberResponse;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.SsmBaseStoreService;
import com.ssm.manage.service.SsmMemberAgreementService;
import com.ssm.manage.service.SsmMemberLoginService;
import com.ssm.manage.service.SsmUploadFilesService;
import com.ssm.manage.utils.Base64DecodedMultipartFileUtil;
import com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.SessionHelp;
import com.ssm.util.RedisClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
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.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

@Api(value="会员登录controller",tags={"会员登录相关接口"})
@RequestMapping("/demay/ssm/memberLogin")
@RestController
@Slf4j
public class SsmMemberLoginController {
    @Autowired
    private RedisClient<MemberResponse> redisClient;
    @Autowired
    public SsmMemberLoginService ssmMemberLoginService;
    @Autowired
    private SsmUploadFilesService ssmUploadFilesService;

    @Autowired
    private MemberLoginImageDao memberLoginImageDao;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;
    @Autowired
    private SsmMemberAgreementService ssmMemberAgreementService;

    //todo 验证码登录
    @ApiOperation(value = "手机端会员手机验证码登陆获取token接口", notes = "获取登录接口生成的token 使用接口前必须获取一次。作为参数传入", response = GenericResponse.class)
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "mobilePhone",value = "会员手机号",required = true),
                    @ApiImplicitParam(name = "passCode",value = "验证码",required = true)
            }
    )
    @RequestMapping(path="/phoneLogin", method= RequestMethod.POST)
    public GenericResponse phoneLogin(@RequestBody MemberRequest memberRequest,HttpSession session) {
        GenericResponse<MemberResponse> genericResponse = new GenericResponse<>();

        MemberResponse memberResponse = null;
        try{
            memberResponse = ssmMemberLoginService.uniPhoneLogin(memberRequest);
        }catch (SmsException e){
            log.error("SsmMemberLoginController.phoneLogin:", e);
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmMemberLoginController.phoneLogin:", e);
            genericResponse.setCodeAndMsg(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            return genericResponse;
        }
        if (memberResponse == null){
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        SessionHelp.setToken(session,memberResponse.getToken());
        SessionHelp.setLoginAccount(session,memberResponse.getMobilePhone());
        SessionHelp.setStoreId(session,memberResponse.getStoreId());
        session.setMaxInactiveInterval(60*60*24*7);
        genericResponse.setData(memberResponse);
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }
    //todo 获取验证码
    @ApiOperation(value = "手机端会员获取手机短信验证码接口", notes = "会员获取手机短信验证码接口", response = GenericResponse.class)
    @RequestMapping(path="/getSmsCode", method= RequestMethod.POST)
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "mobilePhone",value = "会员手机号",required = true),
            }
    )
    public GenericResponse getSmsCode(@RequestBody MemberRequest memberRequest) {
        GenericResponse<MemberResponse> genericResponse = new GenericResponse<>();
        MemberResponse memberResponse = null;
        try{
            memberResponse = ssmMemberLoginService.getSmsCode(memberRequest);
        }catch (SmsException e){
            log.error("SsmMemberLoginController.getSmsCode:", e);
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmMemberLoginController.getSmsCode:", e);
            genericResponse.setCodeAndMsg(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            return genericResponse;
        }
        if (memberResponse == null){
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setData(memberResponse);
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }


    @ApiOperation(value = "手机端会员修改密码接口", notes = "会员修改密码接口", response = String.class)
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "id",value = "id",required = true),
                    @ApiImplicitParam(name = "newPassword",value = "会员新密码",required = true),
                    @ApiImplicitParam(name = "password",value = "会员旧密码",required = true)
            }
    )
    @RequestMapping(path="/changePassword", method= RequestMethod.POST)
    public GenericResponse changePassword(@RequestBody MemberRequest memberRequest, HttpServletRequest request) {
        GenericResponse<MemberResponse> genericResponse = new GenericResponse<>();
        String token = request.getHeader("token");
        memberRequest.setOldToken(token);
        int i = 0;
        try{
            i = ssmMemberLoginService.changePassword(memberRequest);
        }catch (SmsException e){
            log.error("SsmMemberLoginController.changePassword:", e);
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmMemberLoginController.changePassword:", e);
            genericResponse.setCodeAndMsg(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }

    @ApiOperation(value = "手机端会员手机获取总店", notes = "获取登录接口生成的token 使用接口前必须获取一次。作为参数传入", response = GenericResponse.class)
    @RequestMapping(path="/getMemberStore", method= RequestMethod.POST)
    public GenericResponse getMemberStore(@RequestBody MemberRequest memberRequest) {
        GenericResponse<List<BaseStores>> genericResponse = new GenericResponse<>();
        List<BaseStores> storeList = null;
        try{
            storeList = ssmMemberLoginService.getMemberStore(memberRequest);
        }catch (SmsException e){
            log.error("SsmMemberLoginController.phonePassLogin:", e);
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmMemberLoginController.phonePassLogin:", e);
            genericResponse.setCodeAndMsg(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            return genericResponse;
        }
        if (storeList == null){
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setData(storeList);
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }
    //todo 登录接口
    @ApiOperation(value = "手机端会员手机密码登陆获取token接口", notes = "获取登录接口生成的token 使用接口前必须获取一次。作为参数传入", response = GenericResponse.class)
    @RequestMapping(path="/phonePassLogin", method= RequestMethod.POST)
    public GenericResponse phonePassLogin(@RequestBody MemberRequest memberRequest,HttpSession session) {
        GenericResponse<MemberResponse> genericResponse = new GenericResponse<>();
        MemberResponse memberResponse = null;
        try{
            memberResponse = ssmMemberLoginService.uniPhonePassLogin(memberRequest);
        }catch (SmsException e){
            log.error("SsmMemberLoginController.phonePassLogin:", e);
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmMemberLoginController.phonePassLogin:", e);
            genericResponse.setCodeAndMsg(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            return genericResponse;
        }
        if (memberResponse == null){
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        SessionHelp.setToken(session,memberResponse.getToken());
        SessionHelp.setLoginAccount(session,memberResponse.getMobilePhone());
        SessionHelp.setStoreId(session,memberResponse.getStoreId());
        session.setMaxInactiveInterval(60*60*24*7);
        genericResponse.setData(memberResponse);
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }


    @ApiOperation(value = "退出登录",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/logout")
    public GenericResponse logout (@RequestBody MemberRequest memberRequest,HttpServletRequest request){
        GenericResponse genericResponse = new GenericResponse();
        String token = request.getHeader("token");
        memberRequest.setOldToken(token);
        try {
            ssmMemberLoginService.uniLogout(memberRequest);
        }catch (Exception e){
            log.error("SsmMemberLoginController.logout",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }
    @ApiOperation(value = "会员上传签名", httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/memberAddImage")
    public GenericResponse update(List<MultipartFile> fileList,MemberRequest memberRequest) {
        GenericResponse genericResponse = new GenericResponse();
        //文件信息list
        if (fileList != null) {
            List<UploadFiles> uploadFilesInfo = new ArrayList<>();
            FtpUtils ftp = new FtpUtils();
            for (MultipartFile multipartFile : fileList) {
                UploadFiles uploadFiles = new UploadFiles();
                String fileName = multipartFile.getOriginalFilename();//获取文件名
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());//获取文件后缀
                String saveName = UUID.randomUUID() + "." + suffix;//将文件名用时间重命名
                String path = Constant.filePath + "/" + memberRequest.getStoreId();//文件上传路径
                uploadFiles.setFileName(saveName);
                uploadFiles.setFilePath(path);
                uploadFilesInfo.add(uploadFiles);

                InputStream inputStream = null;
                try {
                    inputStream = multipartFile.getInputStream();
                    ftp.uploadFile(path, saveName, inputStream);
                } catch (IOException e) {
                    log.error("SsmRefundOrderController.update:", e);
                    genericResponse.setCodeAndMsg(ResponseCode.FILE_UPLOAD_FAILED);
                    return genericResponse;
                }
            }
            for (UploadFiles uploadFiles : uploadFilesInfo) {
                uploadFiles.setDocId(memberRequest.getId());
                uploadFiles.setDocNum(memberRequest.getMemberNum()+"-"+memberRequest.getMemberName());
                    uploadFiles.setDocType(Constant.MEMBER_LOGIN_IMGER);
                try {
                    ssmUploadFilesService.add(uploadFiles);
                } catch (SmsException e) {
                    genericResponse.setCodeAndMsg(ResponseCode.FAILED);
                    return genericResponse;
                }
            }
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }



    @ApiOperation(value = "会员上传签名（新）base64的方式上传", httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/memberUpload")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "base64", value = "图片的base64", required = true),
            @ApiImplicitParam(name = "storeId", value = "门店id", required = true),
            @ApiImplicitParam(name = "id", value = "会员id", required = true)
//            @ApiImplicitParam(name = "agreementId", value = "会员协议id", required = true)
    }
    )
    public GenericResponse memberUpload(@RequestBody MemberRequest memberRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        //文件信息list
//        String loginAccount = SessionHelp.getLoginAccount(session);
//        MemberResponse memberResponse = redisClient.get(getKey(loginAccount));
        Long storeId = memberRequest.getStoreId();
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(storeId);
        if(baseStore.getParentId()!=null){
            storeId = baseStore.getParentId();
        }
//查询当前已审核的协议
        MemberAgreement memberAgreement = new MemberAgreement();
        memberAgreement.setStoreId(storeId);
        memberAgreement.setStartState(1);
        List<MemberAgreement> select = ssmMemberAgreementService.select(memberAgreement);
        if(select!=null && select.size()>0){
            memberAgreement = select.get(0);
        }
//        MemberRequest memberRequest = new MemberRequest();
//        memberRequest.setId(Long.valueOf("383682858604027904"));
//        memberRequest.setStoreId(Long.valueOf("369234373443874816"));
//        memberRequest.setMemberNum("01000194");
//        memberRequest.setMemberName("陆秀冲");
//        String base64 = "image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAAAXNSR0IArs4c6QAACshJREFUeF7tnVvoZVMcx7/u15BcSmrceWEmNB6Mu4iahheXN5cHbxLjScKLlHIpr2QKjSeXJIqQlGvhhSIRYpCQO6Eve7HnOHP+e++z/ue/f2t9Tp3OMf+91/79Pr/l0z5rr732duIFAQhAIAiB7YLESZgQgAAEhLDoBBCAQBgCCCtMqQgUAhBAWPQBCEAgDAGEFaZUBAoBCCAs+gAEIBCGAMIKUyoChQAEEBZ9AAIQCEMAYYUpFYFCAAIIiz4AAQiEIYCwwpSKQCEAAYRFH4AABMIQQFhhSkWgEIAAwqIPQAACYQggrDClIlAIQABh0QcgAIEwBBBWmFIRKAQggLDoAxCAQBgCCCtMqQgUAhBAWPQBCEAgDAGEFaZUBAo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IhJAWBGrRswQqJQAwqq08KQNgYgEEFbEqhEzBCol8Betvgqm1C1q7QAAAABJRU5ErkJggg==";
        // 拼接文件路径
        // 创建一个临时文件，并将字节数组写入这个文件
        MultipartFile multipartFile = Base64DecodedMultipartFileUtil.base64ToMultipart(memberRequest.getBase64());
        if (multipartFile != null) {
            FtpUtils ftp = new FtpUtils();
//            for (MultipartFile multipartFile : fileList) {
            MemberLoginImage uploadFiles = new MemberLoginImage();
            String fileName = multipartFile.getOriginalFilename();//获取文件名
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());//获取文件后缀
            String saveName = UUID.randomUUID() + "." + suffix;//将文件名用时间重命名
            String path = Constant.filePath + "/" + memberRequest.getStoreId();//文件上传路径
            uploadFiles.setFileName(saveName);
            uploadFiles.setFilePath(path);

            InputStream inputStream = null;
            try {
                inputStream = multipartFile.getInputStream();
                ftp.uploadFile(path, saveName, inputStream);
            } catch (IOException e) {
                log.error("SsmRefundOrderController.update:", e);
            }
//            }
            uploadFiles.setMemberId(memberRequest.getId());
            uploadFiles.setAgreementId(memberAgreement.getId());
            uploadFiles.setLoginDate(new Date());
            uploadFiles.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                memberLoginImageDao.saveNotNull(uploadFiles);
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }
    public String getKey(String phone){
        String key = "";
        if (StringUtils.isNotBlank(phone)){
            key = Constant.memberKey + phone;
        }
        return key;
    }
}
