package com.sptg.gateway.controller.ad;

import com.baomidou.mybatisplus.plugins.Page;
import com.sptg.ad.api.constant.AdSecurityToken;
import com.sptg.ad.api.dto.AdAdsenseDto;
import com.sptg.ad.api.dto.AdContentDto;
import com.sptg.ad.api.entity.AdAdsense;
import com.sptg.ad.api.entity.AdContent;
import com.sptg.ad.api.feigns.AdAdsenseFeign;
import com.sptg.ad.api.feigns.AdContentFeign;
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.entity.Device;
import com.sptg.device.api.feigns.DeviceFeign;
import com.sptg.estate.api.entity.Residential;
import com.sptg.estate.api.feigns.ResidentialFeign;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.feigns.ConfFeign;
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.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * title: AdContentController
 * package: com.sptg.gateway.controller.ad
 * description: 广告位-控制器
 */
@Slf4j
@RestController
@RequestMapping(value = "/ad/adsense")
@RequiredArgsConstructor
public class AdAdsenseController {

    private final ConfFeign confFeign;
    private final SecurityServiceInterface<Account> securityServiceInterface;
    private final AdAdsenseFeign adAdsenseFeign;
    private final SysOperationLogFeign sysOperationLogFeign;
    private final DeviceFeign deviceFeign;
    private final ResidentialFeign residentialFeign;


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

    /**
     * 查询广告类容列表(分页)
     *
     * @param adAdsenseDto 查询条件参数
     * @param page         分页参数
     * @return
     */
    @PostMapping(value = "/showAdAdsenseList")
    @Security(token = AdSecurityToken.AD_ADSENSE_MANAGE, format = DataFormatEnum.JSON)
    public ResultBean<Page<AdAdsense>> showAdAdsenseList(AdAdsenseDto adAdsenseDto, Page<AdAdsense> page) {
        //获取当前登陆用户
//        Account onLineUser = this.securityServiceInterface.getOnLineUser();
//        adAdsenseDto.setOrgPosition(onLineUser.getOrgPosition());
        adAdsenseDto.setPage(page);
        ResultBean<Page<AdAdsense>> pageResultBean = this.adAdsenseFeign.showAdAdsenseList(adAdsenseDto);
        if(null!=pageResultBean.getData()){
                List<AdAdsense> records = pageResultBean.getData().getRecords();
                records.parallelStream().forEach(record -> {
                    if (record.getDeviceId() != null) {
                        Device device = deviceFeign.getEntityById(Long.valueOf(record.getDeviceId()));
                        if (null != device) {
                            record.setDeviceName(device.getName());
                        }

                    }
                    if (record.getResidentialId() != null) {
                        Residential residential = residentialFeign.findResidentialById(record.getResidentialId());
                        if (null != residential) {
                            record.setResidentialArea(residential.getRegion());
                            record.setResidentialName(residential.getName());
                        }

                    }

                });
        }

        return pageResultBean;
    }

    /**
     * 功能描述:显示新增/编辑页面 iframe
     *
     * @param
     * @return
     */
    @GetMapping("/add/view")
    @Security(token = AdSecurityToken.AD_ADSENSE_INSERT, format = DataFormatEnum.VIEW)
    public ModelAndView showEditAdsense(Long id) {
        ModelAndView modelAndView = new ModelAndView("ad/ad-adsense-add");
        modelAndView.addObject("fastDfsServer", this.confFeign.getFileServerHost());
        AdAdsense adAdsense = new AdAdsense();
        //编辑
        if (id != null) {
            AdAdsense edit = this.adAdsenseFeign.findAdsenseById(id);
            if (edit != null) {
                adAdsense = edit;
            }
        }
        modelAndView.addObject("adAdsense", adAdsense);
        return modelAndView;
    }


    /**
     * 功能描述:新增/编辑广告类容
     *
     * @param adAdsense
     * @return
     */
    @PostMapping(value = "/addAdAdsense")
    @Security(token = AdSecurityToken.AD_ADSENSE_INSERT, format = DataFormatEnum.JSON)
    public ResultBean<Boolean> addAdAdsense(AdAdsense adAdsense) {
        if (adAdsense.getDeviceId().equals("")) {
            adAdsense.setDeviceId(null);
        }
        //获取当前登陆用户
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        int operationEvent = SysLogConstant.ALTER_EVENT;
        //新增
        if (adAdsense.getId() == null) {
            adAdsense.setCreateAccountId(onLineUser.getId());
            adAdsense.setCreateAccountName(onLineUser.getLoginName());
//            adAdsense.setOrgId(onLineUser.getOrgId());
            adAdsense.setCreateDate(new Date());
//            adAdsense.setRootOrgId(onLineUser.getRootOrgId());
            adAdsense.setStatus(OperationConstant.ZERO);
//            adContent.setOrgPosition(onLineUser.getOrgPosition());
            operationEvent = SysLogConstant.ADD_EVENT;
        }
        //保存
        ResultBean<Boolean> resultBean = this.adAdsenseFeign.addAdAdsense(adAdsense);
        if (resultBean.getData() != null && resultBean.getData()) {
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog = new SysOperationLog(SysLogMenuConstant.AD_ADSENSE_MANAGE, operationEvent,
                    WebUtils.getIp(), adAdsense, onLineUser);
            sysOperationLogFeign.info(sysOperationLog);
            /*-------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    @PostMapping(value = "/updateAdsenseStatus")
    @Security(token = AdSecurityToken.AD_ADSENSE_INSERT, format = DataFormatEnum.JSON)
    public ResultBean<Boolean> updateAdsenseStatus(@RequestParam("id") Long id, @RequestParam("adsenseStatus") String adsenseStatus) {
        return this.adAdsenseFeign.updateAdsenseStatus(id, adsenseStatus);
    }

    /**
     * 功能描述:删除--软删除
     *
     * @param ids 广告类型id字符串，逗号隔开 1,2,3
     * @return
     */
    @GetMapping(value = "/deleteAdAdsense/{id}")
    @Security(token = AdSecurityToken.AD_ADSENSE_DELETE, format = DataFormatEnum.JSON)
    public ResultBean<Boolean> deleteAdContent(@PathVariable(value = "id") String ids) {
        ResultBean<Boolean> resultBean = this.adAdsenseFeign.deleteAdAdsense(ids);
        if (resultBean.getData()) {
            //获取当前登陆用户
            Account onLineUser = this.securityServiceInterface.getOnLineUser();
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            String[] idsArray = ids.split(",");
            if (idsArray.length > 0) {
                AdAdsenseDto adAdsenseDto = new AdAdsenseDto();
                adAdsenseDto.setIds(Arrays.asList(idsArray));
                SysOperationLog sysOperationLog = new SysOperationLog(SysLogMenuConstant.AD_ADSENSE_MANAGE, SysLogConstant.DELETE_EVENT, WebUtils.getIp(), adAdsenseDto, onLineUser);
                sysOperationLogFeign.info(sysOperationLog);
            }
            /*-------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 功能描述:批量删除广告位
     *
     * @param ids 选中的id集合
     * @return ResultBean<Boolean>
     */
    @PostMapping(value = "/deleteAdSenseList")
    @Security(token = AdSecurityToken.AD_ADSENSE_DELETE, format = DataFormatEnum.JSON)
    public ResultBean<Boolean> deleteAdContentList(@RequestBody List<String> ids) {
        if (null == ids || ids.size() <= 0) {
            //  参数异常
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        AdAdsenseDto dto = new AdAdsenseDto();
        dto.setIds(ids);
        ResultBean<Boolean> resultBean = this.adAdsenseFeign.deleteAdsenseList(dto);
        if (null != resultBean.getData() && resultBean.getData()) {
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog = new SysOperationLog(SysLogMenuConstant.ACCOUNT_MANAGE, SysLogConstant.DELETE_EVENT,
                    WebUtils.getIp(), dto, onLineUser);
            sysOperationLogFeign.info(sysOperationLog);
            /*-------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 功能描述:模糊查询获取广告列表
     * @param
     * @return
     *
     *
     */
//    @GetMapping(value = "/getList")
//    public ResultBean<AdContent> getList(AdContentDto dto){
//        if (null == dto || StringUtils.isEmpty(dto.getAdTitle())){
//            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
//        }
//        //  获取当前用户
//        Account onLineUser = this.securityServiceInterface.getOnLineUser();
//        dto.setOrgPosition(onLineUser.getOrgPosition());
//        return this.adContentFeign.getList(dto);
//    }
}
