package com.yizhi.application.marketing.controller;

import com.baomidou.mybatisplus.plugins.Page;
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.CardConfigClient;
import com.yizhi.course.application.feign.MarketingCourseClient;
import com.yizhi.course.application.vo.*;
import com.yizhi.course.application.vo.domain.CourseEntityVo;
import com.yizhi.live.application.feign.LiveActivityClient;
import com.yizhi.system.application.feign.SmsSendRecordClient;
import com.yizhi.system.application.vo.SmsSendVo;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

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

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

    @Autowired
    private MarketingCourseClient marketingCourseClient;

    @Autowired
    private CardConfigClient cardConfigClient;

    @Autowired
    private SmsSendRecordClient smsSendRecordClient;

    @Autowired
    private LiveActivityClient liveActivityClient;

    @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("/public/view")
    public Response<MarketingCourseVo> view(
            @ApiParam(name = "courseId", value = "课程id", required=true) @RequestParam Long courseId,
            @ApiParam(name = "shareId", required = false ,value = "分享id(微信固定传-1)") @RequestParam(required = false) Long shareId,
            @ApiParam(name = "accountId", required = false, value = "分享用户id") @RequestParam(required = false) Long accountId,
            @ApiParam(name = "childShareOpenId", required = false, value = "分享用户id") @RequestParam(required = false) String childShareOpenId,
            @ApiParam(name = "openId", required = false ,value = "分享查看人的微信id") @RequestParam(required = false) String openId){
        RequestContext rc = ContextHolder.get();
        // 企业号微信免登录，查看课程，如果没有分享用户id（accountId）则取登陆用户的上下文账号
        if(Objects.isNull(accountId)){
            accountId = rc.getAccountId();
        }
        if(accountId==null || accountId.longValue()==0){
            return Response.fail();
        }
        MarketingCourseVo retData = marketingCourseClient.view(courseId,shareId,accountId,openId,false,childShareOpenId);
        List<ChapterVo> chapterVoList = retData.getChapters();
        /*if(! CollectionUtils.isEmpty(chapterVoList) &&
                chapterVoList.stream().filter(itemObj -> Integer.valueOf(9).equals(itemObj.getMaterialType())).count()>0){
            liveActivityClient.g
        }*/
        Boolean cardShow = retData.getCardShow();
        if(cardShow == null){
            cardShow = Boolean.FALSE;
            retData.setCardShow(cardShow);
        }
        if(cardShow.booleanValue()){ // 是否需要显示名片信息
            CardConfigVO cardConfigVO = cardConfigClient.getBySiteId(rc.getSiteId());
            if(cardConfigVO != null){
                CardInfoVO cardInfoVO = new CardInfoVO();
                AccountVO accountVO = retData.getAccountInfo();
                cardInfoVO.setCardTopDisplay(cardConfigVO.getCardTopDisplay());
                cardInfoVO.setTopBarBgcolor(cardConfigVO.getTopBarBgcolor());
                cardInfoVO.setTopBarText(cardConfigVO.getTopBarText());
                Integer topBarButton = cardConfigVO.getTopBarButton();
                cardInfoVO.setTopBarButton(topBarButton==null?"0":topBarButton.toString());

                cardInfoVO.setCardBodyDisplay(cardConfigVO.getCardBodyDisplay());
                cardInfoVO.setBodyBgimg(cardConfigVO.getBodyBgimg());
                cardInfoVO.setBodyField1(accountVO.getFullName());
                cardInfoVO.setBodyField2(getFieldValue(accountVO, cardConfigVO.getBodyField2()));
                cardInfoVO.setBodyField3(getFieldValue(accountVO, cardConfigVO.getBodyField3()));
                cardInfoVO.setBodyField4(getFieldValue(accountVO, cardConfigVO.getBodyField4()));
                Integer bodyField5 = cardConfigVO.getBodyField5();
                cardInfoVO.setBodyField5(bodyField5 == 9 ? accountVO.getDescription() : getFieldValue(accountVO, bodyField5));

                cardInfoVO.setCardFootDisplay(cardConfigVO.getCardFootDisplay());

                // 设置电话号码信息
                cardInfoVO.setMobile(accountVO.getMobile());
                // 邮箱
                cardInfoVO.setEmail(accountVO.getEmail());
                // 头像
                cardInfoVO.setHeadPortrait(accountVO.getHeadPortrait());
                retData.setCardInfo(cardInfoVO);
            }
        }
        return Response.ok(retData);
    }

    // 获取字段设置的值
    private static String getFieldValue(AccountVO accountVO, Integer fieldConfig) {
        int field = fieldConfig==null?0:fieldConfig.byteValue();
        String ret = null;
        switch (field){
            case 0:
                ret = "";
                break;
            case 1:
                ret = accountVO.getPosition();
                break;
            case 2:
                ret = accountVO.getOrgName();
                break;
            case 3:
                ret = accountVO.getCompanyName();
                break;
            case 4:
                ret = accountVO.getMobile();
                break;
            case 5:
                ret = accountVO.getEmail();
                break;
            case 6:
                ret = accountVO.getRemarkFirst();
                break;
            case 7:
                ret = accountVO.getRemarkSecond();
                break;
            case 8:
                ret = accountVO.getRemarkThird();
                break;
            default:
                ret = "";

        }
        return ret;
    }

    @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(), "分享的课程id不能为空！");
        }
        if(vo.getAccountId()==null){
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(), "分享课程的用户id不能为空！");
        }
        return Response.ok(marketingCourseClient.share(vo));
    }

    @ApiOperation(value = "分享被浏览的停留时间")
    @GetMapping("/public/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(), "分享课程被浏览的记录id不能为空！");
        }
        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> pageInfo = marketingCourseClient.shareList(pageNo, pageSize, searchFiled);
        // Response<T> ok(Pair<List<T>, 修改成Response<T> ok(Pair<T,
        return Response.ok(PageTools.convert(pageInfo));
    }

    @ApiOperation(value = "查询我分享的课程被浏览的记录", response = BrowseRecordsVo.class)
    @GetMapping("/share/browse/records")
    public Response<BrowseRecordsVo> shareBrowseRecords(
            @ApiParam(name = "courseId", value = "课程ID" ,required = true)
                                                                @RequestParam Long courseId,
            @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(courseId,pageNo, pageSize,searchFiled);
        return Response.ok(PageTools.split(retPage));
    }

    @ApiOperation(value = "查询我分享的课程被多少人传播汇总", response = BrowseRecordsVo.class)
    @GetMapping("/share/spread/list")
    public Response<CourseShareVo> shareSpreadList(
            @ApiParam(name = "courseId", value = "课程ID" ,required = true) @RequestParam Long courseId,
            @ApiParam(name = "pageNo", value = "页码" ,required = true) @RequestParam int pageNo
            ,@ApiParam(name = "pageSize", value = "每页条数") @RequestParam(required = false) Integer pageSize
            ,@ApiParam(name = "firstShareId", value = "第一级分享人id，在查询第一级下的推广人时候传入") @RequestParam(value = "firstShareId" ,required = false) String firstShareId){
        PageInfo<CourseShareVo> retPage = marketingCourseClient.shareSpreadList(courseId,pageNo, pageSize,firstShareId);
        //return Response.ok(PageTools.split(retPage));
        return Response.ok(PageTools.convert(retPage));
    }

    @ApiOperation(value = "根据openId查询微信用户信息", response = WechatInfoVO.class)
    @GetMapping("/wechat/openid/get")
    public Response<WechatInfoVO> wachatOpenIdGet(
            @ApiParam(name = "openId", value = "微信openId" ,required = true) @RequestParam String openId){
        WechatInfoVO retData = marketingCourseClient.wachatOpenIdGet(openId);
        return Response.ok(retData);
    }

    @ApiOperation(value = "根据微信openId和手机号发送验证码短信")
    @GetMapping("/public/tel/authorize/sms/send")
    public Response<Boolean> sendGSM(@ApiParam(name = "openId", value = "微信openId" ,required = true) @RequestParam String openId,
                                     @ApiParam(name = "tel", value = "手机号" ,required = true) @RequestParam String tel){
        //int captcha = new Random().ints(1, 100000, 999999).findFirst().getAsInt();

        // 判断openId 是否在平台存在，手机号码是否使用过,短信发送的前置检查
        int retStatus = marketingCourseClient.smsSendPreCheck(openId, tel);
        switch (retStatus){
            case 1:
                return Response.fail(ReturnCode.BIZ_FAIL.getCode(),"未通过微信授权");
                //return Response.fail(Constants.COURSE_MSG_COURSE_NOT_WECHAT_CERTIFICATION.getCode().toString(),Constants.COURSE_MSG_COURSE_NOT_WECHAT_CERTIFICATION.getName());
            case 2:
                return Response.fail(ReturnCode.BIZ_FAIL.getCode(),"该手机号已经被使用过");
                //return Response.fail(Constants.COURSE_MSG_COURSE_TEL_USED.getCode().toString(),Constants.COURSE_MSG_COURSE_TEL_USED.getName());
            case 3:
                return Response.fail(ReturnCode.BIZ_FAIL.getCode(),"发送消息太频繁");
                //return Response.fail(Constants.COURSE_MSG_COURSE_SMS_FREQUENTLY_SEND.getCode().toString(),Constants.COURSE_MSG_COURSE_SMS_FREQUENTLY_SEND.getName());
        }
        // 开始发送短信
        SmsSendVo smsSendVo = new SmsSendVo();
        smsSendVo.setTel(tel);
        Map<String, Object> smsSendStatus = smsSendRecordClient.simpleSmsSend(smsSendVo);
        // 发送过程如果有异常直接抛出
        long success = smsSendStatus.keySet().stream().filter(keys -> smsSendRecordClient.SUCCESS_CODE.equals(keys)).count();
        if(success == 0){
            Set<String> kes = smsSendStatus.keySet();
            String key = kes.toArray()[0].toString();
            return Response.fail(key, smsSendStatus.get(key).toString());
        }
        // 保存短信发送的验证码，以便后面做短信验证处理
        String code = smsSendStatus.get( smsSendRecordClient.SUCCESS_CODE).toString();
        Boolean addStatus = marketingCourseClient.saveCaptcha(openId, tel, code);
        return Response.ok(addStatus);
    }

    @ApiOperation(value = "根据微信openId和手机号以及发送的短信验证码 检查验证码是否在有效的时间内")
    @GetMapping("/public/sms/captcha/validate")
    public Response sendGSM(@ApiParam(name = "openId", value = "微信openId" ,required = true) @RequestParam String openId,
                            @ApiParam(name = "tel", value = "手机号" ,required = true) @RequestParam String tel,
                            @ApiParam(name = "captcha", value = "验证" ,required = true) @RequestParam String captcha){
        int ret = marketingCourseClient.smsCaptchaValidate(openId, tel, captcha);
        switch (ret){
            case 1:
                return Response.fail(ReturnCode.BIZ_FAIL.getCode(),"手机号被多次发送授权验证码");
                //return Response.fail(Constants.COURSE_MSG_COURSE_TEL_SMS_MULTIPLE_SEND.getCode().toString(),Constants.COURSE_MSG_COURSE_TEL_SMS_MULTIPLE_SEND.getName());
            case 2:
                return Response.fail(ReturnCode.BIZ_FAIL.getCode(),"验证码不存在");
                //return Response.fail(Constants.COURSE_MSG_COURSE_CAPTCHA_NON_EXISTENT.getCode().toString(),Constants.COURSE_MSG_COURSE_CAPTCHA_NON_EXISTENT.getName());
            case 3:
                return Response.fail(ReturnCode.BIZ_FAIL.getCode(),"验证码过期");
                //return Response.fail(Constants.COURSE_MSG_COURSE_CAPTCHA_EXPIRED.getCode().toString(),Constants.COURSE_MSG_COURSE_CAPTCHA_EXPIRED.getName());
            default:
                return Response.ok();
        }
    }

}
