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

import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Constant;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.content.api.dto.material.ContentMaterialDTO;
import com.gic.content.api.enums.*;
import com.gic.content.api.qdto.material.ContentMaterialPageQDTO;
import com.gic.content.api.qdto.material.ContentMaterialQDTO;
import com.gic.content.api.qdto.producer.ContentProducerClerkRandomQDTO;
import com.gic.content.api.service.ContentMaterialApiService;
import com.gic.haoban.common.utils.EntityUtil;
import com.gic.haoban.manage.api.dto.StaffDTO;
import com.gic.haoban.manage.web.controller.content.adaptor.ClerkStoreAdaptor;
import com.gic.haoban.manage.web.controller.content.adaptor.MaterialDataAdaptor;
import com.gic.haoban.manage.web.qo.content.ContentAuditMaterialQO;
import com.gic.haoban.manage.web.qo.content.ContentMaterialSaveQO;
import com.gic.haoban.manage.web.vo.content.creative.ContentMaterialConvsVO;
import com.gic.haoban.manage.web.vo.content.creative.ContentMaterialDataVO;
import com.gic.haoban.manage.web.vo.content.creative.ContentMaterialVO;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * 好办-创作中心
 *
 */
@Controller
@RequestMapping("/creative")
public class ContentCreativeController {

    private static final Logger log = LoggerFactory.getLogger(ContentCreativeController.class);
    @Autowired
    private ContentMaterialApiService contentMaterialApiService;
    @Autowired
    private ClerkService clerkService;
    @Autowired
    private ClerkStoreAdaptor clerkStoreAdaptor;
    @Autowired
    private MaterialDataAdaptor materialDataAdaptor;

    /**
     * 创建素材
     * @param saveQO
     * @return
     */
    @ResponseBody
    @RequestMapping("/save-material")
    public RestResponse<ContentMaterialDTO> saveMaterial(@Validated @RequestBody ContentMaterialSaveQO saveQO) {
        String clerkId = saveQO.getClerkId();
        StaffDTO staffDTO = clerkStoreAdaptor.queryStaff(clerkId);
        if (staffDTO == null) {
            return RestResponse.failure("-1", "成员不存在");
        }
        ClerkDTO clerk = clerkService.getClerkByClerkId(clerkId);
        if (clerk == null) {
            return RestResponse.failure("-1", "导购不存在");
        }
        //组装导购发布人信息
        ContentProducerClerkRandomQDTO producerQDTO = new ContentProducerClerkRandomQDTO();
        producerQDTO.setProducerType(MaterialProducerTypeEnum.CLERK.value);
        producerQDTO.setNickName(clerk.getClerkName());
        producerQDTO.setAvatar(staffDTO.getNickName());
        producerQDTO.setEnterpriseId(saveQO.getEnterpriseId());
        producerQDTO.setClerkId(clerkId);
        producerQDTO.setClerkCode(clerk.getClerkCode());
        producerQDTO.setStoreId(clerk.getStoreId());
        ContentMaterialQDTO contentMaterialQDTO = EntityUtil.changeEntityByJSON(ContentMaterialQDTO.class, saveQO);
        contentMaterialQDTO.setCreatorId(clerk.getClerkId());
        contentMaterialQDTO.setCreatorName(clerk.getClerkName());
        contentMaterialQDTO.setUpdaterId(clerk.getClerkId());
        contentMaterialQDTO.setUpdaterName(clerk.getClerkName());
        contentMaterialQDTO.setProducer(producerQDTO);
        contentMaterialQDTO.setMaterialPurpose(MaterialPurposeEnum.AUDIT.code);
        contentMaterialQDTO.setPublishType(MaterialPublishTypeEnum.NONE.value);
        contentMaterialQDTO.setShelfStatus(Constant.FLAG_TRUE);
        ServiceResponse<ContentMaterialDTO> response = contentMaterialApiService.saveMaterial(contentMaterialQDTO);
        if (!response.isSuccess()) {
            return RestResponse.failure(response.getCode(), response.getMessage());
        }
        return RestResponse.successResult(response.getResult());
    }

    /**
     * 删除素材
     * @param enterpriseId  企业id
     * @param contentMaterialId 素材id
     * @return
     */
    @ResponseBody
    @RequestMapping("/delete-material")
    public RestResponse<Void> saveMaterial(String enterpriseId, Long contentMaterialId) {
        ServiceResponse<Void> response = contentMaterialApiService.deleteMaterial(enterpriseId, contentMaterialId);
        if (!response.isSuccess()) {
            return RestResponse.failure(response.getCode(), response.getMessage());
        }
        return RestResponse.successResult();
    }


    /**
     * 素材详情
     * @param enterpriseId 企业id
     * @param contentMaterialId 素材id
     * @return
     */
    @ResponseBody
    @RequestMapping("/detail-material")
    public RestResponse<ContentMaterialVO> getMaterialDetail(String enterpriseId, Long contentMaterialId) {
        ServiceResponse<ContentMaterialDTO> response = contentMaterialApiService.getMaterialDetail(enterpriseId, contentMaterialId);
        if (!response.isSuccess()) {
            return RestResponse.failure(response.getCode(), response.getMessage());
        }
        ContentMaterialVO detailVO = EntityUtil.changeEntityByJSON(ContentMaterialVO.class, response.getResult());
        Map<Long, ContentMaterialConvsVO> map = materialDataAdaptor.queryCreativeConvsMap(enterpriseId, Lists.newArrayList(detailVO.getContentMaterialId()), null);
        ContentMaterialConvsVO materialConvsVO = map.get(detailVO.getContentMaterialId());
        detailVO.setConvs(materialConvsVO);
        return RestResponse.successResult(detailVO);
    }

    /**
     * 素材列表
     * @param auditMaterialQO qo
     * @return
     */
    @ResponseBody
    @RequestMapping("/page-material")
    public RestResponse<Page<ContentMaterialVO>> pageAuditMaterial(@RequestBody ContentAuditMaterialQO auditMaterialQO) {
        ContentMaterialPageQDTO pageQDTO = new ContentMaterialPageQDTO();
        String enterpriseId = auditMaterialQO.getEnterpriseId();
        pageQDTO.setEnterpriseId(enterpriseId);
        pageQDTO.setStoreId(auditMaterialQO.getStoreId());
        pageQDTO.setClerkId(auditMaterialQO.getClerkId());
        pageQDTO.setQueryScene(MaterialSearchSceneEnum.HAOBAN_AUDIT.value);
        Integer convsFlag = auditMaterialQO.getConvsFlag();
        // 分页数据总数（无转化查询取素材分页数据，有转化查询取数据组返回的分页数据）
        Integer totalCount = null;
        //素材对应转化数据map
        Map<Long, ContentMaterialConvsVO> map = null;
        //转化数据过滤的素材id列表
        List<Long> filterMaterialIdList = null;
        boolean convs = convsFlag != null && convsFlag == Constant.FLAG_TRUE;
        //是否有转化查询
        if (convs) {
            ServiceResponse<List<Long>> listIdResponse = contentMaterialApiService.listMaterialIdBySearch(pageQDTO);
            if (!listIdResponse.isSuccess() || CollectionUtils.isEmpty(listIdResponse.getResult())) {
                return RestResponse.successResult(new Page<>());
            }
            List<Long> materialIdList = listIdResponse.getResult();
            Page<ContentMaterialConvsVO> dataPage = materialDataAdaptor.queryCreativeConvs(enterpriseId, materialIdList, auditMaterialQO.getBasePageInfo());
            if (dataPage == null || CollectionUtils.isEmpty(dataPage.getResult())) {
                return RestResponse.successResult(new Page<>());
            }
            List<ContentMaterialConvsVO> result = dataPage.getResult();
            map = result.stream().collect(Collectors.toMap(ContentMaterialConvsVO::getContentMaterialId, t -> t));
            filterMaterialIdList = result.stream().map(ContentMaterialConvsVO::getContentMaterialId).collect(Collectors.toList());
            totalCount = dataPage.getTotalCount();
        }
        pageQDTO.setContentMaterialIdList(filterMaterialIdList);
        ServiceResponse<Page<ContentMaterialDTO>> response = contentMaterialApiService.pageMaterial(pageQDTO, auditMaterialQO.getBasePageInfo());
        if (!response.isSuccess() || CollectionUtils.isEmpty(response.getResult().getResult())) {
            return RestResponse.successResult(new Page<>());
        }
        Page<ContentMaterialDTO> page = response.getResult();
        Page<ContentMaterialVO> result = new Page<>();
        List<ContentMaterialVO> list = EntityUtil.changeEntityListByJSON(ContentMaterialVO.class, response.getResult().getResult());
        if (totalCount == null) {
            totalCount = page.getTotalCount();
        }
        result.setTotalCount(totalCount);
        result.setResult(list);
        result.setCurrentPage(page.getCurrentPage());
        result.setPageSize(page.getPageSize());
        if (!convs) {
            List<Long> materialIdList = list.stream().map(ContentMaterialVO::getContentMaterialId).collect(Collectors.toList());
            BasePageInfo pageInfo = new BasePageInfo();
            pageInfo.setPageNum(1);
            pageInfo.setPageSize(materialIdList.size());
            map = materialDataAdaptor.queryCreativeConvsMap(enterpriseId, materialIdList, pageInfo);
        }
        //列表转化数据
        if (CollectionUtils.isNotEmpty(list)) {
            for (ContentMaterialVO materialVO : list) {
                Long contentMaterialId = materialVO.getContentMaterialId();
                ContentMaterialConvsVO materialConvsVO = map.get(contentMaterialId);
                materialVO.setConvs(materialConvsVO);
            }
        }
        return RestResponse.successResult(result);
    }

    /**
     * 数据概览
     * @param auditMaterialQO  qo
     * @return
     */
    @ResponseBody
    @RequestMapping("/material-data")
    public RestResponse<ContentMaterialDataVO> auditMaterialData(@RequestBody ContentAuditMaterialQO auditMaterialQO) {
        ContentMaterialPageQDTO pageQDTO = new ContentMaterialPageQDTO();
        String enterpriseId = auditMaterialQO.getEnterpriseId();
        pageQDTO.setEnterpriseId(enterpriseId);
        pageQDTO.setStoreId(auditMaterialQO.getStoreId());
        pageQDTO.setClerkId(auditMaterialQO.getClerkId());
        pageQDTO.setQueryScene(MaterialSearchSceneEnum.HAOBAN_AUDIT.value);
        ServiceResponse<Long> response = contentMaterialApiService.countMaterialBySearch(pageQDTO);
        pageQDTO.setAuditStatus(MaterialAuditEnum.AUDIT.code);
        ServiceResponse<Long> auditResponse = contentMaterialApiService.countMaterialBySearch(pageQDTO);
        if (!response.isSuccess() || !auditResponse.isSuccess()) {
            return RestResponse.failure("-1", "请求失败");
        }
        ContentMaterialDataVO materialDataVO = new ContentMaterialDataVO();
        materialDataVO.setAuditCount(auditResponse.getResult());
        materialDataVO.setCreateCount(response.getResult());
        //转化数据
        ServiceResponse<List<Long>> idListResponse = contentMaterialApiService.listMaterialIdBySearch(pageQDTO);
        if (!idListResponse.isSuccess()) {
            return RestResponse.failure("-1", "请求失败");
        }
        ContentMaterialConvsVO materialConvsVO = materialDataAdaptor.queryCreativeConvsOverview(enterpriseId, idListResponse.getResult());
        materialDataVO.setConvs(materialConvsVO);
        return RestResponse.successResult(materialDataVO);
    }

}
