package cn.ibizlab.api.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.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 org.springframework.validation.annotation.Validated;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import cn.ibizlab.api.dto.*;
import cn.ibizlab.api.mapping.*;
import cn.ibizlab.core.analysis.domain.DAMetric;
import cn.ibizlab.core.analysis.service.IDAMetricService;
import cn.ibizlab.core.analysis.filter.DAMetricSearchContext;
import cn.ibizlab.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"指标" })
@RestController("api-dametric")
@RequestMapping("")
public class DAMetricResource {

    @Autowired
    public IDAMetricService dametricService;

    @Autowired
    @Lazy
    public DAMetricMapping dametricMapping;

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-Create-all')")
    @ApiOperation(value = "新建指标", tags = {"指标" },  notes = "新建指标")
	@RequestMapping(method = RequestMethod.POST, value = "/dametrics")
    public ResponseEntity<DAMetricDTO> create(@Validated @RequestBody DAMetricDTO dametricdto) {
        DAMetric domain = dametricMapping.toDomain(dametricdto);
		dametricService.create(domain);
        DAMetricDTO dto = dametricMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-Create-all')")
    @ApiOperation(value = "批量新建指标", tags = {"指标" },  notes = "批量新建指标")
	@RequestMapping(method = RequestMethod.POST, value = "/dametrics/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<DAMetricDTO> dametricdtos) {
        dametricService.createBatch(dametricMapping.toDomain(dametricdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "dametric" , versionfield = "updatedate")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-Update-all')")
    @ApiOperation(value = "更新指标", tags = {"指标" },  notes = "更新指标")
	@RequestMapping(method = RequestMethod.PUT, value = "/dametrics/{dametric_id}")
    public ResponseEntity<DAMetricDTO> update(@PathVariable("dametric_id") String dametric_id, @RequestBody DAMetricDTO dametricdto) {
		DAMetric domain  = dametricMapping.toDomain(dametricdto);
        domain .setMetricId(dametric_id);
		dametricService.update(domain );
		DAMetricDTO dto = dametricMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-Update-all')")
    @ApiOperation(value = "批量更新指标", tags = {"指标" },  notes = "批量更新指标")
	@RequestMapping(method = RequestMethod.PUT, value = "/dametrics/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<DAMetricDTO> dametricdtos) {
        dametricService.updateBatch(dametricMapping.toDomain(dametricdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-Remove-all')")
    @ApiOperation(value = "删除指标", tags = {"指标" },  notes = "删除指标")
	@RequestMapping(method = RequestMethod.DELETE, value = "/dametrics/{dametric_id}")
    public ResponseEntity<Boolean> remove(@PathVariable("dametric_id") String dametric_id) {
         return ResponseEntity.status(HttpStatus.OK).body(dametricService.remove(dametric_id));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-Remove-all')")
    @ApiOperation(value = "批量删除指标", tags = {"指标" },  notes = "批量删除指标")
	@RequestMapping(method = RequestMethod.DELETE, value = "/dametrics/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        dametricService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-Get-all')")
    @ApiOperation(value = "获取指标", tags = {"指标" },  notes = "获取指标")
	@RequestMapping(method = RequestMethod.GET, value = "/dametrics/{dametric_id}")
    public ResponseEntity<DAMetricDTO> get(@PathVariable("dametric_id") String dametric_id) {
        DAMetric domain = dametricService.get(dametric_id);
        DAMetricDTO dto = dametricMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取指标草稿", tags = {"指标" },  notes = "获取指标草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/dametrics/getdraft")
    public ResponseEntity<DAMetricDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(dametricMapping.toDto(dametricService.getDraft(new DAMetric())));
    }

    @ApiOperation(value = "检查指标", tags = {"指标" },  notes = "检查指标")
	@RequestMapping(method = RequestMethod.POST, value = "/dametrics/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody DAMetricDTO dametricdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(dametricService.checkKey(dametricMapping.toDomain(dametricdto)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-Save-all')")
    @ApiOperation(value = "保存指标", tags = {"指标" },  notes = "保存指标")
	@RequestMapping(method = RequestMethod.POST, value = "/dametrics/save")
    public ResponseEntity<Boolean> save(@RequestBody DAMetricDTO dametricdto) {
        return ResponseEntity.status(HttpStatus.OK).body(dametricService.save(dametricMapping.toDomain(dametricdto)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-Save-all')")
    @ApiOperation(value = "批量保存指标", tags = {"指标" },  notes = "批量保存指标")
	@RequestMapping(method = RequestMethod.POST, value = "/dametrics/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<DAMetricDTO> dametricdtos) {
        dametricService.saveBatch(dametricMapping.toDomain(dametricdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-SyncRule-all')")
    @ApiOperation(value = "同步指标到规则", tags = {"指标" },  notes = "同步指标到规则")
	@RequestMapping(method = RequestMethod.POST, value = "/dametrics/{dametric_id}/syncrule")
    public ResponseEntity<DAMetricDTO> syncRule(@PathVariable("dametric_id") String dametric_id, @RequestBody DAMetricDTO dametricdto) {
        DAMetric domain = dametricMapping.toDomain(dametricdto);
        domain.setMetricId(dametric_id);
        domain = dametricService.syncRule(domain);
        dametricdto = dametricMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dametricdto);
    }
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-SyncRule-all')")
    @ApiOperation(value = "批量处理[同步指标到规则]", tags = {"指标" },  notes = "批量处理[同步指标到规则]")
	@RequestMapping(method = RequestMethod.POST, value = "/dametrics/{dametric_id}/syncrulebatch")
    public ResponseEntity<Boolean> syncRuleBatch(@RequestBody List<DAMetricDTO> dametricdtos) {
        return ResponseEntity.status(HttpStatus.OK).body(dametricService.syncRuleBatch(dametricMapping.toDomain(dametricdtos)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-searchDefault-all')")
	@ApiOperation(value = "获取数据集", tags = {"指标" } ,notes = "获取数据集")
    @RequestMapping(method= RequestMethod.GET , value="/dametrics/fetchdefault")
	public ResponseEntity<List<DAMetricDTO>> fetchDefault(DAMetricSearchContext context) {
        Page<DAMetric> domains = dametricService.searchDefault(context) ;
        List<DAMetricDTO> list = dametricMapping.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','ibzdst-DAMetric-searchDefault-all')")
	@ApiOperation(value = "查询数据集", tags = {"指标" } ,notes = "查询数据集")
    @RequestMapping(method= RequestMethod.POST , value="/dametrics/searchdefault")
	public ResponseEntity<Page<DAMetricDTO>> searchDefault(@RequestBody DAMetricSearchContext context) {
        Page<DAMetric> domains = dametricService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(dametricMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}


    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-Create-all')")
    @ApiOperation(value = "根据分析建立指标", tags = {"指标" },  notes = "根据分析建立指标")
	@RequestMapping(method = RequestMethod.POST, value = "/dabuilds/{dabuild_id}/dametrics")
    public ResponseEntity<DAMetricDTO> createByDABuild(@PathVariable("dabuild_id") String dabuild_id, @RequestBody DAMetricDTO dametricdto) {
        DAMetric domain = dametricMapping.toDomain(dametricdto);
        domain.setBuildId(dabuild_id);
		dametricService.create(domain);
        DAMetricDTO dto = dametricMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-Create-all')")
    @ApiOperation(value = "根据分析批量建立指标", tags = {"指标" },  notes = "根据分析批量建立指标")
	@RequestMapping(method = RequestMethod.POST, value = "/dabuilds/{dabuild_id}/dametrics/batch")
    public ResponseEntity<Boolean> createBatchByDABuild(@PathVariable("dabuild_id") String dabuild_id, @RequestBody List<DAMetricDTO> dametricdtos) {
        List<DAMetric> domainlist=dametricMapping.toDomain(dametricdtos);
        for(DAMetric domain:domainlist){
            domain.setBuildId(dabuild_id);
        }
        dametricService.createBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "dametric" , versionfield = "updatedate")
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-Update-all')")
    @ApiOperation(value = "根据分析更新指标", tags = {"指标" },  notes = "根据分析更新指标")
	@RequestMapping(method = RequestMethod.PUT, value = "/dabuilds/{dabuild_id}/dametrics/{dametric_id}")
    public ResponseEntity<DAMetricDTO> updateByDABuild(@PathVariable("dabuild_id") String dabuild_id, @PathVariable("dametric_id") String dametric_id, @RequestBody DAMetricDTO dametricdto) {
        DAMetric domain = dametricMapping.toDomain(dametricdto);
        domain.setBuildId(dabuild_id);
        domain.setMetricId(dametric_id);
		dametricService.update(domain);
        DAMetricDTO dto = dametricMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-Update-all')")
    @ApiOperation(value = "根据分析批量更新指标", tags = {"指标" },  notes = "根据分析批量更新指标")
	@RequestMapping(method = RequestMethod.PUT, value = "/dabuilds/{dabuild_id}/dametrics/batch")
    public ResponseEntity<Boolean> updateBatchByDABuild(@PathVariable("dabuild_id") String dabuild_id, @RequestBody List<DAMetricDTO> dametricdtos) {
        List<DAMetric> domainlist=dametricMapping.toDomain(dametricdtos);
        for(DAMetric domain:domainlist){
            domain.setBuildId(dabuild_id);
        }
        dametricService.updateBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-Remove-all')")
    @ApiOperation(value = "根据分析删除指标", tags = {"指标" },  notes = "根据分析删除指标")
	@RequestMapping(method = RequestMethod.DELETE, value = "/dabuilds/{dabuild_id}/dametrics/{dametric_id}")
    public ResponseEntity<Boolean> removeByDABuild(@PathVariable("dabuild_id") String dabuild_id, @PathVariable("dametric_id") String dametric_id) {
		return ResponseEntity.status(HttpStatus.OK).body(dametricService.remove(dametric_id));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-Remove-all')")
    @ApiOperation(value = "根据分析批量删除指标", tags = {"指标" },  notes = "根据分析批量删除指标")
	@RequestMapping(method = RequestMethod.DELETE, value = "/dabuilds/{dabuild_id}/dametrics/batch")
    public ResponseEntity<Boolean> removeBatchByDABuild(@RequestBody List<String> ids) {
        dametricService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-Get-all')")
    @ApiOperation(value = "根据分析获取指标", tags = {"指标" },  notes = "根据分析获取指标")
	@RequestMapping(method = RequestMethod.GET, value = "/dabuilds/{dabuild_id}/dametrics/{dametric_id}")
    public ResponseEntity<DAMetricDTO> getByDABuild(@PathVariable("dabuild_id") String dabuild_id, @PathVariable("dametric_id") String dametric_id) {
        DAMetric domain = dametricService.get(dametric_id);
        DAMetricDTO dto = dametricMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "根据分析获取指标草稿", tags = {"指标" },  notes = "根据分析获取指标草稿")
    @RequestMapping(method = RequestMethod.GET, value = "/dabuilds/{dabuild_id}/dametrics/getdraft")
    public ResponseEntity<DAMetricDTO> getDraftByDABuild(@PathVariable("dabuild_id") String dabuild_id) {
        DAMetric domain = new DAMetric();
        domain.setBuildId(dabuild_id);
        return ResponseEntity.status(HttpStatus.OK).body(dametricMapping.toDto(dametricService.getDraft(domain)));
    }

    @ApiOperation(value = "根据分析检查指标", tags = {"指标" },  notes = "根据分析检查指标")
	@RequestMapping(method = RequestMethod.POST, value = "/dabuilds/{dabuild_id}/dametrics/checkkey")
    public ResponseEntity<Boolean> checkKeyByDABuild(@PathVariable("dabuild_id") String dabuild_id, @RequestBody DAMetricDTO dametricdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(dametricService.checkKey(dametricMapping.toDomain(dametricdto)));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-Save-all')")
    @ApiOperation(value = "根据分析保存指标", tags = {"指标" },  notes = "根据分析保存指标")
	@RequestMapping(method = RequestMethod.POST, value = "/dabuilds/{dabuild_id}/dametrics/save")
    public ResponseEntity<Boolean> saveByDABuild(@PathVariable("dabuild_id") String dabuild_id, @RequestBody DAMetricDTO dametricdto) {
        DAMetric domain = dametricMapping.toDomain(dametricdto);
        domain.setBuildId(dabuild_id);
        return ResponseEntity.status(HttpStatus.OK).body(dametricService.save(domain));
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-Save-all')")
    @ApiOperation(value = "根据分析批量保存指标", tags = {"指标" },  notes = "根据分析批量保存指标")
	@RequestMapping(method = RequestMethod.POST, value = "/dabuilds/{dabuild_id}/dametrics/savebatch")
    public ResponseEntity<Boolean> saveBatchByDABuild(@PathVariable("dabuild_id") String dabuild_id, @RequestBody List<DAMetricDTO> dametricdtos) {
        List<DAMetric> domainlist=dametricMapping.toDomain(dametricdtos);
        for(DAMetric domain:domainlist){
             domain.setBuildId(dabuild_id);
        }
        dametricService.saveBatch(domainlist);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-SyncRule-all')")
    @ApiOperation(value = "根据分析指标", tags = {"指标" },  notes = "根据分析指标")
	@RequestMapping(method = RequestMethod.POST, value = "/dabuilds/{dabuild_id}/dametrics/{dametric_id}/syncrule")
    public ResponseEntity<DAMetricDTO> syncRuleByDABuild(@PathVariable("dabuild_id") String dabuild_id, @PathVariable("dametric_id") String dametric_id, @RequestBody DAMetricDTO dametricdto) {
        DAMetric domain = dametricMapping.toDomain(dametricdto);
        domain.setBuildId(dabuild_id);
        domain = dametricService.syncRule(domain) ;
        dametricdto = dametricMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dametricdto);
    }
    @ApiOperation(value = "批量处理[根据分析指标]", tags = {"指标" },  notes = "批量处理[根据分析指标]")
	@RequestMapping(method = RequestMethod.POST, value = "/dabuilds/{dabuild_id}/dametrics/{dametric_id}/syncrulebatch")
    public ResponseEntity<Boolean> syncRuleByDABuild(@PathVariable("dabuild_id") String dabuild_id, @RequestBody List<DAMetricDTO> dametricdtos) {
        return ResponseEntity.status(HttpStatus.OK).body(dametricService.syncRuleBatch(dametricMapping.toDomain(dametricdtos)));
    }
    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','ibzdst-DAMetric-searchDefault-all')")
	@ApiOperation(value = "根据分析获取数据集", tags = {"指标" } ,notes = "根据分析获取数据集")
    @RequestMapping(method= RequestMethod.GET , value="/dabuilds/{dabuild_id}/dametrics/fetchdefault")
	public ResponseEntity<List<DAMetricDTO>> fetchDAMetricDefaultByDABuild(@PathVariable("dabuild_id") String dabuild_id,DAMetricSearchContext context) {
        context.setN_buildid_eq(dabuild_id);
        Page<DAMetric> domains = dametricService.searchDefault(context) ;
        List<DAMetricDTO> list = dametricMapping.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','ibzdst-DAMetric-searchDefault-all')")
	@ApiOperation(value = "根据分析查询数据集", tags = {"指标" } ,notes = "根据分析查询数据集")
    @RequestMapping(method= RequestMethod.POST , value="/dabuilds/{dabuild_id}/dametrics/searchdefault")
	public ResponseEntity<Page<DAMetricDTO>> searchDAMetricDefaultByDABuild(@PathVariable("dabuild_id") String dabuild_id, @RequestBody DAMetricSearchContext context) {
        context.setN_buildid_eq(dabuild_id);
        Page<DAMetric> domains = dametricService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(dametricMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

