package com.softwarebr.nunu.web.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.brframework.commoncms.annatotion.AdminMenu;
import com.brframework.commoncms.annatotion.layout.EditAlertLayout;
import com.brframework.commoncms.annatotion.layout.EditLayout;
import com.brframework.commoncms.annatotion.layout.PageLayout;
import com.brframework.commoncms.annatotion.layout.ViewLayout;
import com.brframework.commoncms.annatotion.option.CmsOption;
import com.brframework.commoncms.core.Icons;
import com.brframework.commonweb.json.JSONResult;
import com.brframework.commonweb.json.Page;
import com.brframework.commonweb.json.PageParam;
import com.brframework.commonwebadmin.aop.annotation.AOLog;
import com.softwarebr.nunu.domain.PlatformModular;
import com.softwarebr.nunu.domain.VerifyPageTotal;
import com.softwarebr.nunu.dto.ser.PlatformParamDTO;
import com.softwarebr.nunu.entity.ser.Platform;
import com.softwarebr.nunu.globals.SystemConst;
import com.softwarebr.nunu.json.admin.ser.*;
import com.softwarebr.nunu.service.ser.PlatformService;
import com.softwarebr.nunu.service.user.MemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;

import static com.brframework.commondb.core.ControllerPageHandle.convertTo;
import static com.brframework.commondb.core.ControllerPageHandle.jpaPageConvertToPage;

/**
 * @author lilin
 * @date 2020-02-24 13:22:47
 */

@RestController
@Api(tags = "创新资源服务平台管理")
@AdminMenu(menuName = "创新资源服务平台管理", icon = Icons.TABLE)
@RequestMapping("/admin/access")
public class AdminSerController {

    @Autowired
    private PlatformService platformService;

    @Autowired
    private MemberService memberService;

    @ApiOperation(value = "创新资源服务平台列表", notes = "创新资源服务平台列表", produces = "text/plain")
    @GetMapping("/v1/platform/page")
    @AdminMenu(menuName = "创新资源服务平台管理", url = "resources")
    @PreAuthorize("hasRole('ser-platform-query')")
    @PageLayout(
            options = {
                    @CmsOption(name = "添加", uriMappingMethod = "platformCreateV1")
            },
            columnOptions = {
                    @CmsOption(name = "查看", uriMappingMethod = "getPlatform"),
                    @CmsOption(name = "上架", uriMappingMethod = "platformUpperShelfV1"),
                    @CmsOption(name = "下架", uriMappingMethod = "platformLowerShelfV1"),
                    @CmsOption(name = "首页推荐", uriMappingMethod = "platformIndexYesV1"),
                    @CmsOption(name = "取消推荐", uriMappingMethod = "platformIndexNoV1"),
                    @CmsOption(name = "审核", uriMappingMethod = "platformVerifyV1"),
                    @CmsOption(name = "修改", uriMappingMethod = "platformEditV1")
            }
    )
    public JSONResult<Page<PlatformResult>> platformListV1(PageParam pageParam, PlatformQueryParam param) {
        if (null != param.getAccount()) {
            param.setPublisher(memberService.findMemberIdByPhone(param.getAccount()));
        }
        Page<PlatformResult> page = jpaPageConvertToPage(platformService.page(pageParam, param), pageParam, PlatformResult.class);
        for (PlatformResult platformResult : page.getList()) {
            if (platformResult.getPublisher() > 0) {
                platformResult.setAccount(memberService.accessObject(platformResult.getPublisher()).getPhone());
            } else {
                platformResult.setAccount("平台");
            }

        }
        return JSONResult.ok(page);
    }

    @ApiOperation(value = "创新资源服务平台状态数据统计", notes = "创新资源服务平台状态数据统计", produces = "text/plain")
    @PreAuthorize("hasRole('ser-platform-query')")
    @GetMapping("/v1/platform/count")
    public JSONResult<VerifyPageTotal> getPlatformCount(PlatformQueryParam param) {
        VerifyPageTotal verifyPageResult = new VerifyPageTotal();
        if (null != param.getAccount()) {
            param.setPublisher(memberService.findMemberIdByPhone(param.getAccount()));
        }
        verifyPageResult.setTotalCount(platformService.count(param));
        param.setStatus(SystemConst.STATUS_LOWER_SHELF);
        verifyPageResult.setLowerCount(platformService.count(param));
        param.setStatus(SystemConst.STATUS_UPPER_SHELF);
        verifyPageResult.setUpperCount(platformService.count(param));
        param.setStatus(null);
        param.setVerify(SystemConst.VERIFY_AWAIT);
        verifyPageResult.setVerifyAwaitCount(platformService.count(param));
        param.setVerify(SystemConst.VERIFY_ADOPT);
        verifyPageResult.setVerifyAdoptCount(platformService.count(param));
        param.setVerify(SystemConst.VERIFY_REJECT);
        verifyPageResult.setVerifyRejectCount(platformService.count(param));
        return JSONResult.ok(verifyPageResult);
    }

    @ApiOperation(value = "修改创新资源服务平台信息", notes = "修改创新资源服务平台信息", produces = "text/plain")
    @PostMapping("/v1/platform/{id}")
    @PreAuthorize("hasRole('ser-platform-edit-v1')")
    @AOLog
    @EditAlertLayout(
            paddingMappingMethod = "getPlatform"
    )
    public JSONResult platformEditV1(@PathVariable Long id, @Valid @RequestBody PlatformParam param) {
        PlatformParamDTO platformParamDTO = convertTo(param, PlatformParamDTO.class);
        platformParamDTO.setModularJson(JSONObject.toJSONString(param.getModulars()));
        platformService.updatePlatform(id, platformParamDTO);
        return JSONResult.ok();
    }

    @ApiOperation(value = "添加创新资源服务平台信息", notes = "添加创新资源服务平台信息", produces = "text/plain")
    @PutMapping("/v1/platform/add")
    @PreAuthorize("hasRole('ser-platform-create-v1')")
    @AOLog
    @EditLayout
    public JSONResult platformCreateV1(@Valid @RequestBody PlatformParam param) {
        PlatformParamDTO platformParamDTO = convertTo(param, PlatformParamDTO.class);
        platformParamDTO.setModularJson(JSONObject.toJSONString(param.getModulars()));
        platformService.savePlatform(-1L, platformParamDTO);
        return JSONResult.ok();
    }

    @ApiOperation(value = "查看创新资源服务平台信息", notes = "查看创新资源服务平台信息", produces = "text/plain")
    @PreAuthorize("hasRole('ser-platform-query')")
    @GetMapping("/v1/platform/{id}")
    @ViewLayout(paddingMappingMethod = "getPlatform")
    public JSONResult<PlatformDetailsResult> getPlatform(@PathVariable Long id) {
        Platform platform = platformService.accessObject(id);
        PlatformDetailsResult detailsResult = convertTo(platform, PlatformDetailsResult.class);
        detailsResult.setModulars(JSONArray.parseArray(platform.getModular(), PlatformModular.class));
        return JSONResult.ok(detailsResult);
    }

    @ApiOperation(value = "创新资源服务平台上架", notes = "创新资源服务平台上架", produces = "text/plain")
    @PostMapping("/v1/platform/upper/{id}")
    @PreAuthorize("hasRole('ser-platform-upper-edit-v1')")
    @AOLog
    public JSONResult platformUpperShelfV1(@PathVariable Long id) {
        platformService.platformUpperShelf(id);
        return JSONResult.ok();
    }

    @ApiOperation(value = "创新资源服务平台下架", notes = "创新资源服务平台下架", produces = "text/plain")
    @PostMapping("/v1/platform/lower/{id}")
    @PreAuthorize("hasRole('ser-platform-lower-edit-v1')")
    @AOLog
    public JSONResult platformLowerShelfV1(@PathVariable Long id) {
        platformService.platformLowerShelf(id);
        return JSONResult.ok();
    }

    @ApiOperation(value = "创新资源服务平台审核", notes = "创新资源服务平台审核", produces = "text/plain")
    @PostMapping("/v1/platform/verify/{id}")
    @PreAuthorize("hasRole('ser-platform-verify-edit-v1')")
    @AOLog
    public JSONResult platformVerifyV1(@PathVariable Long id, @Valid @RequestBody PlatformVerifyParam param) {
        platformService.platformVerify(id, param.getVerify(), param.getVerifyRemark());
        return JSONResult.ok();
    }

    @ApiOperation(value = "创新资源服务平台首页推荐", notes = "创新资源服务平台首页推荐", produces = "text/plain")
    @PreAuthorize("hasRole('ser-platform-index-edit-v1')")
    @PostMapping("/v1/platform/index/yes/{id}")
    @AOLog
    public JSONResult platformIndexYesV1(@PathVariable Long id) {
        platformService.platformIndexYes(id);
        return JSONResult.ok();
    }

    @ApiOperation(value = "创新资源服务平台取消推荐", notes = "创新资源服务平台取消推荐", produces = "text/plain")
    @PreAuthorize("hasRole('ser-platform-index-edit-v1')")
    @PostMapping("/v1/platform/index/no/{id}")
    @AOLog
    public JSONResult platformIndexNoV1(@PathVariable Long id) {
        platformService.platformIndexNo(id);
        return JSONResult.ok();
    }

}