package com.sptg.gateway.controller.ad;

import com.baomidou.mybatisplus.plugins.Page;
import com.sptg.ad.api.dto.AdOfflinePushRecordDto;
import com.sptg.ad.api.entity.*;
import com.sptg.ad.api.feigns.*;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.common.core.constant.SysLogConstant;
import com.sptg.common.core.util.WebUtils;
import com.sptg.common.security.annotation.Security;
import com.sptg.common.security.enums.DataFormatEnum;
import com.sptg.common.security.service.SecurityServiceInterface;
import com.sptg.device.api.feigns.DeviceFeign;
import com.sptg.estate.api.entity.Residential;
import com.sptg.estate.api.feigns.ResidentialFeign;
import com.sptg.estate.api.feigns.UnitFeign;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.entity.Area;
import com.sptg.permissions.api.entity.Organization;
import com.sptg.permissions.api.feigns.AreaFeign;
import com.sptg.permissions.api.feigns.ConfFeign;
import com.sptg.permissions.api.feigns.OrgFeign;
import com.sptg.statistics.api.constant.SysLogMenuConstant;
import com.sptg.statistics.api.entity.SysOperationLog;
import com.sptg.statistics.api.feigns.SysOperationLogFeign;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * title: AdOfflinePushRecordController
 * package: com.sptg.gateway.controller.ad
 * description: 线下广告发布-控制器
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/ad/offline/push")
public class AdOfflinePushRecordController {

    private final SecurityServiceInterface<Account> securityServiceInterface;
    private final ConfFeign confFeign;
    private final AdOfflinePushRecordFeign adOfflinePushRecordFeign;
    private final AdContentFeign adContentFeign;
    private final AdTypeFeign adTypeFeign;
    private final AdMaterialFeign adMaterialFeign;
    private final OrgFeign orgFeign;

    private final ResidentialFeign residentialFeign;
    private final AdAdsenseFeign adAdsenseFeign;
    private final UnitFeign unitFeign;
    private final DeviceFeign deviceFeign;
    private final AreaFeign areaFeign;
    private final SysOperationLogFeign sysOperationLogFeign;

    /**
     * 功能描述:广告发布页面
     */
    @GetMapping("/index")
    @Security(token = {"ad:push::offline:manage"}, format = DataFormatEnum.VIEW)
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView("ad/ad-offline-push-manage");
        modelAndView.addObject("fastDfsServer", this.confFeign.getFileServerHost());
        return modelAndView;
    }


    /**
     * 查询线下广告发布列表(分页)
     *
     * @param adOfflinePushRecordDto 查询条件参数
     * @param page                   分页参数
     */
    @PostMapping(value = "/showAdOfflinePushRecordList")
    @Security(token = {"ad:push::offline:manage"}, format = DataFormatEnum.JSON)
    public ResultBean<Page<AdOfflinePushRecord>> showAdOfflinePushRecordList(AdOfflinePushRecordDto adOfflinePushRecordDto, Page<AdOfflinePushRecord> page) {
        //获取当前登陆用户
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        adOfflinePushRecordDto.setOrgPosition(onLineUser.getOrgPosition());
        adOfflinePushRecordDto.setPage(page);
        ResultBean<Page<AdOfflinePushRecord>> pageResultBean = this.adOfflinePushRecordFeign.showAdOfflinePushRecordList(adOfflinePushRecordDto);
        Page<AdOfflinePushRecord> pageResult = pageResultBean.getData();
        if(null != pageResult){
            List<AdOfflinePushRecord> records = pageResult.getRecords();
            if (records != null && !records.isEmpty()) {
                for (AdOfflinePushRecord adOfflinePushRecord : records) {
                    //  获取关联的外键Id列表
                    Long adId = adOfflinePushRecord.getAdId();
                    if (null != adId) {
                        AdContent adContent = this.adContentFeign.findAdContentById(adId);
                        if (null != adContent) {
                            adOfflinePushRecord.setAdTitle(adContent.getAdTitle());
                            adOfflinePushRecord.setAdCode(adContent.getAdCode());
                            //广告类型名称
                            Long adTypeId = adContent.getAdTypeId();
                            if (null != adTypeId) {
                                AdType adType = this.adTypeFeign.getAdTypeById(adTypeId);
                                if (null != adType) {
                                    adOfflinePushRecord.setAdTypeName(adType.getName());
                                }
                            }
                            //广告素材所属商家
                            Long adMaterialId = adContent.getAdMaterialId();
                            if (null != adMaterialId) {
                                AdMaterial adMaterial = this.adMaterialFeign.findAdMaterialById(adMaterialId);
                                if(null!=adMaterial){
                                    adOfflinePushRecord.setAdMaterialFile(adMaterial.getMaterialFile());
                                    Organization org = this.orgFeign.getOrgById(adMaterial.getOrgId());
                                    if(null!=org){
                                        adOfflinePushRecord.setOrgName(org.getName());
                                    }
                                }
                            }
                            //发布位置

                        }
                    }

                }
            }
        }

        return pageResultBean;
    }

    /**
     * 功能描述:关联广告弹窗页面 iframe
     */
    @GetMapping("/task/relevance/view")
    public ModelAndView showTaskRelevance(Integer onlineOrOffline) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("ad/ad-push-task-relevance");
        modelAndView.addObject("onlineOrOffline", onlineOrOffline);
        return modelAndView;
    }


    /**
     * 功能描述:发布任务详情 iframe
     */
    @GetMapping("/detail/view")
//    @Security(token = {"ad:push:task:detail","ad:push:leisure:task:detail"},format = DataFormatEnum.VIEW)
    public ModelAndView showTaskDetail(Long id) {
        ModelAndView modelAndView = new ModelAndView();
        AdOfflinePushRecord adOfflinePushRecord;
//        //详情
        if (id != null) {
            adOfflinePushRecord = this.adOfflinePushRecordFeign.findAdOfflinePushRecordById(id);
            Long adId = adOfflinePushRecord.getAdId();
            if(adId != null){
                AdContent adContent = this.adContentFeign.findAdContentById(adId);
                if(adContent != null){
                    adOfflinePushRecord.setAdTitle(adContent.getAdTitle());
                }
            }
//                    List<Long> fkId = new ArrayList<>(adPushTaskDetailsList.size());
//                    for (AdPushTaskDetails adPushTaskDetails:adPushTaskDetailsList){
//                        fkId.add(adPushTaskDetails.getFkId());
//                    }
//                    List objects = null;
//                    //发布类型{ 1 ：按小区发布，2：按单元发布，3：按设备发布，4：按区域发布}
//                    Integer pushType = adPushTask.getPushType();
//                    if(pushType==1){
//                        objects = residentialFeign.getByOrgIdList(fkId);
//                    }else if(pushType==2){
//                        objects = unitFeign.getListByIdList(fkId);
//                    }else if(pushType==3){
//                        objects =deviceFeign.getListByIds(fkId);
//                    }else if(pushType==4){
//                        objects = areaFeign.getListByIds(fkId);
//                    }
//                    modelAndView.addObject("objects",objects);
//                }
//            }
            modelAndView.addObject("adOfflinePushRecord", adOfflinePushRecord);
            modelAndView.setViewName("ad/ad-offline-push-detail");
        }
        return modelAndView;
    }

    /**
     * 功能描述:显示新增/编辑页面 iframe
     *
     * @return ModelAndView
     */
    @GetMapping("/add/view")
    @Security(token = {"ad:push:offline:insert"}, format = DataFormatEnum.VIEW)
    public ModelAndView showTaskAddContent() {
        return new ModelAndView("ad/ad-offline-push-add");
    }


    /**
     * 功能描述:新增/编辑广告类容
     * @param task  任务详情
     */
    @PostMapping(value = "/add")
    @Security(token = {"ad:push:offline:insert"}, format = DataFormatEnum.JSON)
    public @ResponseBody
    ResultBean<Boolean> addAdPushTask(AdOfflinePushRecord adOfflinePushRecord) {
//        Assert.notNull(task.getTaskType(),"任务类型不能为空");
//        //  默认启用阈值配置
//        if (null == task.getEnableThreshold()){
//            task.setEnableThreshold(1);
//        }
//        //获取当前登录用户
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        adOfflinePushRecord.setCreateAccountId(onLineUser.getId());
        adOfflinePushRecord.setCreateAccountName(onLineUser.getLoginName());
        adOfflinePushRecord.setOrgId(onLineUser.getOrgId());
        adOfflinePushRecord.setCreateDate(new Date());
        adOfflinePushRecord.setRootOrgId(onLineUser.getRootOrgId());
//        //发布状态{ -1：发布失败，0：待发布，1：发布成功，2：已撤销
        adOfflinePushRecord.setPushStatus(OperationConstant.ZERO);
        adOfflinePushRecord.setOrgPosition(onLineUser.getOrgPosition());
//        // 发布总次数--初始化站位
        adOfflinePushRecord.setPushCount((long) 0);
//        //发布成功次数--初始化站位
        adOfflinePushRecord.setPushSuccess((long) 0);
//        //广告预计发布时间
        Calendar calendar = Calendar.getInstance();
//        //  日期加一天
////        calendar.add(Calendar.DATE, 1);
////        // 将分秒,毫秒域清零,时设置到凌晨2点
////        calendar.set(Calendar.HOUR_OF_DAY, 2);
////        calendar.set(Calendar.MINUTE, 0);
////        calendar.set(Calendar.SECOND, 0);
////        calendar.set(Calendar.MILLISECOND, 0);
//        //广告任务的预计发布时间--第二天凌晨2:00
        adOfflinePushRecord.setEstimatePushDate(calendar.getTime());
//        ResultBean<Boolean>  resultBean=this.adPushTaskFeign.addAdPushTask(task);
        if (StringUtils.isNotBlank(adOfflinePushRecord.getPushLocationId())) {
            String[] locationIdList = adOfflinePushRecord.getPushLocationId().split(",");
            Integer pushType = adOfflinePushRecord.getPushType();
            StringBuffer buffer = new StringBuffer();
            if (pushType == 1) { //按小区
                for (int i = 0; i < locationIdList.length; i++) {
                    Residential residential = this.residentialFeign.findResidentialById(Long.valueOf(locationIdList[i]));
                    if (null != residential) {
                        if (i == 0) {
                            buffer.append(residential.getName());
                        } else {
                            buffer.append("," + residential.getName());
                        }
                    }
                }
            } else if (pushType == 2) {//按广告位
                for (int i = 0; i < locationIdList.length; i++) {
                    AdAdsense adAdsense = this.adAdsenseFeign.findAdsenseById(Long.valueOf(locationIdList[i]));
                    if (null != adAdsense) {
                        if (i == 0) {
                            buffer.append(adAdsense.getAdsenseName());
                        } else {
                            buffer.append("," + adAdsense.getAdsenseName());
                        }
                    }
                }
            } else if (pushType == 3) {//按区域
                List<String> strings = Arrays.asList(locationIdList);
                List<Long> longList = new ArrayList<>();
                strings.parallelStream().forEach(item -> {
                    longList.add(Long.valueOf(item));
                });
                List<Area> listByIds = this.areaFeign.getListByIds(longList);
                for (int i = 0; i < listByIds.size(); i++) {
                    if (i == 0) {
                        buffer.append(listByIds.get(i).getName());
                    } else {
                        buffer.append("," + listByIds.get(i).getName());
                    }
                }
            }
            adOfflinePushRecord.setPushLocationName(buffer.toString());
        }
        ResultBean<Boolean> resultBean = this.adOfflinePushRecordFeign.addAdOfflinePushRecord(adOfflinePushRecord);
        if (resultBean.getData() != null && resultBean.getData()) {
//            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog = new SysOperationLog(SysLogMenuConstant.AD_PUSH_TASK_MANAGE, SysLogConstant.ADD_EVENT,
                    WebUtils.getIp(), adOfflinePushRecord, onLineUser);
            sysOperationLogFeign.info(sysOperationLog);
//            /*-------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

//    /**
//     * 功能描述:任务撤销
//     * @param id 任务id
//     * @return
//     */
    @GetMapping(value = "/cancel/{id}")
    @Security(token = {"ad:offline:push:delete"},format = DataFormatEnum.JSON)
    public ResultBean<Boolean> cancelAdPushTask(@PathVariable(value = "id")Long id){
        ResultBean<Boolean>  resultBean=this.adOfflinePushRecordFeign.cancelAdOfflinePushRecord(id);
        if(resultBean.getData()!=null && resultBean.getData()){
//            //获取当前登录用户
            Account onLineUser = this.securityServiceInterface.getOnLineUser();
            AdOfflinePushRecord adOfflinePushRecord=new AdOfflinePushRecord();
            adOfflinePushRecord.setId(id);
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.AD_PUSH_TASK_MANAGE, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(),"删除线下广告发布记录",adOfflinePushRecord,onLineUser);
            sysOperationLogFeign.info(sysOperationLog);
        }
        return resultBean;
    }
//            AdPushTask adPushTask=new AdPushTask();
    @GetMapping(value = "/push/{id}/{pushStatus}")
    @Security(token = {"ad:offline:push:delete"},format = DataFormatEnum.JSON)
    public ResultBean<Boolean> cancelAdPushTask(@PathVariable(value = "id")Long id,@PathVariable(value = "pushStatus")Integer pushStatus){
        AdOfflinePushRecord adOfflinePushRecordById = this.adOfflinePushRecordFeign.findAdOfflinePushRecordById(id);
        if(adOfflinePushRecordById!=null){
            adOfflinePushRecordById.setPushStatus(pushStatus);
            ResultBean<Boolean> resultBean = this.adOfflinePushRecordFeign.updateAdOfflinePushRecord(adOfflinePushRecordById);
//            adPushTask.setId(id);
            if(resultBean.getData()!=null && resultBean.getData()){
                Account onLineUser = this.securityServiceInterface.getOnLineUser();
                AdOfflinePushRecord adOfflinePushRecord=new AdOfflinePushRecord();
                adOfflinePushRecord.setId(id);
//            /*---------------------------------------------------记录日志--------------------------------------------------------*/
                SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.AD_PUSH_TASK_MANAGE, SysLogConstant.ALTER_EVENT,
                        WebUtils.getIp(),"修改线下广告发布记录状态",adOfflinePushRecord,onLineUser);
                sysOperationLogFeign.info(sysOperationLog);
//            /*-------------------------------------------------------------------------------------------------------------------*/
            }
            return resultBean;
        }
//    }
        return new ResultBean<>(ResultEnum.ERROR);
    }

}
