package com.yunzhi.marketing.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunzhi.marketing.base.BaseController;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.common.CommConstant;
import com.yunzhi.marketing.common.StringUtils;
import com.yunzhi.marketing.common.WorkWxUtils;
import com.yunzhi.marketing.entity.ExtendContent;
import com.yunzhi.marketing.entity.TaLiveActivity;
import com.yunzhi.marketing.po.LiveAndVideoVO;
import com.yunzhi.marketing.reportCustomerAop.ReportCustomer;
import com.yunzhi.marketing.service.IExtendContentService;
import com.yunzhi.marketing.service.ITaLiveActivityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-02-20
 */
@RestController
@RequestMapping("/api")
@Api(value = "直播活动", tags = "xlk-直播活动")
public class TaLiveActivityController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(TaLiveActivityController.class);

    @Autowired
    public ITaLiveActivityService iTaLiveActivityService;

    @Autowired
    public IExtendContentService iExtendContentService;

    @Autowired
    public WorkWxUtils workWxUtils;

    /**
     * 分页查询列表
     *
     * @param pageNum
     * @param pageSize
     * @param liveActivityTitle 直播活动标题
     * @param cityId            所属城市
     * @param buildingId        所属楼盘
     * @param
     * @param status            状态
     * @param source            查询来源，1:直播等活动，2:开屏广告
     * @param request
     * @return
     */
    @RequestMapping(value = "/admin/taLiveActivity", method = RequestMethod.GET)
    public ResponseBean taLiveActivityList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                           String liveActivityTitle,
                                           String cityId,
                                           String buildingId,
                                           Integer status,
                                           @RequestParam(value = "source", defaultValue = "1") Integer source,
                                           HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            IPage<TaLiveActivity> result = iTaLiveActivityService.listLiveActivityByCondition(pageNum, pageSize, getOrgId(request),
                    liveActivityTitle, cityId, buildingId, status, getTaPersonBuildingListByUserId(request), getUserId(request), source, getInstitutionIds(request));
            responseBean.addSuccess(result);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taLiveActivityList -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     *
     * @param taLiveActivity 实体对象
     * @return
     */
    @RequestMapping(value = "/admin/taLiveActivity", method = RequestMethod.POST)
    public ResponseBean taLiveActivityAdd(@RequestBody TaLiveActivity taLiveActivity, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            Integer orgId = getOrgId(request);
            Integer userId = getUserId(request);
            taLiveActivity.setOrgId(orgId);
            taLiveActivity.setCreateUser(userId.toString());
            taLiveActivity.setUpdateUser(userId.toString());
            taLiveActivity.setInstitutionId(getInstitutionId(taLiveActivity.getBuildingId()));
            responseBean = iTaLiveActivityService.taLiveActivityAdd(taLiveActivity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taLiveActivityAdd -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     *
     * @param id 实体ID
     */
    @ResponseBody
    @RequestMapping(value = "/admin/delTaLiveActivity", method = RequestMethod.PUT)
    public ResponseBean taLiveActivityDelete(@RequestBody List<TaLiveActivity> taLiveActivity, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            List<Integer> liveActivityIds = new ArrayList<>();
            for (TaLiveActivity activity : taLiveActivity) {
                liveActivityIds.add(activity.getLiveActivityId());
            }
            QueryWrapper<ExtendContent> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_id", getOrgId(request));
            queryWrapper.eq("content_type", CommConstant.LIVE);
            queryWrapper.in("target_id", liveActivityIds);
            List<ExtendContent> list = iExtendContentService.list(queryWrapper);
            list.forEach(e -> {
                e.setStatus(CommConstant.NOT_PUBLISH);
            });
            if (list.size() > 0) {
                iExtendContentService.updateBatchById(list);
            }

            responseBean = iTaLiveActivityService.delLiveActivityList(getOrgId(request), taLiveActivity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taLiveActivityDelete -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     *
     * @param id             实体ID
     * @param taLiveActivity 实体对象
     * @return
     */
    @RequestMapping(value = "/admin/taLiveActivity/{id}", method = RequestMethod.PUT)
    public ResponseBean taLiveActivityUpdate(@PathVariable Integer id,
                                             @RequestBody TaLiveActivity taLiveActivity, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            taLiveActivity.setLiveActivityId(id);
            taLiveActivity.setUpdateUser(getUserId(request).toString());
            QueryWrapper<ExtendContent> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_id", getOrgId(request));
            queryWrapper.eq("content_type", CommConstant.LIVE);
            queryWrapper.eq("target_id", taLiveActivity.getLiveActivityId());
            List<ExtendContent> list = iExtendContentService.list(queryWrapper);
            if (CommConstant.NOT_PUBLISH.equals(taLiveActivity.getStatus())) {
                list.forEach(e -> {
                    e.setStatus(CommConstant.NOT_PUBLISH);
                });
            }
            if (list.size() > 0) {
                iExtendContentService.updateBatchById(list);
            }

            if (!StringUtils.isEmpty(taLiveActivity.getLiveRoomParam())) {
                taLiveActivity.setLiveAppPath(taLiveActivity.getLiveRoomParam().replace(".html", ""));
            }

            taLiveActivity.setUpdateDate(LocalDateTime.now());
            taLiveActivity.setUpdateUser(getUserId(request).toString());
            if (iTaLiveActivityService.updateById(taLiveActivity)) {
                responseBean.addSuccess(taLiveActivity);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taLiveActivityUpdate -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     *
     * @param id             实体ID
     * @return
     */
    @RequestMapping(value = "/admin/publish/live/{id}", method = RequestMethod.PUT)
    public ResponseBean taLiveActivityUpdate(@PathVariable Integer id,HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            TaLiveActivity taLiveActivity = iTaLiveActivityService.getById(id);
            if (CommConstant.NOT_PUBLISH.equals(taLiveActivity.getStatus())) {
                taLiveActivity.setStatus(CommConstant.IS_PUBLISH);
            }else if (CommConstant.IS_PUBLISH.equals(taLiveActivity.getStatus())) {
                taLiveActivity.setStatus(CommConstant.NOT_PUBLISH);
            }
            taLiveActivity.setUpdateDate(LocalDateTime.now());
            taLiveActivity.setUpdateUser(getUserId(request).toString());
            iTaLiveActivityService.updateById(taLiveActivity);
            responseBean.addSuccess(taLiveActivity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taLiveActivityUpdate -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     *
     * @param id 实体ID
     */
    @RequestMapping(value = "/admin/taLiveActivity/{id}", method = RequestMethod.GET)
    public ResponseBean taLiveActivityGet(@PathVariable Integer id) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iTaLiveActivityService.getDetailById(id));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taLiveActivityDelete -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 访问量自增
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/wx/addVisitNum", method = RequestMethod.PUT)
    public ResponseBean addVisitNum(@RequestParam("id") String id) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaLiveActivityService.addVisitNum(id);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("addVisitNum -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 获取直播详情
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/wx/taLiveActivity/{id}", method = RequestMethod.GET)
    @ReportCustomer(type = "live")
    public ResponseBean getLiveActivityDetailById(@PathVariable("id") String id,
                                                  @RequestParam(value = "qrCodeId", required = false) String qrCodeId,
                                                  @RequestParam(value = "channelId", required = false) String channelId,
                                                  @RequestParam(value = "sceneId", required = false) String sceneId,
                                                  HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaLiveActivityService.getLiveActivityDetailById(id, getOrgId(request));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("getLiveActivityDetailById -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 分页查询列表
     *
     * @param pageNum
     * @param pageSize
     * @param liveActivityTitle 直播活动标题
     * @param cityId            所属城市
     * @param buildingId        所属楼盘
     * @param status            状态
     * @param request
     * @return
     */
    @ApiOperation(value = "wx-视频直播列表", notes = "admin-视频直播列表")
    @RequestMapping(value = "/wx/taLiveActivity", method = RequestMethod.GET)
    public ResponseBean taLiveActivityListForMiniApp(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                     @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                     @RequestParam(value = "cityId", required = false) Integer cityId,
                                                     @RequestParam(value = "buildingId", required = false) String buildingId,
                                                     @RequestParam(value = "name", required = false) String name,
                                                     @RequestParam(value = "process", required = false) Integer process,
                                                     @RequestParam(value = "newHouse", required = false) Boolean newHouse,
                                                     HttpServletRequest request) {
        if (process != null) {
            return getPureLiveActivity(pageNum, pageSize, cityId, buildingId, name, process, request);
        }

        ResponseBean responseBean = new ResponseBean();
        try {
            Integer orgId = getOrgId(request);
            IPage<LiveAndVideoVO> pg = new Page<>(pageNum, pageSize);
            IPage<LiveAndVideoVO> result = iTaLiveActivityService.getWxLiveActivityAndVideo(pg, orgId, cityId, buildingId, name, newHouse);
            responseBean.addSuccess(result);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taLiveActivityListForMiniApp -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    private ResponseBean getPureLiveActivity(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                             @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                             @RequestParam(value = "cityId", required = false) Integer cityId,
                                             @RequestParam(value = "buildingId", required = false) String buildingId,
                                             @RequestParam(value = "name", required = false) String name,
                                             @RequestParam(value = "process", required = false) Integer process,
                                             HttpServletRequest request) {

        Integer orgId = getOrgId(request);
        IPage<TaLiveActivity> pg = new Page<>(pageNum, pageSize);
        return ResponseBean.success(iTaLiveActivityService.getWxPureLiveActivityList(pg, orgId, cityId, buildingId, name, process));
    }

    @GetMapping("/wx/taLiveActivity/work/livingCode")
    public ResponseBean getWorkLivingCode(@RequestParam("livingId") String livingId,
                                          HttpServletRequest request) {
        String openid = getOpenId(request);
        try {
            JSONObject liveInfo = workWxUtils.getLivingInfoById(livingId);
            if (null == liveInfo) {
                return ResponseBean.error("未找到直播房间", ResponseBean.ERROR_UNAVAILABLE);
            }

            String livingCode = workWxUtils.getLivingCode(livingId, openid);
            liveInfo.put("livingCode", livingCode);

            return ResponseBean.success(liveInfo);
        } catch (Exception e) {
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    @GetMapping("/admin/taLiveActivity/work/rooms")
    public ResponseBean getWorkLivingRooms(@RequestParam("phone") String phone,
                                          HttpServletRequest request) {
        try {
            String userid = workWxUtils.getUserByPhone(phone);
            return ResponseBean.success(workWxUtils.getLivingRoomsOfUser(userid));
        } catch (WxErrorException e) {
            return ResponseBean.error(e.getError().getErrorMsg(), ResponseBean.ERROR_UNAVAILABLE);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }
    }
}
