package com.iamberry.wechat.handles.customized;

import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.customized.CustomizedColor;
import com.iamberry.wechat.core.entity.customized.CustomizedPattern;
import com.iamberry.wechat.core.entity.customized.CustomizedPosition;
import com.iamberry.wechat.core.entity.customized.CustomizedTooth;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.face.customized.CustomizedColorService;
import com.iamberry.wechat.face.customized.CustomizedPatternService;
import com.iamberry.wechat.face.customized.CustomizedPositionService;
import com.iamberry.wechat.face.customized.CustomizedToothService;
import com.iamberry.wechat.face.member.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 *  定制牙刷
 */
@Controller
@RequestMapping("/wechat/customized")
public class CustomizedHandler {

    @Autowired
    private CustomizedColorService customizedColorService;
    @Autowired
    private CustomizedPatternService customizedPatternService;
    @Autowired
    private CustomizedPositionService customizedPositionService;
    @Autowired
    private CustomizedToothService customizedToothService;
    @Autowired
    private MemberService memberService;

    /**
     * 获取颜色和图案
     * @param req
     * @return
     */
    @RequestMapping("/color_patterns")
    @ResponseBody
    public ResultMsg getColorPatterns(HttpServletRequest req){
        ResultMsg rm = ResultMsg.getSuccess();

        CustomizedColor customizedColor = new CustomizedColor();
        customizedColor.setColorStatus(1);
        List<CustomizedColor> customizedColorList = customizedColorService.getCustomizedColorList(customizedColor);

        CustomizedPattern customizedPattern = new CustomizedPattern();
        customizedPattern.setPatternStatus(1);
        List<CustomizedPattern> customizedPatternList = customizedPatternService.getCustomizedPatternList(customizedPattern);

        rm.addData("customizedColorList",customizedColorList);
        rm.addData("customizedPatternList",customizedPatternList);
        return rm;
    }

    /**
     * 根据纹理获取位置信息
     * @param req
     * @return
     */
    @RequestMapping("/get_position")
    @ResponseBody
    public ResultMsg getPosition(HttpServletRequest req,Integer patternId){
        ResultMsg rm = ResultMsg.getSuccess();

        if(patternId == null){
            return ResultMsg.getError();
        }

        CustomizedPosition customizedPosition = new CustomizedPosition();
        customizedPosition.setPositionStatus(1);
        customizedPosition.setPatternId(patternId);
        List<CustomizedPosition> customizedPositionList = customizedPositionService.getCustomizedPositionList(customizedPosition);

        rm.addData("customizedPositionList",customizedPositionList);
        return rm;
    }

    /**
     * 上传头像
     * @param req
     * @return
     */
    @RequestMapping("/upload_avatar")
    @ResponseBody
    public ResultMsg uploadAvatar(HttpServletRequest req,String avatarImg){
//        Member member = WechatUtils.getUserBySession(req);
//        member = memberService.getMemberByUserOpenId(member.getUserOpenid());

        ResultMsg rm = ResultMsg.getSuccess();
        if(avatarImg == null || "".equals(avatarImg)){
            return ResultMsg.getError();
        }

        String acatar[] = avatarImg.split(",");
        avatarImg = acatar[1];

        String dataStaing = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String path = "common/images/customized/avatar/" + dataStaing + "/";

        // 生成文件
        String filePath = req.getSession().getServletContext().getRealPath("/") + path ;
        File imgfile = new File(filePath); //全路径
        if (!imgfile.exists()){
            imgfile.mkdirs();
        }
        // 生成文件名
        String files = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".png";
        // 生成文件
        String filename = filePath + files;
        String avatarImgPath = path + files;     //返回路径
        byte[] buffer;//图像转换的目的字节数组
        BASE64Decoder base64 = new BASE64Decoder();  //新建64位解码器
        try {
            buffer = base64.decodeBuffer(avatarImg);//64位解码到字节数组中
            //写进文件  创建一个向具有指定名称的文件中写入数据的输出文件流。创建一个新 FileDescriptor 对象来表示此文件连接。

            File file = new File(filename); //全路径
            if (!file.exists()){
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file); //设置好保存路径，创建文件输出流。
            fos.write(buffer);  //写入
            fos.flush();  //刷新
            fos.close();  //关闭
            fos = null;//释放
        }catch (Exception e){
            e.printStackTrace();
            return ResultMsg.getError();
        }
        rm.addData("avatarImgPath",avatarImgPath);
        return rm;
    }

    /**
     * 生成牙刷
     * @param req
     * @param productId  商品id
     * @param colorId 颜色id
     * @param toothColorId  定制颜色id
     * @param positionId 位置id
     * @param avatarImgPath 头像图片位置
     * @param toothImg 牙刷
     * @param toothText 文字
     * @return
     */
    @RequestMapping("/generate")
    @ResponseBody
    public ResultMsg generate(HttpServletRequest req,
                              @RequestParam(value= "productId",defaultValue= "70" ,required=false) Integer productId,
                              @RequestParam(value= "colorId",defaultValue= "75" ,required=false) Integer colorId,
                              Integer toothColorId,Integer positionId,String avatarImgPath,String toothImg,String toothText){
        Member member = WechatUtils.getUserBySession(req);
        member = memberService.getMemberByUserOpenId(member.getUserOpenid());
        ResultMsg rm = ResultMsg.getSuccess();

        if(toothColorId == null || positionId == null || avatarImgPath == null || "".equals(avatarImgPath)
                || toothImg == null || "".equals(toothImg) || toothText == null || "".equals(toothText) ){
            return ResultMsg.getError();
        }

        /*生成图片*/
        String acatar[] = toothImg.split(",");
        toothImg = acatar[1];

        String dataStaing = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String path = "common/images/customized/tooth/" + dataStaing + "/";

        // 生成文件
        String filePath = req.getSession().getServletContext().getRealPath("/") + path ;
        File imgfile = new File(filePath); //全路径
        if (!imgfile.exists()){
            imgfile.mkdirs();
        }
        // 生成文件名
        String files = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".png";
        // 生成文件
        String filename = filePath + files;
        String toothImgPath = path + files;     //返回路径
        byte[] buffer;//图像转换的目的字节数组
        BASE64Decoder base64 = new BASE64Decoder();  //新建64位解码器
        try {
            buffer = base64.decodeBuffer(toothImg);//64位解码到字节数组中
            File file = new File(filename); //全路径
            if (!file.exists()){
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file); //设置好保存路径，创建文件输出流。
            fos.write(buffer);  //写入
            fos.flush();  //刷新
            fos.close();  //关闭
            fos = null;//释放
        }catch (Exception e){
            e.printStackTrace();
            return ResultMsg.getError();
        }

        CustomizedPosition customizedPosition = customizedPositionService.getCustomizedPositionById(positionId);

        CustomizedTooth customizedTooth = new CustomizedTooth();
        customizedTooth.setUserOpenId(member.getUserOpenid());
        customizedTooth.setProductId(productId);
        customizedTooth.setColorId(colorId);
        customizedTooth.setToothColorId(toothColorId);
        customizedTooth.setToothPatternId(customizedPosition.getPatternId());
        customizedTooth.setToothPositionId(positionId);
        customizedTooth.setToothAvatarImg(avatarImgPath);
        customizedTooth.setToothImg(toothImgPath);
        customizedTooth.setToothText(toothText);
        customizedTooth.setToothType(1);    //1微信
        customizedTooth.setToothStatus(1);  //正常
        Integer flag = customizedToothService.save(customizedTooth);
        if(flag < 0){
            return ResultMsg.getError();
        }
        return rm.addData("toothId",customizedTooth.getToothId());
    }


    /**
     * 生成位置集合
     * @return
     */
//    @RequestMapping("/gp")
//    @ResponseBody
//    public ResultMsg generatedPosition(HttpServletRequest req){
//        ResultMsg rm = ResultMsg.getSuccess();
//        List<CustomizedPosition> customizedPositionList = new ArrayList<>();
//        List<CustomizedPattern> customizedPatternList = customizedPatternService.getCustomizedPatternList(new CustomizedPattern());
//        for (CustomizedPattern customizedPattern:customizedPatternList) {
//            for (int i=0;i<4;i++){
//                CustomizedPosition customizedPosition = new CustomizedPosition();
//                customizedPosition.setPatternId(customizedPattern.getPatternId());
//                customizedPosition.setPositionType(i+1);  //位置类型 1:正面 2:右侧 3:反面 4:左侧
//                customizedPosition.setPositionPatternX(1000);
//                customizedPosition.setPositionPatternY(1000);
//                customizedPosition.setPositionAvatarX(1000);
//                customizedPosition.setPositionAvatarY(1000);
//                customizedPosition.setPositionTextX(1000);
//                customizedPosition.setPositionTextY(1000);
//                customizedPosition.setPositionStatus(1);
//                customizedPositionList.add(customizedPosition);
//            }
//        }
//        Integer flag = customizedPositionService.saveList(customizedPositionList);
//        return rm;
//    }





}
