package com.slodon.b2b2c.controller.seller.admin;


import com.slodon.b2b2c.core.constant.StoreConst;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.PageVO;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.core.util.AssertUtil;
import com.slodon.b2b2c.core.util.UserUtil;
import com.slodon.b2b2c.core.util.WebUtil;
import com.slodon.b2b2c.model.seller.SellerMediaModel;
import com.slodon.b2b2c.model.seller.StoreModel;
import com.slodon.b2b2c.seller.dto.MediaListAddDTO;
import com.slodon.b2b2c.seller.dto.MediaListUpdateDTO;
import com.slodon.b2b2c.seller.example.StoreExample;
import com.slodon.b2b2c.seller.pojo.Store;
import com.slodon.b2b2c.seller.pojo.Vendor;
import com.slodon.b2b2c.system.pojo.Admin;
import com.slodon.b2b2c.system.pojo.SysMedia;
import com.slodon.b2b2c.vo.seller.MediaListVo;
import com.slodon.b2b2c.vo.seller.MediaTreeVo;
import com.slodon.b2b2c.vo.seller.StoreVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 多媒体管理
 */

@Api(tags = "seller多媒体管理")
@RestController
@RequestMapping("v3/seller/admin/media")
public class AdminMediaController {

    @Resource
    private SellerMediaModel sellerMediaModel;
    @Resource
    private StoreModel storeModel;

    @ApiOperation("多媒体管理列表-admin")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "多媒体分类", paramType = "query"),
            @ApiImplicitParam(name = "fileType", value = "文件类型", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("newList")
    public JsonResult<PageVO<MediaListVo>> getNewList(HttpServletRequest request,
                                                   @RequestParam(value = "type", required = false) String type,
                                                   @RequestParam(value = "name", required = false) String name,
                                                   @RequestParam(value = "fileType", required = false) String fileType,
                                                   @RequestParam(value = "startTime", required = false) String startTime,
                                                   @RequestParam(value = "endTime", required = false) String endTime,
                                                   @RequestParam(value = "storeId", required = false) Long storeId){
        PagerInfo pager = WebUtil.handlerPagerInfo(request);

        List<SysMedia> list = getMediaList(pager,type,fileType,startTime,endTime,storeId,name);
        ArrayList<MediaListVo> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(sysMedia -> {
                vos.add(new MediaListVo(sysMedia));
            });
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }

    /**
     * 多媒体管理列表公用方法
     * @param pager
     * @param type
     * @param fileType
     * @param startTime
     * @param endTime
     * @param storeId
     * @param name
     * @return
     */
    private List<SysMedia> getMediaList(PagerInfo pager,String type, String fileType,
                                        String startTime,String endTime,Long storeId,String name){
        //根据前台选择之后传回来的上传多媒体类型来设置数据库查的类型 file/video/picture
        ArrayList<String> fileTypeList = null;
        if(!StringUtils.isEmpty(fileType)){
            fileTypeList = getFileTypeList(fileType);
        }
        if("/".equals(type)){
            type = null;
        }
        pager.setRowsCount(sellerMediaModel.mediaListPageCount(type,fileTypeList,startTime,endTime,storeId,name));
        List<SysMedia> list = sellerMediaModel.getMediaListByPage(type,fileTypeList,startTime,endTime, pager,storeId,name);
        return list;
    }

    /**
     * 根据前台选择之后传回来的上传多媒体类型来设置数据库查的类型
     * @param fileType 前台选择之后传回来的上传多媒体类型 有 图片/视频/文件
     * @return
     */
    public ArrayList<String> getFileTypeList(String fileType){
        ArrayList<String> fileTypeList = new ArrayList<>();
        if("picture".equals(fileType)){
            fileTypeList.add(".jpg");
            fileTypeList.add(".jpeg");
            fileTypeList.add(".bmp");
            fileTypeList.add(".gif");
            fileTypeList.add(".png");
            fileTypeList.add(".tif");
        }else if("video".equals(fileType)){
            fileTypeList.add(".avi");
            fileTypeList.add(".mov");
            fileTypeList.add(".rmvb");
            fileTypeList.add(".rm");
            fileTypeList.add(".flv");
            fileTypeList.add(".mp4");
            fileTypeList.add(".3gp");
            fileTypeList.add("video");
        }else if("file".equals(fileType)){
            fileTypeList.add(".doc");
            fileTypeList.add(".docx");
            fileTypeList.add(".xls");
            fileTypeList.add(".xlsx");
            fileTypeList.add(".pdf");
            fileTypeList.add(".zip");
            fileTypeList.add(".rar");
        }
        return fileTypeList;
    }


    /**
     * 编辑
     * @param request
     * @param mediaListUpdateDTO 编辑时入参
     * @return
     */
    @ApiOperation("编辑多媒体")
    @PostMapping("edit")
    @ResponseBody
    public JsonResult<Integer> editMediaList(HttpServletRequest request, MediaListUpdateDTO mediaListUpdateDTO) {
        //postman测试数据
//        mediaListUpdateDTO.setId(18L);
//        mediaListUpdateDTO.setName("111--111");
//        mediaListUpdateDTO.setPath("/images/seller/goods/jLoKz1kGTkHfttJk0CR.jpg");
//        mediaListUpdateDTO.setType("brand");
//        mediaListUpdateDTO.setExtend(".jpg");
        // 验证参数是否为空
        AssertUtil.notNull(mediaListUpdateDTO, "多媒体信息不能为空，请重试！");
        AssertUtil.notEmpty(mediaListUpdateDTO.getName(), "多媒体名称不能为空，请重试！");
        AssertUtil.notEmpty(mediaListUpdateDTO.getPath(), "多媒体图片路径不能为空，请重试！");
        AssertUtil.notEmpty(mediaListUpdateDTO.getType(), "多媒体分类不能为空，请重试！");

        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        sellerMediaModel.updateMediaList(mediaListUpdateDTO, vendor);
        return SldResponse.success("编辑成功", "多媒体id"+mediaListUpdateDTO.getId());
    }


    @ApiOperation("新增多媒体")
    @PostMapping("add")
    @ResponseBody
    public JsonResult<Integer> addMediaList(HttpServletRequest request, MediaListAddDTO mediaListAddDTO) {
        //postman测试数据
//        mediaListAddDTO.setName("222");
//        mediaListAddDTO.setPath("/images/seller/goods/wvUQsyTV1SN21rBMdaa.jpg");
//        mediaListAddDTO.setType("goods");
//        mediaListAddDTO.setExtend(".jpg");

        String logMsg = "图片名称" + mediaListAddDTO.getName();
        // 验证参数是否为空
        AssertUtil.notNull(mediaListAddDTO, "多媒体信息不能为空，请重试！");
        AssertUtil.notEmpty(mediaListAddDTO.getName(), "多媒体名称不能为空，请重试！");
        AssertUtil.notEmpty(mediaListAddDTO.getPath(), "多媒体图片路径不能为空，请重试！");
        AssertUtil.notEmpty(mediaListAddDTO.getType(), "多媒体分类不能为空，请重试！");

        Admin admin = UserUtil.getUser(request, Admin.class);

        sellerMediaModel.saveMedia1(mediaListAddDTO, admin);
        return SldResponse.success("添加成功", logMsg);
    }


    @ApiOperation("多媒体删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mediaIds", value = "多媒体Id字符串集合，用逗号隔开", required = true, paramType = "query")
    })
    @PostMapping("deleteMediaByIds")
    public JsonResult<Integer> deleteMediaByIds(HttpServletRequest request, String mediaIds) {
        // 验证参数是否为空
        String logMsg = "删除多媒体Id" + mediaIds;
        AssertUtil.notEmpty(mediaIds, "删除多媒体ID不能为空,请重试");
        AssertUtil.notFormatFrontIds(mediaIds, "mediaIds格式错误,请重试");

        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        int number = sellerMediaModel.deleteMediaByIds(mediaIds);
        return SldResponse.success(number + "条多媒体删除成功", logMsg);
    }


    /**
     *多媒体左边的树形结构模拟数据
     * @return
     */
    public List<MediaTreeVo> getTree(){
        List<MediaTreeVo> trees = Arrays.asList(
                new MediaTreeVo(1,"系统","/",0),
                new MediaTreeVo(2,"商品","goods",1),
                new MediaTreeVo(3,"品牌","sellerBrand",1),
                new MediaTreeVo(4,"店铺简介","profile",1),
                new MediaTreeVo(5,"店铺展示","companyShow",1),
                new MediaTreeVo(6,"荣誉资质","certificate",1),
//                new MediaTreeVo(7,"logo设置","logo",1),
                new MediaTreeVo(8,"商品视频","video",1)
        );
        return trees;

    }

    /**
     * list集合转化为树形结构的json之后返回前台
     * @return
     */
    @GetMapping("getTree")
    public JsonResult<List<MediaTreeVo>> list2Tree() {
        List<MediaTreeVo> trees = getTree();
        List<MediaTreeVo> result = new ArrayList<>();
        if(!CollectionUtils.isEmpty(trees)){
            for(MediaTreeVo p : trees){
                if(p.getParentId() == null || p.getParentId() == 0) {
                    MediaTreeVo vo = new MediaTreeVo(p.getId(),p.getName(),p.getAttribute(),p.getParentId());
                    vo.setNodeList(recurrence(trees, p));
                    result.add(vo);
                }
            }
        }
        return SldResponse.success(result);
    }
    /**
     *  递归函数
     * @param list
     * @param vo
     */
    private static List<MediaTreeVo> recurrence(List<MediaTreeVo> list, MediaTreeVo vo){
        List<MediaTreeVo> subNodes = new ArrayList<>();
        for(MediaTreeVo d : list){
            if (vo.getId().equals(d.getParentId())) {
                MediaTreeVo sub = new MediaTreeVo(d.getId(),d.getName(),d.getAttribute(), d.getParentId());
                sub.setNodeList(recurrence(list, d));
                subNodes.add(sub);
            }
        }
        return subNodes;
    }


    @ApiOperation("店铺下拉框数据")
    @GetMapping("getStoreList")
    public JsonResult<List<StoreVO>> getStoreList(HttpServletRequest request) {
        StoreExample storeExample = new StoreExample();
        storeExample.setStateNotEquals(StoreConst.STORE_STATE_DELETE);
        List<Store> storeList = storeModel.getStoreList(storeExample, null);
        List<StoreVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(storeList)) {
            storeList.forEach(store -> {
                StoreVO vo = new StoreVO(store);
                vos.add(vo);
            });
        }
        return SldResponse.success(vos);
    }







}
