package com.jpsoft.shinestar.modules.mobile.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.AliyunLiveConfig;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.config.YsConfig;
import com.jpsoft.shinestar.modules.base.dto.CashierDTO;
import com.jpsoft.shinestar.modules.base.entity.CameraInfo;
import com.jpsoft.shinestar.modules.base.entity.GoodsInfo;
import com.jpsoft.shinestar.modules.base.entity.PersonInfo;
import com.jpsoft.shinestar.modules.base.entity.PersonPopedom;
import com.jpsoft.shinestar.modules.base.service.CameraInfoService;
import com.jpsoft.shinestar.modules.base.service.GoodsInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonPopedomService;
import com.jpsoft.shinestar.modules.business.entity.CameraPurchaser;
import com.jpsoft.shinestar.modules.business.service.CameraPurchaserService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.AliyunLiveUtil;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.common.utils.YsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/mobile/cameraApi")
@Api(description = "公开课接口")
public class CameraApiController {

    @Autowired
    private YsUtil ysUtil;

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private CameraPurchaserService cameraPurchaserService;

    @Autowired
    private CameraInfoService cameraInfoService;

    @Autowired
    private PersonPopedomService personPopedomService;

    @Autowired
    private YsConfig ysConfig;

    @Autowired
    private AliyunLiveConfig aliyunLiveConfig;

    @Autowired
    private GoodsInfoService goodsInfoService;

    /**
     * 判断当前人是否 可以购买成功 时间是否到期
     *
     * @return
     */
    public boolean exist(CameraPurchaser purchaser) {

        if (purchaser != null) {
            if (purchaser.getEndTime().getTime() > new Date().getTime()) {
                return true;
            }
        }
        return false;
    }

    @PostMapping("cameraList")
    @ApiOperation(value = "家长直播列表集合")
    public MessageResult<Map> cameraList(String currentId, String token, @RequestAttribute String subject) {
        //是否购买，
        //购买时长
        //视频

        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));
            Long personId = personInfo.getId();
            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());

            if (StringUtils.isNotBlank(personPopedom.getRelationPopedom())) {
                PersonPopedom personPopedom1 = personPopedomService.get(personPopedom.getRelationPopedom());
                personId = personPopedom1.getPersonId();
            }

            CameraPurchaser purchaser = cameraPurchaserService.getByPersonId(personId);
            Map<String, Object> data = new HashMap<>();

            if (exist(purchaser)) {
                //
                List<CameraInfo> cameraInfos = cameraInfoService.findByPersonId(personId);
                data.put("list", cameraInfos);

                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = formatter.format(purchaser.getEndTime());

                data.put("endtime", dateString);
                data.put("buystatus", true);
            } else {
                data.put("buystatus", false);
            }

            messageResult.setData(data);
            messageResult.setResult(true);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);

            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("cameraListPension")
    @ApiOperation(value = "家长直播列表集合   --长者")
    public MessageResult<Map> cameraListPension(String currentId, String token, @RequestAttribute String subject) {
        //是否购买，
        //购买时长
        //视频

        MessageResult<Map> messageResult = new MessageResult<>();

        try {

            PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));
            Long personId = personInfo.getId();
            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());

            if (StringUtils.isNotBlank(personPopedom.getRelationPopedom())) {
                PersonPopedom personPopedom1 = personPopedomService.get(personPopedom.getRelationPopedom());
                personId = personPopedom1.getPersonId();
            }

            Map<String, Object> data = new HashMap<>();

//          if (true) {
            List<CameraInfo> cameraInfos = cameraInfoService.findByPersonId(personId);
            data.put("list", cameraInfos);
            data.put("buystatus", true);
//          } else {
//            data.put("buystatus", false);
//          }

            messageResult.setData(data);
            messageResult.setResult(true);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);

            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


    @PostMapping("cameraDetailPension")
    @ApiOperation(value = "观看直播-长者")
    public MessageResult<Map> cameraDetailPension(String id, String currentId, @RequestAttribute String subject) {

        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            Map<String, Object> data = new HashMap<>();

            PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));

            Long personId = personInfo.getId();
            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());

            if (StringUtils.isNotBlank(personPopedom.getRelationPopedom())) {
                PersonPopedom personPopedom1 = personPopedomService.get(personPopedom.getRelationPopedom());
                personId = personPopedom1.getPersonId();
            }

            CameraInfo cameraInfo = cameraInfoService.get(id);

            if (cameraInfo.getStatus() == 1) {
                String appKey, appSecret;

                appKey = cameraInfo.getAccount();
                appSecret = cameraInfo.getPassword();

                JSONObject jsonObject = null;


                if ("ys".equals(cameraInfo.getPlatform())) {
                    jsonObject = ysUtil.getLiveAddressUrl(appKey, appSecret,
                            cameraInfo.getDeviceSerial(),
                            cameraInfo.getChannelNo(), 5 * 60L);
                } else if ("aliyun".equals(cameraInfo.getPlatform())) {
                    //播流地址短时间有效
                    String pullStreamSignedUrl = AliyunLiveUtil.generateSignedUrl(
                            aliyunLiveConfig.getPullStreamUrl(),
                            "/" + aliyunLiveConfig.getAppName() + "/" + cameraInfo.getDeviceSerial() + ".m3u8",
                            (new Date()).getTime() / 1000 + 5 * 60,
                            aliyunLiveConfig.getPullKey());

                    jsonObject = new JSONObject();

                    jsonObject.put("hdAddress", pullStreamSignedUrl);
                    jsonObject.put("liveAddress", pullStreamSignedUrl);
                }

                data.put("json", jsonObject);
            }

            data.put("detail", cameraInfo);

            messageResult.setData(data);
            messageResult.setResult(true);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);

            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("cameraDetail")
    @ApiOperation(value = "观看直播")
    public MessageResult<Map> cameraDetail(String id, String currentId, @RequestAttribute String subject) {

        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            Map<String, Object> data = new HashMap<>();

            PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));

            Long personId = personInfo.getId();
            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());

            if (StringUtils.isNotBlank(personPopedom.getRelationPopedom())) {
                PersonPopedom personPopedom1 = personPopedomService.get(personPopedom.getRelationPopedom());
                personId = personPopedom1.getPersonId();
            }

            CameraInfo cameraInfo = cameraInfoService.get(id);
            CameraPurchaser purchaser = cameraPurchaserService.getByPersonId(personId);

            //收费摄像头，判断是否付费
            if (!exist(purchaser)) {
                //未购买， 或者到期
                if (purchaser == null) {
                    throw new Exception("异常访问");
                } else {
                    throw new Exception("购买时间已经到期");
                }
            }

            if (cameraInfo.getStatus() == 1) {
                String appKey, appSecret;
                appKey = cameraInfo.getAccount();
                appSecret = cameraInfo.getPassword();

                JSONObject jsonObject = null;

                if ("ys".equals(cameraInfo.getPlatform())) {
                    jsonObject = ysUtil.getLiveAddressUrl(appKey, appSecret,
                            cameraInfo.getDeviceSerial(),
                            cameraInfo.getChannelNo(), 5 * 60L);
                } else if ("aliyun".equals(cameraInfo.getPlatform())) {
                    //播流地址短时间有效
                    String pullStreamSignedUrl = AliyunLiveUtil.generateSignedUrl(
                            aliyunLiveConfig.getPullStreamUrl(),
                            "/" + aliyunLiveConfig.getAppName() + "/" + cameraInfo.getDeviceSerial() + ".m3u8",
                            (new Date()).getTime() / 1000 + 5 * 60,
                            aliyunLiveConfig.getPullKey());

                    jsonObject = new JSONObject();

                    jsonObject.put("hdAddress", pullStreamSignedUrl);
                    jsonObject.put("liveAddress", pullStreamSignedUrl);
                }

                data.put("json", jsonObject);
            }

            data.put("detail", cameraInfo);

            messageResult.setData(data);
            messageResult.setResult(true);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);

            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("submit")
    @ApiOperation(value = "提交购买")
    public MessageResult<CashierDTO> submit(String goodsId, String payPersonId, String personId, String token, @RequestAttribute String subject) {

        MessageResult<CashierDTO> messageResult = new MessageResult<>();

        try {

            // CourseInfo courseInfo = courseInfoService.get(courseId);
            GoodsInfo goodsInfo = goodsInfoService.get(goodsId);
            if (goodsInfo == null) {
                throw new Exception("商品不存在");
            }


            Map<String, Object> map = new HashMap();
            // map.put("code",paycode);
            map.put("payPersonId", payPersonId);
            map.put("personId", personId);


            CashierDTO cashierDTO = cameraPurchaserService.submit(goodsInfo, map);


            messageResult.setData(cashierDTO);
            messageResult.setCode(200);
            messageResult.setMessage("成功");
            messageResult.setResult(true);
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);
        }

        return messageResult;
    }

    @PostMapping("update")
    @ApiOperation(value = "设备维护-update")
    public MessageResult<Object> update(String id, String personId, String token, @RequestAttribute String subject) {

        MessageResult<Object> messageResult = new MessageResult<>();

        try {
            CameraInfo info = cameraInfoService.get(id);
            info.setUpdateBy(subject);
            info.setUpdateTime(new Date());
            if (StringUtils.isNotEmpty(personId)) {
                info.setPersonId(Long.valueOf(personId));
            } else {
                info.setPersonId(null);
            }
            cameraInfoService.update(info);
            //  messageResult.setData(cashierDTO);
            messageResult.setCode(200);
            messageResult.setMessage("成功");
            messageResult.setResult(true);
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);
        }

        return messageResult;
    }


    @ApiOperation(value = "设备维护")
    @RequestMapping(value = "pageList", method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String token, String name, String id,
            @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
            HttpServletRequest request) {
        String subject = (String) request.getAttribute("subject");

        //当前用户ID
        System.out.println(subject);

        MessageResult<Map> msgResult = new MessageResult<>();

        Map<String, Object> searchParams = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("create_time", "desc"));

        PersonInfo person = personInfoService.get(Long.parseLong(subject));

        if (StringUtils.isNotEmpty(name)) {
            searchParams.put("deviceName", "%" + name + "%");
        }
        if (StringUtils.isNotEmpty(id)) {
            searchParams.put("deviceSerial", "%" + id + "%");
        }

        Page<CameraInfo> page = cameraInfoService.pageSearch(searchParams, pageIndex, pageSize, true, sortList);

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;
    }

}
