package com.ruoyi.web.controller.api;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.RegionTreeSelect;
import com.ruoyi.common.utils.*;
import com.ruoyi.mall.domain.MallGoodsClass;
import com.ruoyi.mall.domain.MallGoodsGoods;
import com.ruoyi.mall.domain.MallGoodsProduct;
import com.ruoyi.mall.domain.MallMemberCms;
import com.ruoyi.mall.domain.vo.GoodsProductVO;
import com.ruoyi.mall.domain.vo.IndexGoodsVO;
import com.ruoyi.mall.service.*;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Stream;

/**
 * @ClassName ApiCommonController
 * @Description 工具方法接口
 * @Author changwj
 * @Date 2021/11/29 10:17 AM
 * @Version 1.0
 **/
@RestController
@RequestMapping("/api/cms")
@ResponseBody
public class ApiCommonController {

    @Resource
    private IMallMemberCmsService mallMemberCmsService;

    @Resource
    private IMallPurchaseNotesService mallPurchaseNotesService;

    @Resource
    private IMallRegionService regionService;

    @GetMapping("/test")
    public List<RegionTreeSelect> test(){
        return regionService.buildRegionTreeList();
    }

    @GetMapping("/getRegionByPid/{pid}")
    public ApiResult getRegionByPid(@PathVariable("pid") Integer pid){
        return ApiResult.ok().put("data",regionService.selectList(pid));
    }

    @GetMapping("/getRegionByPidNew")
    public ApiResult getRegionByPidNew(@RequestParam Map<String, Object> params){
        int pid = Integer.parseInt(params.get("pid").toString());
        return ApiResult.ok().put("data",regionService.selectList(pid));
    }

    /**
     * 购买须知
     * @return
     */
    @GetMapping("/getPurchaseNotes")
    public ApiResult getPurchaseNotes(){
        try {

            return ApiResult.ok().put("data",mallPurchaseNotesService.selectMallPurchaseNotesById(1));
        }catch (Exception e){
            e.printStackTrace();
            return ApiResult.error("服务器异常");
        }

    }

    /**
     * 发送验证码
     * @return
     */
    @PostMapping("/sendCmsCode")
    public ApiResult sendCmsCode(@RequestBody Map<String,Object> param){
        if (!param.containsKey("phone") || MapUtils.getString(param,"phone") == null){
            return ApiResult.error("缺少phone");
        }
        try {
            MallMemberCms mallMemberCms = new MallMemberCms();
            mallMemberCms.setCmsCode(buildCode());
            mallMemberCms.setPhone(MapUtils.getString(param,"phone"));
            //状态（0-未使用，1-已使用）
            mallMemberCms.setStatus(0L);
            mallMemberCms.setCreateAt(DateUtils.getTime());
            //发送验证码
            if (JuSms.aliSendSms(mallMemberCms.getPhone(), mallMemberCms.getCmsCode())){
                return mallMemberCmsService.sendCmsCode(mallMemberCms);
            }
            return ApiResult.error("发送失败");
        }catch (Exception e){
            e.printStackTrace();
            return ApiResult.error("服务器异常");
        }

    }

    /**
     * 生成6位随机数
     * @return
     */
    private String buildCode() {
        String sources = "0123456789";
        Random rand = new Random();
        StringBuffer flag = new StringBuffer();
        for (int j = 0; j < 6; j++) {
            flag.append(sources.charAt(rand.nextInt(10)) + "");
        }
        return flag.toString();
    }

    /**
     * 单个上传
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/common/upload")
    @ResponseBody
    @CrossOrigin
    public ApiResult upload(MultipartFile file, HttpServletRequest request) {
        String fileName = null;
        try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image != null) {
                fileName = "IMG_" + image.getWidth() + "_" + image.getHeight() + "@";
            }else {
                fileName = "";
            }
            String imagePath = new ImgUpload().upload(file.getBytes(),
                    fileName);
            if (StringUtils.isBlank(imagePath)) {
                return  ApiResult.error("上传失败");
            }
            return ApiResult.ok().put("data", imagePath);
        } catch (Exception e) {
            return ApiResult.error();
        }
    }

    /**
     * 单个上传（视频）
     * @param request
     * @return
     */
    @PostMapping("/common/uploadVideo")
    @ResponseBody
    @CrossOrigin
    public ApiResult uploadVideo(HttpServletRequest request) {
        String fileName = null;
        try {
            Part file = request.getPart("file");
            InputStream inputStream = file.getInputStream();

            String imagePath = new ImgUpload().upload(inputStream,
                    fileName);
            if (StringUtils.isBlank(imagePath)) {
                return  ApiResult.error("上传失败");
            }
            return ApiResult.ok().put("data", imagePath);
        } catch (Exception e) {
            return ApiResult.error();
        }
    }

}
