package com.yizhi.application.marketing.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.accountUtil.AuthorizeQueryAccount;
import com.yizhi.core.application.enums.InternationalEnums;
import com.yizhi.application.tools.PageTools;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.course.application.feign.MarketingCourseClient;
import com.yizhi.course.application.vo.*;
import com.yizhi.course.application.vo.domain.CourseEntityVo;
import com.yizhi.system.application.system.remote.AccountClient;
import com.yizhi.system.application.vo.AccountVO;
import com.yizhi.system.application.vo.OrgVO;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.domain.Response;
import com.yizhi.util.application.page.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

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

/**
 * @Author: XieHaijun
 * @Description:
 * @Date: Created in 19:52 2018/4/9
 * @Modified By
 */
@Api(tags = "营销课程接口")
@RestController
@RequestMapping("/manage/marketing/course")
public class MarketingCourseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(MarketingCourseController.class);

    @Autowired
    private MarketingCourseClient marketingCourseClient;

    @Autowired
    private AccountClient accountClient;

    @Autowired
    private AuthorizeQueryAccount queryAccount;

    @ApiOperation(value = "新增营销课程", response = MarketingCourseVo.class)
    @PostMapping("/save")
    public Response<MarketingCourseVo> save(@ApiParam(name = "marketingCourseVo", value = "营销课程vo")
                                      @RequestBody MarketingCourseVo marketingCourseVo){
        try {
            return Response.ok(marketingCourseClient.save(marketingCourseVo));
        } catch (Exception e) {
            LOGGER.info(JSON.toJSONString(e));
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation(value = "更新营销课程")
    @PostMapping("/update")
    public Response<Boolean> update(@ApiParam(name = "marketingCourseVo", value = "营销课程vo")
                                        @RequestBody MarketingCourseVo marketingCourseVo){
        Long id = marketingCourseVo.getId();
        if(id == null || id == 0L){
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(), InternationalEnums.MARKETINGCOURSECONTROLLER9.getCode());
        }
        if(StringUtils.isEmpty(marketingCourseVo.getName())){
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(), InternationalEnums.MARKETINGCOURSECONTROLLER10.getCode());
        }
        RequestContext rc = ContextHolder.get();
        boolean extisChapte = true;
        if(Integer.valueOf(1).equals(marketingCourseVo.getShelves()) && CollectionUtils.isEmpty(marketingCourseVo.getChapters())){ // 判断上架的时候检查
            extisChapte = marketingCourseClient.extisChapte(id);
            if(!extisChapte){
                marketingCourseVo.setShelves(0); // 没有关联强制设在成草稿
            }
        }
        //MarketingCourseVo marketingCourseVo1 = marketingCourseClient.getByName(marketingCourseVo.getName(),rc.getSiteId(),marketingCourseVo.getId());
        boolean extisCode = false;
        MarketingCourseVo o1 = marketingCourseClient.existByCode(marketingCourseVo.getCode(),rc.getSiteId(),marketingCourseVo.getId());
        if(o1 != null && ! StringUtils.isEmpty(o1.getCode())){
            extisCode = true;
            marketingCourseVo.setShelves(0); // 存在code强制设在成草稿
        }

        if(!extisChapte){
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(), InternationalEnums.MARKETINGCOURSECONTROLLER2.getCode());
        }
        if(extisCode){
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(), InternationalEnums.MARKETINGCOURSECONTROLLER3.getCode());
        }

        marketingCourseClient.update(marketingCourseVo);

        return Response.ok();
    }

    @ApiOperation(value = "批量删除营销课程")
    @PostMapping("/delete")
    public Response<Boolean> delete(@ApiParam(name = "courseIds", value = "要删除的课程id，多个用,号隔开")
                              @RequestBody List<Long> courseIds){
        if(CollectionUtils.isEmpty(courseIds)){
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(), InternationalEnums.MARKETINGCOURSECONTROLLER1.getCode());
        }
        String courseIdsStr = courseIds.stream().map(obj-> obj.toString()).collect(Collectors.joining(","));
        return Response.ok(marketingCourseClient.delete(courseIdsStr));
    }

    @ApiOperation(value = "课程上架")
    @GetMapping("/up")
    public Response<Boolean> up(@ApiParam(name = "id", value = "课程ID" ,required = true)
                          @RequestParam(value = "id") Long id, @RequestParam(value = "code") String code){
        if(id == null){
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(), InternationalEnums.MARKETINGCOURSECONTROLLER4.getCode());
        }
        boolean extisChapte = marketingCourseClient.extisChapte(id);
        if(!extisChapte){
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(), InternationalEnums.MARKETINGCOURSECONTROLLER2.getCode());
        }
        RequestContext rc = ContextHolder.get();
        MarketingCourseVo o1 = marketingCourseClient.existByCode(code,rc.getSiteId(),id);
        if(o1 != null && ! StringUtils.isEmpty(o1.getCode())){
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(), InternationalEnums.MARKETINGCOURSECONTROLLER3.getCode());
        }
        return Response.ok(marketingCourseClient.up(id));
    }

    @ApiOperation(value = "课程下架")
    @GetMapping("/down")
    public Response<Boolean> down(@ApiParam(name = "id", value = "课程ID" ,required = true)
                            @RequestParam(value = "id") Long id){
        if(id == null){
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(), InternationalEnums.MARKETINGCOURSECONTROLLER4.getCode());
        }
        return Response.ok(marketingCourseClient.down(id));
    }

    @ApiOperation(value = "课程列表", response = CourseEntityVo.class)
    @PostMapping("/list")
    public Response<CourseEntityVo> list(@ApiParam(name = "queryCourseRequest", value = "可以指定查询条件，不指定查询全部的营销课程" )
                                 @RequestBody QueryCourseRequest queryCourseRequest){
        Page<CourseEntityVo> retPage = marketingCourseClient.list(queryCourseRequest);
        return Response.ok(PageTools.split(retPage));
    }

    @ApiOperation(value = "查看课程", response = MarketingCourseVo.class)
    @GetMapping("/view")
    public Response<MarketingCourseVo> view(@ApiParam(name = "courseId", value = "课程id", required=true) @RequestParam Long courseId,
                                  @ApiParam(name = "shareId", value = "分享id") @RequestParam(required = false) Long shareId
                                           ){

        LOGGER.info("课程id = {},分享id = {}",courseId,shareId);

        MarketingCourseVo vo = marketingCourseClient.view(courseId,null,
                ContextHolder.get().getAccountId(),null, true, "" );
        if(vo==null){
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),InternationalEnums.MARKETINGCOURSECONTROLLER5.getCode());
        }
        List<CourseAccountVO> ranges = vo.getAccountIds();
        if (!CollectionUtils.isEmpty(ranges)) {
            List<Long> accountIds = new ArrayList<>(ranges.size());
            List<Long> orgIds = new ArrayList<>(ranges.size());
            ranges.forEach(a -> {
                if (a.getType().equals(1)) {
                    orgIds.add(a.getRelationId());
                } else {
                    accountIds.add(a.getRelationId());
                }
            });
            Map<Long, AccountVO> accountMap = queryAccount.queryAccountByIds(accountIds);
            Map<Long, OrgVO> orgMap = queryAccount.queryOrgByIds(orgIds);
            ranges.forEach(a -> {
                if (null != accountMap) {
                    AccountVO accountVO = accountMap.get(a.getRelationId());
                    if (null != accountVO && a.getType().equals(2)) {
                        a.setWorkNum(accountVO.getWorkNum());
                        a.setFullName(accountVO.getFullName());
                        a.setName(accountVO.getName());
                    }
                }
                if (null != orgMap) {
                    OrgVO orgVO = orgMap.get(a.getRelationId());
                    if (null != orgVO && a.getType().equals(1)) {
                        a.setName(orgVO.getName());
                    }
                }
            });
        }
        return Response.ok(vo);
    }

    @ApiOperation(value = "分享课程", response = CourseShareVo.class)
    @PostMapping("/share")
    public Response<CourseShareVo> share(@ApiParam(name = "vo", value = "课程分享vo") @RequestBody CourseShareVo vo){
        if(vo.getCourseId()==null){
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(), InternationalEnums.MARKETINGCOURSECONTROLLER6.getCode());
        }
        if(vo.getAccountId()==null){
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(), InternationalEnums.MARKETINGCOURSECONTROLLER7.getCode());
        }
        // 查询用户信息
        AccountVO avo = accountClient.findById(vo.getAccountId());
        vo.setName(avo.getName());
        vo.setFullName(avo.getFullName());
        // 用户手机号
        vo.setTel(avo.getMobile());
        return Response.ok(marketingCourseClient.share(vo));
    }

    @ApiOperation(value = "分享被浏览的停留时间")
    @GetMapping("/activity")
    public Response<Boolean> activity(@ApiParam(name = "browseRecordId", value = "分享课程被浏览的记录id" ,required = true)
                                          @RequestParam Long browseRecordId ){
        if(browseRecordId == null){
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(), InternationalEnums.MARKETINGCOURSECONTROLLER8.getCode());
        }
        return Response.ok(marketingCourseClient.activity(browseRecordId));
    }

    @ApiOperation(value = "查询我分享的课程信息", response = CourseShareVo.class)
    @GetMapping("/share/list")
    public Response<CourseShareVo> shareList(@ApiParam(name = "pageNo", value = "页码" ,required = true)
            @RequestParam int pageNo
            ,@ApiParam(name = "pageSize", value = "每页条数" ,required = false)
                                             @RequestParam(required = false) Integer pageSize
            ,@RequestParam(value = "searchFiled" ,required = false) String searchFiled){
        PageInfo<CourseShareVo> retPage = marketingCourseClient.shareList(pageNo, pageSize,searchFiled);
        // Response<T> ok(Pair<List<T>, 修改成Response<T> ok(Pair<T,
        return Response.ok(PageTools.convert(retPage));
    }

    @ApiOperation(value = "查询我分享的课程被浏览的记录", response = BrowseRecordsVo.class)
    @GetMapping("/share/browse/records")
    public Response<BrowseRecordsVo> shareBrowseRecords(
            @ApiParam(name = "shareId", value = "分享ID" ,required = true)
                                                                @RequestParam Long shareId,
            @ApiParam(name = "pageNo", value = "页码" ,required = true)
            @RequestParam int pageNo
            ,@ApiParam(name = "pageSize", value = "每页条数" ,required = false)
            @RequestParam(required = false) Integer pageSize
            ,@RequestParam(value = "searchFiled" ,required = false) String searchFiled){
        Page<BrowseRecordsVo> retPage = marketingCourseClient.shareBrowseRecords(shareId,pageNo, pageSize,searchFiled);
        return Response.ok(PageTools.split(retPage));
    }
}
