package com.ssm.controller;

import com.github.pagehelper.PageInfo;
import com.ssm.manage.response.GenericResponse;
import com.ssm.manage.response.PageResponse;
import com.ssm.core.util.Base64DecodedMultipartFileUtil;
import com.ssm.manage.utils.SessionHelp;
import com.ssm.core.utils.FtpUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.entity.*;
import com.ssm.manage.query.MemberAgreementRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.response.StaffResponse;
import com.ssm.manage.service.*;
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.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.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Api(value="会员协议控制类",tags={"会员协议相关接口"})
@RestController
@RequestMapping("/demay/ssm/member")
@Slf4j
public class SsmMemberAgreementController {
    @Autowired
    private SsmMemberAgreementService ssmMemberAgreementService;
    @Autowired
    private RedisClient<StaffResponse> redisClient;
    private static String staffKey = "staffKey";



    @ApiOperation(value = "会员协议添加",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/addMemberFile")
    public GenericResponse addMemberFile(@RequestBody MemberAgreementRequest memberFileRequest, HttpSession session) throws IOException, SmsException {
        GenericResponse genericResponse = new GenericResponse<>();
        List<MemberAgreementFile> memberAgreementFileList=new ArrayList<>();
        Pattern img = Pattern.compile(this.BASE64_IMG);
        Pattern src = Pattern.compile(this.BASE64_SRC);
        Matcher imgMatcher = img.matcher(memberFileRequest.getContent());
        boolean b = imgMatcher.find();
        String replace=memberFileRequest.getContent();
        if(b){
            while (b){
                String img1 = imgMatcher.group(0);


                Matcher srcMatcher = src.matcher(img1);
                boolean b1 = srcMatcher.find();
                if (b1){
                    String s = srcMatcher.group(3);

                    MultipartFile multipartFile = Base64DecodedMultipartFileUtil.base64ToMultipart(s);
                    String fileName = multipartFile.getOriginalFilename();//获取文件名
                    String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());//获取文件后缀
                    String saveName = UUID.randomUUID() + "." + suffix;//将文件名用时间重命名
                    String path = Constant.filePath + "/" + "265309505575694336";//文件上传路径
                    MemberAgreementFile memberAgreementFile = new MemberAgreementFile();
                    memberAgreementFile.setFileName(saveName);
                    memberAgreementFile.setFilePath(path);
                    InputStream inputStream = null;
                    FtpUtils ftp = new FtpUtils();
                    try {
                        inputStream = multipartFile.getInputStream();
                        ftp.uploadFile(path, saveName, inputStream);
                        memberAgreementFileList.add(memberAgreementFile);
                        //查询出匹配的值替换
                         replace = replace.replace(s, "http://110.41.6.1:8077/tydFile/"+path+"/"+saveName);

                    } catch (IOException e) {
                        log.error("SsmRefundOrderController.add:", e);
                        genericResponse.setCodeAndMsg(ResponseCode.FILE_UPLOAD_FAILED);
                        return genericResponse;
                    }
                }
                b = imgMatcher.find();
            }

        }
        memberFileRequest.setMemberAgreementFiles(memberAgreementFileList);
        memberFileRequest.setContent(replace);
        memberFileRequest.setStoreId(SessionHelp.getStoreId(session));
        int i=0;
        try {
            i =  ssmMemberAgreementService.addMemberFile(memberFileRequest);
        } catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmMemberAgreementController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0)
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }


    @ApiOperation(value = "会员协议分页查询",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/selectPage")
    public PageResponse selectPage(@RequestBody MemberAgreementRequest memberFileRequest, HttpSession session) throws IOException, SmsException {
        PageResponse<MemberAgreement> pageResponse = new PageResponse<>();
        PageInfo<MemberAgreement> pageInfo = new PageInfo<>();
        if(memberFileRequest.getStoreId()==null)
        memberFileRequest.setStoreId(SessionHelp.getStoreId(session));
        try {
            pageInfo = ssmMemberAgreementService.selectPage(memberFileRequest);
//            pageInfo.getList().sort(Comparator.comparing(MemberAgreement::getStartState));
        } catch (Exception e) {
            log.error("SsmMemberAgreementController.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("/updateMemberAgreement")
    public GenericResponse updateMemberAgreement(@RequestBody MemberAgreementRequest memberFileRequest, HttpSession session) throws IOException, SmsException {
        GenericResponse<MemberAgreement> pageResponse = new GenericResponse<>();
        StaffResponse staffResponse = new StaffResponse();
        String phone = SessionHelp.getLoginAccount(session);
        Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0) {
            String key = new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }

        if(memberFileRequest.getStoreId()==null)
            memberFileRequest.setStoreId(SessionHelp.getStoreId(session));
        MemberAgreement memberAgreement = new MemberAgreement();
        BeanUtils.copyProperties(memberFileRequest,memberAgreement);
        memberAgreement.setUpdateName(staffResponse.getStaffName());
        memberAgreement.setUpdateDate(new Date());
        try {
            int i = ssmMemberAgreementService.updateByPrimaryKey(memberAgreement);
        } catch (Exception e) {
            log.error("SsmMemberAgreementController.selectPage", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;
    }

    @ApiOperation(value = "修改会员协议",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/pushMemberAgreement")
    public GenericResponse pushMemberAgreement(@RequestBody MemberAgreementRequest memberFileRequest, HttpSession session) throws IOException, SmsException {
        GenericResponse<MemberAgreement> pageResponse = new GenericResponse<>();
        StaffResponse staffResponse = new StaffResponse();
        String phone = SessionHelp.getLoginAccount(session);
        Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0) {
            String key = new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }

        if(memberFileRequest.getStoreId()==null)
            memberFileRequest.setStoreId(SessionHelp.getStoreId(session));
        MemberAgreement memberAgreement = new MemberAgreement();
        BeanUtils.copyProperties(memberFileRequest,memberAgreement);
        memberAgreement.setStartName(staffResponse.getStaffName());
        memberAgreement.setStartDate(new Date());
        memberAgreement.setStartState(1);
        try {
            List<MemberAgreement> select = ssmMemberAgreementService.select(null);
            if(select!=null && select.size()>0) {
                for (MemberAgreement agreement : select) {
                    if (agreement.getStartState() == 1) {
                        agreement.setEndName(staffResponse.getStaffName());
                        agreement.setEndDate(new Date());
                    }
                    agreement.setStartState(0);
                    ssmMemberAgreementService.updateByPrimaryKey(agreement);
                }
            }
            int i = ssmMemberAgreementService.updateStateByStartState(memberAgreement);
        } catch (Exception e) {
            log.error("SsmMemberAgreementController.selectPage", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;
    }
    @ApiOperation(value = "新增会员协议",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/deleteMemberAgreement")
    public GenericResponse deleteMemberAgreement(@RequestBody MemberAgreementRequest memberFileRequest, HttpSession session) throws IOException, SmsException {
        GenericResponse<MemberAgreement> pageResponse = new GenericResponse<>();
        if(memberFileRequest.getStoreId()==null)
            memberFileRequest.setStoreId(SessionHelp.getStoreId(session));

        try {
            int i = ssmMemberAgreementService.deleteByPrimaryKey(memberFileRequest.getId());
        } catch (Exception e) {
            log.error("SsmMemberAgreementController.selectPage", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;
    }
    @ApiOperation(value = "新增会员协议",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/addMemberAgreement")
    public GenericResponse addMemberAgreement(@RequestBody MemberAgreementRequest memberFileRequest, HttpSession session) throws IOException, SmsException {
        GenericResponse<MemberAgreement> pageResponse = new GenericResponse<>();
        if(memberFileRequest.getStoreId()==null)
            memberFileRequest.setStoreId(SessionHelp.getStoreId(session));

        StaffResponse staffResponse = new StaffResponse();
        String phone = SessionHelp.getLoginAccount(session);
        Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0) {
            String key = new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }
        MemberAgreement memberAgreement = new MemberAgreement();
        BeanUtils.copyProperties(memberFileRequest,memberAgreement);
        memberAgreement.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        memberAgreement.setAddName(staffResponse.getStaffName());
        memberAgreement.setAddDate(new Date());
        memberAgreement.setStartState(0);
        try {
            int i = ssmMemberAgreementService.save(memberAgreement);
        } catch (Exception e) {
            log.error("SsmMemberAgreementController.selectPage", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;
    }

    @ApiOperation(value = "会员协议详情查询",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/selectOne")
    public GenericResponse selectOne(@RequestBody MemberAgreementRequest memberFileRequest, HttpSession session) throws IOException, SmsException {
        GenericResponse genericResponse = new GenericResponse<>();
        MemberAgreement memberAgreement=new MemberAgreement();
        if(memberFileRequest.getStoreId()==null)
            memberFileRequest.setStoreId(SessionHelp.getStoreId(session));
        try {
             memberAgreement = ssmMemberAgreementService.selectOne(memberFileRequest);
        } catch (Exception e) {
            log.error("SsmMemberAgreementController.selectPage", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setData(memberAgreement);
        return genericResponse;
    }





    public static final String BASE64_SRC = "(src|SRC)=(\\\"|\\')(.*?)(\\\"|\\')";
    public static final String BASE64_IMG = "<(img|IMG)(.*?)(/>|></img>|>)";

    public String getStaffKey(String phone) {
        return staffKey + phone;
    }

}
