package cn.ibizlab.businesscentral.centralapi.rest;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.math.BigInteger;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.ServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PostAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import cn.ibizlab.businesscentral.centralapi.dto.*;
import cn.ibizlab.businesscentral.centralapi.mapping.*;
import cn.ibizlab.businesscentral.core.marketing.domain.Campaign;
import cn.ibizlab.businesscentral.core.marketing.service.ICampaignService;
import cn.ibizlab.businesscentral.core.marketing.filter.CampaignSearchContext;
import cn.ibizlab.businesscentral.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"市场活动" })
@RestController("CentralApi-campaign")
@RequestMapping("")
public class CampaignResource {

    @Autowired
    public ICampaignService campaignService;

    @Autowired
    @Lazy
    public CampaignMapping campaignMapping;

    @PreAuthorize("hasPermission(this.campaignMapping.toDomain(#campaigndto),'iBizBusinessCentral-Campaign-Create')")
    @ApiOperation(value = "新建市场活动", tags = {"市场活动" },  notes = "新建市场活动")
	@RequestMapping(method = RequestMethod.POST, value = "/campaigns")
    @Transactional
    public ResponseEntity<CampaignDTO> create(@RequestBody CampaignDTO campaigndto) {
        Campaign domain = campaignMapping.toDomain(campaigndto);
		campaignService.create(domain);
        CampaignDTO dto = campaignMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.campaignMapping.toDomain(#campaigndtos),'iBizBusinessCentral-Campaign-Create')")
    @ApiOperation(value = "批量新建市场活动", tags = {"市场活动" },  notes = "批量新建市场活动")
	@RequestMapping(method = RequestMethod.POST, value = "/campaigns/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<CampaignDTO> campaigndtos) {
        campaignService.createBatch(campaignMapping.toDomain(campaigndtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "campaign" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.campaignService.get(#campaign_id),'iBizBusinessCentral-Campaign-Update')")
    @ApiOperation(value = "更新市场活动", tags = {"市场活动" },  notes = "更新市场活动")
	@RequestMapping(method = RequestMethod.PUT, value = "/campaigns/{campaign_id}")
    @Transactional
    public ResponseEntity<CampaignDTO> update(@PathVariable("campaign_id") String campaign_id, @RequestBody CampaignDTO campaigndto) {
		Campaign domain  = campaignMapping.toDomain(campaigndto);
        domain .setCampaignid(campaign_id);
		campaignService.update(domain );
		CampaignDTO dto = campaignMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.campaignService.getCampaignByEntities(this.campaignMapping.toDomain(#campaigndtos)),'iBizBusinessCentral-Campaign-Update')")
    @ApiOperation(value = "批量更新市场活动", tags = {"市场活动" },  notes = "批量更新市场活动")
	@RequestMapping(method = RequestMethod.PUT, value = "/campaigns/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<CampaignDTO> campaigndtos) {
        campaignService.updateBatch(campaignMapping.toDomain(campaigndtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.campaignService.get(#campaign_id),'iBizBusinessCentral-Campaign-Remove')")
    @ApiOperation(value = "删除市场活动", tags = {"市场活动" },  notes = "删除市场活动")
	@RequestMapping(method = RequestMethod.DELETE, value = "/campaigns/{campaign_id}")
    @Transactional
    public ResponseEntity<Boolean> remove(@PathVariable("campaign_id") String campaign_id) {
         return ResponseEntity.status(HttpStatus.OK).body(campaignService.remove(campaign_id));
    }

    @PreAuthorize("hasPermission(this.campaignService.getCampaignByIds(#ids),'iBizBusinessCentral-Campaign-Remove')")
    @ApiOperation(value = "批量删除市场活动", tags = {"市场活动" },  notes = "批量删除市场活动")
	@RequestMapping(method = RequestMethod.DELETE, value = "/campaigns/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        campaignService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.campaignMapping.toDomain(returnObject.body),'iBizBusinessCentral-Campaign-Get')")
    @ApiOperation(value = "获取市场活动", tags = {"市场活动" },  notes = "获取市场活动")
	@RequestMapping(method = RequestMethod.GET, value = "/campaigns/{campaign_id}")
    public ResponseEntity<CampaignDTO> get(@PathVariable("campaign_id") String campaign_id) {
        Campaign domain = campaignService.get(campaign_id);
        CampaignDTO dto = campaignMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取市场活动草稿", tags = {"市场活动" },  notes = "获取市场活动草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/campaigns/getdraft")
    public ResponseEntity<CampaignDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(campaignMapping.toDto(campaignService.getDraft(new Campaign())));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Campaign-Active-all')")
    @ApiOperation(value = "激活", tags = {"市场活动" },  notes = "激活")
	@RequestMapping(method = RequestMethod.POST, value = "/campaigns/{campaign_id}/active")
    @Transactional
    public ResponseEntity<CampaignDTO> active(@PathVariable("campaign_id") String campaign_id, @RequestBody CampaignDTO campaigndto) {
        Campaign domain = campaignMapping.toDomain(campaigndto);
domain.setCampaignid(campaign_id);
        domain = campaignService.active(domain);
        campaigndto = campaignMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(campaigndto);
    }

    @ApiOperation(value = "检查市场活动", tags = {"市场活动" },  notes = "检查市场活动")
	@RequestMapping(method = RequestMethod.POST, value = "/campaigns/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody CampaignDTO campaigndto) {
        return  ResponseEntity.status(HttpStatus.OK).body(campaignService.checkKey(campaignMapping.toDomain(campaigndto)));
    }

    @PreAuthorize("hasPermission(this.campaignMapping.toDomain(#campaigndto),'iBizBusinessCentral-Campaign-Save')")
    @ApiOperation(value = "保存市场活动", tags = {"市场活动" },  notes = "保存市场活动")
	@RequestMapping(method = RequestMethod.POST, value = "/campaigns/save")
    public ResponseEntity<Boolean> save(@RequestBody CampaignDTO campaigndto) {
        return ResponseEntity.status(HttpStatus.OK).body(campaignService.save(campaignMapping.toDomain(campaigndto)));
    }

    @PreAuthorize("hasPermission(this.campaignMapping.toDomain(#campaigndtos),'iBizBusinessCentral-Campaign-Save')")
    @ApiOperation(value = "批量保存市场活动", tags = {"市场活动" },  notes = "批量保存市场活动")
	@RequestMapping(method = RequestMethod.POST, value = "/campaigns/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<CampaignDTO> campaigndtos) {
        campaignService.saveBatch(campaignMapping.toDomain(campaigndtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Campaign-Stop-all')")
    @ApiOperation(value = "停用", tags = {"市场活动" },  notes = "停用")
	@RequestMapping(method = RequestMethod.POST, value = "/campaigns/{campaign_id}/stop")
    @Transactional
    public ResponseEntity<CampaignDTO> stop(@PathVariable("campaign_id") String campaign_id, @RequestBody CampaignDTO campaigndto) {
        Campaign domain = campaignMapping.toDomain(campaigndto);
domain.setCampaignid(campaign_id);
        domain = campaignService.stop(domain);
        campaigndto = campaignMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(campaigndto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Campaign-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Campaign-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"市场活动" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/campaigns/fetchdefault")
	public ResponseEntity<List<CampaignDTO>> fetchDefault(CampaignSearchContext context) {
        Page<Campaign> domains = campaignService.searchDefault(context) ;
        List<CampaignDTO> list = campaignMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Campaign-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Campaign-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"市场活动" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/campaigns/searchdefault")
	public ResponseEntity<Page<CampaignDTO>> searchDefault(@RequestBody CampaignSearchContext context) {
        Page<Campaign> domains = campaignService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(campaignMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Campaign-searchEffective-all') and hasPermission(#context,'iBizBusinessCentral-Campaign-Get')")
	@ApiOperation(value = "获取有效", tags = {"市场活动" } ,notes = "获取有效")
    @RequestMapping(method= RequestMethod.GET , value="/campaigns/fetcheffective")
	public ResponseEntity<List<CampaignDTO>> fetchEffective(CampaignSearchContext context) {
        Page<Campaign> domains = campaignService.searchEffective(context) ;
        List<CampaignDTO> list = campaignMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Campaign-searchEffective-all') and hasPermission(#context,'iBizBusinessCentral-Campaign-Get')")
	@ApiOperation(value = "查询有效", tags = {"市场活动" } ,notes = "查询有效")
    @RequestMapping(method= RequestMethod.POST , value="/campaigns/searcheffective")
	public ResponseEntity<Page<CampaignDTO>> searchEffective(@RequestBody CampaignSearchContext context) {
        Page<Campaign> domains = campaignService.searchEffective(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(campaignMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Campaign-searchStop-all') and hasPermission(#context,'iBizBusinessCentral-Campaign-Get')")
	@ApiOperation(value = "获取停用", tags = {"市场活动" } ,notes = "获取停用")
    @RequestMapping(method= RequestMethod.GET , value="/campaigns/fetchstop")
	public ResponseEntity<List<CampaignDTO>> fetchStop(CampaignSearchContext context) {
        Page<Campaign> domains = campaignService.searchStop(context) ;
        List<CampaignDTO> list = campaignMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Campaign-searchStop-all') and hasPermission(#context,'iBizBusinessCentral-Campaign-Get')")
	@ApiOperation(value = "查询停用", tags = {"市场活动" } ,notes = "查询停用")
    @RequestMapping(method= RequestMethod.POST , value="/campaigns/searchstop")
	public ResponseEntity<Page<CampaignDTO>> searchStop(@RequestBody CampaignSearchContext context) {
        Page<Campaign> domains = campaignService.searchStop(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(campaignMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

