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

import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.content.api.dto.column.ContentColumnListDTO;
import com.gic.content.api.dto.material.ContentMaterialFrontDTO;
import com.gic.content.api.dto.material.ContentMaterialShareInfoDTO;
import com.gic.content.api.enums.ColumnEnum;
import com.gic.content.api.qdto.column.ContentColumnClerkQDTO;
import com.gic.content.api.qdto.material.ContentMaterialPageFrontQDTO;
import com.gic.content.api.qdto.material.ContentMaterialShareQDTO;
import com.gic.content.api.service.ContentColumnApiService;
import com.gic.content.api.service.ContentMaterialApiService;
import com.gic.content.api.service.ContentMaterialShareApiService;
import com.gic.haoban.common.utils.EntityUtil;
import com.gic.haoban.manage.api.service.StaffApiService;
import com.gic.haoban.manage.web.controller.content.adaptor.ClerkStoreAdaptor;
import com.gic.haoban.manage.web.controller.goods.GoodsInfoAdaptor;
import com.gic.haoban.manage.web.qo.content.ContentColumnClerkViewQO;
import com.gic.haoban.manage.web.qo.content.ContentMaterialQO;
import com.gic.haoban.manage.web.qo.content.ContentMaterialShareQO;
import com.gic.haoban.manage.web.vo.content.ContentColumnInfoVO;
import com.gic.haoban.manage.web.vo.content.ContentMaterialInfoVO;
import com.gic.haoban.manage.web.vo.content.ContentMaterialShareInfoVO;
import com.gic.haoban.manage.web.vo.content.SimpleGoodsInfoVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 好办-素材中心（二期）
 *
 */
@RestController
public class ContentMaterialController {

    private static final Logger log = LoggerFactory.getLogger(ContentMaterialController.class);
    @Autowired
    private ContentColumnApiService contentColumnApiService;
    @Autowired
    private ContentMaterialApiService contentMaterialApiService;
    @Autowired
    private ContentMaterialShareApiService contentMaterialShareApiService;

    @Autowired
    private ClerkStoreAdaptor clerkStoreAdaptor;
    @Autowired
    private GoodsInfoAdaptor goodsInfoAdaptor;


    /**
     * 获取栏目筛选条件
     *
     * @param enterpriseId
     * @return
     */
    @RequestMapping(path = "/column-list")
    public RestResponse<List<ContentColumnInfoVO>> queryContentColumn(String enterpriseId, String storeId, String wxEnterpriseId, String clerkId) {
        List<String> storeIdList = new ArrayList<>();
        if (StringUtils.isBlank(storeId)) {
            // 区经 获取管辖的权限
            List<String> storeIds = this.clerkStoreAdaptor.queryClerkStoreIds(clerkId, wxEnterpriseId);
            storeIdList.addAll(storeIds);
        } else {
            storeIdList.add(storeId);
        }
        ServiceResponse<List<ContentColumnListDTO>> serviceResponse = contentColumnApiService.listColumnFront(enterpriseId, ColumnEnum.MATERIAL.value, storeIdList, clerkId);
        if (!serviceResponse.isSuccess() || CollectionUtils.isEmpty(serviceResponse.getResult())) {
            return RestResponse.successResult(Collections.emptyList());
        }
        List<ContentColumnInfoVO> contentColumnInfos = EntityUtil.changeEntityListByJSON(ContentColumnInfoVO.class, serviceResponse.getResult());
        return RestResponse.successResult(contentColumnInfos);
    }


    /**
     * 素材列表
     *
     * @return
     */
    @RequestMapping(path = "/content-material-list")
    public RestResponse<Page<ContentMaterialInfoVO>> queryContentMaterialList(@RequestBody ContentMaterialQO contentMaterialQO) {

        if (StringUtils.isBlank(contentMaterialQO.getEnterpriseId())) {
            log.info("企业id未传 {}", JSON.toJSONString(contentMaterialQO));
            return RestResponse.failure("-777", "参数异常");
        }
        List<Integer> goodsShowStatus = goodsInfoAdaptor.getGoodsShowStatus(contentMaterialQO.getEnterpriseId());
        ContentMaterialPageFrontQDTO contentMaterialPageFrontQDTO = new ContentMaterialPageFrontQDTO();
        contentMaterialPageFrontQDTO.setEnterpriseId(contentMaterialQO.getEnterpriseId());
        contentMaterialPageFrontQDTO.setKeyWord(contentMaterialQO.getSearch());
        contentMaterialPageFrontQDTO.setContentColumnId(contentMaterialQO.getContentColumnId());
        contentMaterialPageFrontQDTO.setMaterialType(contentMaterialQO.getMaterialType());

        if (contentMaterialQO.getSortType() != null) {
            if (contentMaterialQO.getSortType() == 2) {
                contentMaterialPageFrontQDTO.setHotFlag(1);
            }
        }
        if (StringUtils.isBlank(contentMaterialQO.getStoreId())) {
            // 区经 获取管辖的权限
            List<String> storeIds = this.clerkStoreAdaptor.queryClerkStoreIds(contentMaterialQO.getClerkId(), contentMaterialQO.getWxEnterpriseId());
            contentMaterialPageFrontQDTO.setStoreIdList(storeIds);
        } else {
            contentMaterialPageFrontQDTO.setStoreIdList(Collections.singletonList(contentMaterialQO.getStoreId()));
        }
        if (contentMaterialQO.getSearchType() != null && contentMaterialQO.getSearchType().equals(1)) {
            if (StringUtils.isNotBlank(contentMaterialQO.getSearch())) {
                // 搜索条件需要置为空
                contentMaterialPageFrontQDTO.setKeyWord(null);
                List<String> goodsIds = goodsInfoAdaptor.queryGoodsIdWithSearch(contentMaterialQO.getEnterpriseId(), contentMaterialQO.getSearch());
                if (CollectionUtils.isEmpty(goodsIds)) {
                    log.info("搜索商品不存在 {}", contentMaterialQO.getSearch());
                    return RestResponse.successResult(new Page<>());
                }
                contentMaterialPageFrontQDTO.setGoodsIdList(goodsIds);
            }
        }
        BasePageInfo pageInfo = new BasePageInfo();
        pageInfo.setPageNum(contentMaterialQO.getPageNum());
        pageInfo.setPageSize(contentMaterialQO.getPageSize());
        ServiceResponse<Page<ContentMaterialFrontDTO>> serviceResponse = contentMaterialApiService.pageMaterialFront(contentMaterialPageFrontQDTO, pageInfo);
        if (!serviceResponse.isSuccess() || CollectionUtils.isEmpty(serviceResponse.getResult().getResult())) {
            return RestResponse.successResult(new Page<>());
        }
        Page<ContentMaterialFrontDTO> responseResult = serviceResponse.getResult();
        Page<ContentMaterialInfoVO> result = new Page<>();
        result.setTotalCount(responseResult.getTotalCount());
        List<ContentMaterialInfoVO> contentMaterialInfos = responseResult.getResult().stream()
                .map(item -> getContentMaterialInfoVO(goodsShowStatus, item))
                .collect(Collectors.toList());
        result.setResult(contentMaterialInfos);
        result.setCurrentPage(contentMaterialQO.getPageNum());
        result.setPageSize(contentMaterialQO.getPageSize());
        return RestResponse.successResult(result);
    }

    /**
     * 对象转换
     * @param goodsShowStatus
     * @param item
     * @return
     */
    private ContentMaterialInfoVO getContentMaterialInfoVO(List<Integer> goodsShowStatus, ContentMaterialFrontDTO item) {
        ContentMaterialInfoVO contentMaterialInfoVO = new ContentMaterialInfoVO();
        BeanUtils.copyProperties(item, contentMaterialInfoVO);
        if (CollectionUtils.isNotEmpty(item.getContentGoodsList())) {
            List<SimpleGoodsInfoVO> goodsInfoVOS = item.getContentGoodsList()
                    .stream()
                    .filter(temp -> goodsShowStatus.contains(temp.getStatus()))
                    .map(temp -> {
                        SimpleGoodsInfoVO simpleGoodsInfoVO = new SimpleGoodsInfoVO();
                        BeanUtils.copyProperties(temp, simpleGoodsInfoVO);
                        simpleGoodsInfoVO.setGoodsImg(temp.getGoodsImageUrl());
                        return simpleGoodsInfoVO;
                    }).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(goodsInfoVOS)) {
                contentMaterialInfoVO.setContentGoodsList(goodsInfoVOS);
            }
        }
        contentMaterialInfoVO.setPublishTime(item.getPublishBeginTime());
        if (StringUtils.isNotBlank(item.getMaterialImageUrls())) {
            String[] split = StringUtils.split(item.getMaterialImageUrls(), ",");
            List<String> imageUrls = Arrays.stream(split).collect(Collectors.toList());
            contentMaterialInfoVO.setMaterialImageUrls(imageUrls);
        }
        if (StringUtils.isNotBlank(item.getMaterialThumbnailImageUrls())) {
            String[] split = StringUtils.split(item.getMaterialThumbnailImageUrls(), ",");
            List<String> imageUrls = Arrays.stream(split).collect(Collectors.toList());
            contentMaterialInfoVO.setMaterialThumbnailImageUrls(imageUrls);
        }
        return contentMaterialInfoVO;
    }

    /**
     * 分享商品素材
     *
     * @param contentMaterialShareQO
     * @return
     */
    @RequestMapping(path = "/share-content-material")
    public RestResponse<ContentMaterialShareInfoVO> shareContentMaterial(ContentMaterialShareQO contentMaterialShareQO) {

        if (StringUtils.isBlank(contentMaterialShareQO.getEnterpriseId())) {
            return RestResponse.failure("-777", "企业参数异常");
        }
        if (contentMaterialShareQO.getContentMaterialId() == null) {
            // 无素材id 不生成参数
            return RestResponse.successResult();
        }
        ContentMaterialShareQDTO contentMaterialShareQDTO = new ContentMaterialShareQDTO();
        BeanUtils.copyProperties(contentMaterialShareQO, contentMaterialShareQDTO);
        ServiceResponse<ContentMaterialShareInfoDTO> serviceResponse = contentMaterialShareApiService.shareContentMaterial(contentMaterialShareQDTO);
        if (!serviceResponse.isSuccess()) {
            return RestResponse.failure(serviceResponse.getCode(), serviceResponse.getMessage());
        }
        ContentMaterialShareInfoVO shareInfoVO = new ContentMaterialShareInfoVO();
        BeanUtils.copyProperties(serviceResponse.getResult(), shareInfoVO);
        return RestResponse.successResult(shareInfoVO);
    }

    /**
     * 导购栏目最后访问记录
     *
     * @param contentColumnClerkViewQO qo
     * @return
     */
    @RequestMapping(path = "/column-clerk")
    public RestResponse<Void> viewColumnClerk(@RequestBody ContentColumnClerkViewQO contentColumnClerkViewQO) {
        if (StringUtils.isBlank(contentColumnClerkViewQO.getEnterpriseId())) {
            return RestResponse.failure("-777", "企业参数异常");
        }
        ContentColumnClerkQDTO columnClerkQDTO = EntityUtil.changeEntityByJSON(ContentColumnClerkQDTO.class, contentColumnClerkViewQO);
        ServiceResponse<Void> serviceResponse = contentColumnApiService.saveOrUpdateColumnClerk(columnClerkQDTO);
        if (!serviceResponse.isSuccess()) {
            return RestResponse.failure(serviceResponse.getCode(), serviceResponse.getMessage());
        }
        return RestResponse.successResult();
    }

}
