package com.gic.haoban.manage.web.controller;

import com.gic.api.base.commons.Page;
import com.gic.commons.util.DateUtil;
import com.gic.haoban.base.api.common.BasePageInfo;
import com.gic.haoban.base.api.common.PageResult2;
import com.gic.haoban.common.utils.EntityUtil;
import com.gic.haoban.common.utils.HaobanResponse;
import com.gic.haoban.common.utils.PageUtil;
import com.gic.haoban.manage.api.dto.MaterialCategoryDTO;
import com.gic.haoban.manage.api.dto.MaterialDTO;
import com.gic.haoban.manage.api.service.MaterialApiService;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.vo.MaterialVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class MaterialController extends WebBaseController {

    private static Logger logger = LoggerFactory.getLogger(MaterialController.class);

    @Autowired
    private MaterialApiService materialApiService;

    /**
     * desc: 分页查询素材
     *
     * @param wxEnterpriseId 企业微信id
     * @param keyword        素材标题
     * @param categoryId     分类id
     * @param materialType   素材类型
     * @param pageInfo       分页参数
     * @return : {@link HaobanResponse}
     * @author : YongEn
     * @date : 2021/11/18
     */
    @RequestMapping("/material-list")
    public HaobanResponse materialList(String wxEnterpriseId,
                                       String keyword,
                                       String categoryId,
                                       Integer materialType,
                                       BasePageInfo pageInfo) {

        Page<MaterialDTO> page = materialApiService.listMaterial(wxEnterpriseId, keyword, categoryId, materialType, pageInfo);

        //暂时转换
        PageResult2 pageResult2 = PageUtil.getPageInfo(page);
        return resultResponse(HaoBanErrCode.ERR_1, pageResult2);
    }

    /**
     * 素材查询
     *
     * @return
     */
    @RequestMapping("/material-type")
    public HaobanResponse materialType(String wxEnterpriseId) {
        List<MaterialCategoryDTO> list = materialApiService.listCategory(wxEnterpriseId);
        List<MaterialVO> handerList = new ArrayList<MaterialVO>();
        MaterialVO vo = new MaterialVO();
		// 默认给-1位全部分组标准-查询列表时如果传入-1默认查询全部素材
        vo.setCategoryId("-1");
        vo.setCategoryName("全部分组");
        vo.setCategoryParentId("0");
        vo.setWxEnterpriseId(wxEnterpriseId);
        handerList.add(vo);
        for (MaterialCategoryDTO materialCategoryDTO : list) {
            if ("0".equals(materialCategoryDTO.getCategoryParentId())) {
                handerList.add(EntityUtil.changeEntityByJSON(MaterialVO.class, materialCategoryDTO));
            }
        }
        Map<String, List<MaterialCategoryDTO>> map = list.stream().collect(Collectors.groupingBy(MaterialCategoryDTO::getCategoryParentId));
        handerSonMaterial(handerList, map);
        for (MaterialVO materialVO : handerList) {
            List<MaterialVO> sonVoList = materialVO.getList();
            if (sonVoList != null && !sonVoList.isEmpty()) {
                handerSonMaterial(sonVoList, map);
            }
        }
        return resultResponse(HaoBanErrCode.ERR_1, handerList);
    }

    /**
     * 素材查询
     *
     * @return
     */
    @RequestMapping("/reupdalod-material")
    public HaobanResponse reUpdalodMetail(String materialId) {
        if (StringUtils.isBlank(materialId)) {
            return resultResponse(HaoBanErrCode.ERR_10015);
        }
        MaterialDTO material = materialApiService.selectMaterialById(materialId);
        if (material == null) {

        }
        String medialId = "";
        if (material.getMaterialType() == 2 || material.getMaterialType() == 4 || material.getMaterialType() == 5) {
            if (material.getMediaId() == null) {
                medialId = materialApiService.reUpdalodMetail(materialId);
            } else {
                Date wxLastTime = material.getWxLastUploadTime();
                medialId = material.getMediaId();
                if (DateUtil.addDay(wxLastTime, 3).getTime() < System.currentTimeMillis()) {
                    medialId = materialApiService.reUpdalodMetail(materialId);
                }
            }
        }
        return resultResponse(HaoBanErrCode.ERR_1, medialId);
    }


    private void handerSonMaterial(List<MaterialVO> handerList, Map<String, List<MaterialCategoryDTO>> map) {
        for (MaterialVO materialVO : handerList) {
            List<MaterialCategoryDTO> sonList = map.get(materialVO.getCategoryId());
            List<MaterialVO> sonVoList = EntityUtil.changeEntityListByJSON(MaterialVO.class, sonList);
            materialVO.setList(sonVoList);
//			logger.info("map={},handerList={},categoryId={},sonVoList={}",JSON.toJSONString(map),JSON.toJSONString(handerList),materialVO.getCategoryId(),JSON.toJSONString(sonVoList));
//			while(sonVoList != null && sonVoList.size() > 0){
//				handerSonMaterial(sonVoList, map);
//			}
        }
    }

}
