package cn.stylefeng.guns.zjxl.cnotroller;

import cn.stylefeng.guns.config.FastDFSConfig;
import cn.stylefeng.guns.sys.modular.user.param.SysUserParam;
import cn.stylefeng.guns.zjxl.model.UploadModel;
import cn.stylefeng.guns.zjxl.model.ZjxlArticleContent;
import cn.stylefeng.guns.zjxl.model.ZjxlBanner;
import cn.stylefeng.guns.zjxl.model.ret.BannerCompanyCaseRet;
import cn.stylefeng.guns.zjxl.model.ret.BaseResultModel;
import cn.stylefeng.guns.zjxl.model.ret.ResultOneModel;
import cn.stylefeng.guns.zjxl.service.ZjxlArticleContentService;
import cn.stylefeng.guns.zjxl.service.ZjxlBannerService;
import cn.stylefeng.guns.zjxlUtil.BaseController;
import cn.stylefeng.guns.zjxlUtil.FastDFSUtil;
import cn.stylefeng.guns.zjxlUtil.PageUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;


/***
 * @ClassName: ZjxlBannerCnotroller
 * @Description:
 * @Auther: shi kejing
 * @Date: 2020/10/30 17:37
 */
@RestController
@Api(description = "公司官网主页")
@RequestMapping(value = "/zjxl/banner")
public class ZjxlBannerCnotroller extends BaseController {

    private Logger logger = (Logger) LoggerFactory.getLogger(ZjxlBannerCnotroller.class);

    @Autowired
    private ZjxlBannerService bannerService;
    @Autowired
    private ZjxlArticleContentService articleContentService;

    @Autowired
    FastDFSConfig fastDFSConfig;
    @Autowired
    FastDFSUtil fastDFSUtil;
    @Value("${fastDFS.fastdfs_file_url}")
    private String fastdfs_file_url;

    @RequestMapping(value = "/findBannerById", method = RequestMethod.GET)
    @ApiOperation(value = "查看banner列表")
    public String findBannerById(@ApiParam(name = "id", value = "bannerId", required = false) @RequestParam(value = "id", required = false)String id,
                                 @ApiParam(name = "name", value = "bannerName", required = false) @RequestParam(value = "name", required = false)String name,
                                 @ApiParam(name = "pageNo", value = "第几页", defaultValue = "1") @RequestParam(value = "pageNo", required = false) Integer pageNo,
                                 @ApiParam(name = "pageSize", value = "分页大小", defaultValue = "10") @RequestParam(value = "pageSize", required = false) Integer pageSize){
        try {
            List<ZjxlBanner> banner = bannerService.findById(id,name,pageNo-1,pageSize);
            return write(200,"查询成功","data",PageUtil.getPage(banner,pageNo,pageSize,bannerService.allCount()));
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"查询失败");
        }
    }

    @RequestMapping(value = "/addBanner", method = RequestMethod.POST)
    @ApiOperation(value = "添加banner")
    public String addBanner(@ApiParam(name = "bannerName", value = "bannerName", required = false) @RequestParam(value = "bannerName", required = false)String bannerName,
                            @ApiParam(name = "bannerImage", value = "图片", required = false) @RequestParam(value = "bannerImage", required = false)String bannerImage,
                            @ApiParam(name = "bannerType", value = "跳转方式: 0-无  1-站内文章  2-外部链接", required = false) @RequestParam(value = "bannerType", required = false)Integer bannerType,
                            @ApiParam(name = "bannerTypeUrl", value = "跳转链接(如果是站内文章，传文章id)", required = false) @RequestParam(value = "bannerTypeUrl", required = false)String bannerTypeUrl,
                            @ApiParam(name = "bannerSort", value = "排序", required = false) @RequestParam(value = "bannerSort", required = false)Integer bannerSort,
                            @ApiParam(name = "bannerIsLine", value = "是否上线", required = false,defaultValue = "0") @RequestParam(value = "bannerIsLine", required = false)Integer bannerIsLine){
        ZjxlBanner banner = new ZjxlBanner();
        banner.setBannerImage(bannerImage);//String
        banner.setBannerIsLine(bannerIsLine);//integer
        List<ZjxlBanner> bannerList = bannerService.findBannerAll();
        if (bannerList.size() > 0){
            Iterator<ZjxlBanner> bannerIterator = bannerList.iterator();
            while (bannerIterator.hasNext()){
                if (bannerIterator.next().getBannerName().equals(bannerName)){
                    return write(-1,"该名称已存在");
                }
            }
        }
        banner.setBannerName(bannerName);//string
        banner.setBannerSort(bannerSort);
        banner.setBannerType(bannerType);
        if (bannerType == 1){
            List<ZjxlArticleContent> articleContentList = articleContentService.findArticleContentById(bannerTypeUrl);
            JSONObject object = new JSONObject();
            object.put("articleContentId",articleContentList.get(0).getArticleContentId());
            object.put("articleContentType",articleContentList.get(0).getArticleContentType());
            object.put("articleContentClassify",articleContentList.get(0).getArticleContentClassify());
            object.put("articleContentSubclassify",articleContentList.get(0).getArticleContentSubclassify());
            object.put("articleContentTitle",articleContentList.get(0).getArticleContentTitle());
            banner.setBannerTypeUrl(object.toString());
        }else {
            banner.setBannerTypeUrl(bannerTypeUrl);
        }
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // new Date()为获取当前系统时间
        banner.setBannerCreateTime(df.format(new Date()));
        try {
            logger.info("执行banner添加，参数："+banner);
            return write(200,"添加成功","data",bannerService.addBanner(banner));
        }catch (Exception e){
            return write(-1,"添加失败");
        }
    }

    @RequestMapping(value = "/deleteBannerById", method = RequestMethod.POST)
    @ApiOperation(value = "删除banner")
    public String deleteBannerById(String id){
        try {
            logger.info("删除banner，参数"+id);
            if(id == null){
                return write(-1,"参数获取失败:null");
            }
            return write(200,"删除成功","data",bannerService.deleteBannerById(id));
        }catch (Exception e){
            e.printStackTrace();
            return write(-1,"删除失败");
        }
    }

    @RequestMapping(value = "/updateIsLine", method = RequestMethod.POST)
    @ApiOperation(value = "修改是否上线")
    public String updateIsLine(String id,
                               Integer isLine){
        try {
            logger.info("修改是否上线：id====="+id+"，isLine===="+isLine);
            if (id == null || isLine == null){
                return write(-1,"获取参数失败");
            }
            return write(200,"修改成功","data",bannerService.updateIsLine(id,isLine));
        }catch (Exception e){
            e.printStackTrace();
            return write(-1,"修改失败");
        }
    }

    @RequestMapping(value = "/updataBanner", method = RequestMethod.POST)
    @ApiOperation(value = "编辑banner")
    public String updataBanner(@ApiParam(name = "bannerId", value = "bannerId", required = false) @RequestParam(value = "bannerId", required = true)String bannerId,
                               @ApiParam(name = "bannerName", value = "bannerName", required = false) @RequestParam(value = "bannerName", required = false)String bannerName,
                               @ApiParam(name = "bannerImage", value = "图片", required = false) @RequestParam(value = "bannerImage", required = false)String bannerImage,
                               @ApiParam(name = "bannerType", value = "跳转方式: 0-无  1-站内文章  2-外部链接", required = false) @RequestParam(value = "bannerType", required = false)Integer bannerType,
                               @ApiParam(name = "bannerTypeUrl", value = "跳转链接(如果是站内文章，传文章id)", required = false) @RequestParam(value = "bannerTypeUrl", required = false)String bannerTypeUrl,
                               @ApiParam(name = "bannerSort", value = "排序", required = false) @RequestParam(value = "bannerSort", required = false)Integer bannerSort,
                               @ApiParam(name = "bannerIsLine", value = "是否上线", required = false,defaultValue = "0") @RequestParam(value = "bannerIsLine", required = false)Integer bannerIsLine){
        ZjxlBanner banner = new ZjxlBanner();
        banner.setBannerId(bannerId);
        if (bannerType != null){
            banner.setBannerType(bannerType);
        }
        if (bannerType != null){
            if (bannerType == 1){
                List<ZjxlArticleContent> articleContentList = articleContentService.findArticleContentById(bannerTypeUrl);
                JSONObject object = new JSONObject();
                object.put("articleContentId",articleContentList.get(0).getArticleContentId());
                object.put("articleContentType",articleContentList.get(0).getArticleContentType());
                object.put("articleContentClassify",articleContentList.get(0).getArticleContentClassify());
                object.put("articleContentSubclassify",articleContentList.get(0).getArticleContentSubclassify());
                object.put("articleContentTitle",articleContentList.get(0).getArticleContentTitle());
                banner.setBannerTypeUrl(object.toString());
            }else {
                banner.setBannerTypeUrl(bannerTypeUrl);
            }
        }
        if (bannerSort != null){
            banner.setBannerSort(bannerSort);
        }
        List<ZjxlBanner> bannerList = bannerService.findBannerAll();
        if (bannerList.size() > 0){
            Iterator<ZjxlBanner> bannerIterator = bannerList.iterator();
            while (bannerIterator.hasNext()){
                if (bannerIterator.next().getBannerName().equals(bannerName)){
                    return write(-1,"该名称已存在");
                }
            }
        }
        if (bannerName != null){
            banner.setBannerName(bannerName);
        }
        if (bannerImage != null){
            banner.setBannerImage(bannerImage);
        }
        if (bannerIsLine != null){
            banner.setBannerIsLine(bannerIsLine);
        }
        try {
            return write(200,"修改成功","data",bannerService.updateBanner(banner));
        }catch (Exception e){
            e.printStackTrace();
            return write(-1,"修改失败");
        }
    }

    /**
     * 聊天附件上传
     *
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    @RequestMapping(value = "/file", method = RequestMethod.POST)
    @ApiOperation(value = "单文件上传")
    public ResultOneModel<UploadModel> uploadFile(
            @ApiParam(value = "文件", required = true) @RequestParam(value = "file", required = true) MultipartFile file
    ) {
        try {
            UploadModel uploadModel = fileUpload(file);
            return new ResultOneModel<UploadModel>(uploadModel);
        } catch (Exception e) {
            return new ResultOneModel(BaseResultModel.statusEm.file_upload_error.getCode(), BaseResultModel.statusEm.file_upload_error.getMessage() + "," + e.getMessage(), new JSONObject());
        }
    }

    @RequestMapping(value = "/finfBannerCompanyCaseById", method = RequestMethod.GET)
    @ApiOperation(value = "两表查询，把结果放一个实体类返回(测试)")
    public List<BannerCompanyCaseRet> finfBannerCompanyCaseById(String id){
       return bannerService.finfBannerCompanyCaseById(id);
    }

    /**
     * 文件上传到fastDfs
     *
     * @param mf
     * @return
     */
    private UploadModel fileUpload(MultipartFile mf) throws Exception {
        UploadModel uploadModel = new UploadModel();
        // 得到文件的完整名称  xxx.txt
        String fullName = mf.getOriginalFilename();
        //得到文件类型
        String fileType = fullName.substring(fullName.lastIndexOf(".") + 1).toLowerCase();
        String fileName = fullName.substring(0, fullName.lastIndexOf("."));
        //上传到fastdfs
//        ObjectNode objectNode = fastDFSConfig.fastDFSUtil().upload(mf.getInputStream(), fileType, "");
        ObjectNode objectNode = fastDFSUtil.upload(mf.getInputStream(), fileType, "");
        //解析返回的objectNode
        uploadModel.setFileName(fileName);
        uploadModel.setFileType(fileType);
        uploadModel.setFullUri(objectNode.get("fid").toString().replaceAll("\"", ""));
        uploadModel.setFullUrl(fastdfs_file_url + objectNode.get("fid").toString().replaceAll("\"", ""));
        return uploadModel;
    }

    @RequestMapping(value = "/findBannerByIsOnLine", method = RequestMethod.GET)
    @ApiOperation(value = "查看banner列表，仅显示已上线的")
    public String findBannerByIsOnLine(
                                 @ApiParam(name = "pageNo", value = "第几页", defaultValue = "1") @RequestParam(value = "pageNo", required = false) Integer pageNo,
                                 @ApiParam(name = "pageSize", value = "分页大小", defaultValue = "1") @RequestParam(value = "pageSize", required = false) Integer pageSize){
        try {
            return write(200,"查询成功","data",bannerService.findBannerByIsOnLine(pageNo-1,pageSize));
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"查询失败");
        }
    }
}
