package com.softwarebr.nunu.web.api;

import com.brframework.commondb.core.ControllerPageHandle;
import com.brframework.commonsecurity.core.SecurityContextHolder;
import com.brframework.commonsecurity.core.SecuritySubject;
import com.brframework.commonsecurity.core.SecurityUserDetails;
import com.brframework.commonsecurity.core.SecurityUserDetailsService;
import com.brframework.commonweb.json.JSONResult;
import com.brframework.commonweb.json.Page;
import com.brframework.commonweb.json.PageParam;
import com.softwarebr.nunu.dto.train.ActivityParamDTO;
import com.softwarebr.nunu.entity.train.Activity;
import com.softwarebr.nunu.entity.train.ActivityLog;
import com.softwarebr.nunu.globals.SystemConst;
import com.softwarebr.nunu.json.api.VerifyResult;
import com.softwarebr.nunu.json.api.train.*;
import com.softwarebr.nunu.service.SearchService;
import com.softwarebr.nunu.service.oper.AreaService;
import com.softwarebr.nunu.service.train.ActivityLogService;
import com.softwarebr.nunu.service.train.ActivityService;
import com.softwarebr.nunu.service.user.MemberService;
import com.softwarebr.nunu.util.AmountConversionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author lilin
 * @date 2020-02-26 11:02:46
 */

@RestController
@Api(tags = "创新培训活动")
@RequestMapping("/api")
public class ApiTrainController {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private ActivityLogService activityLogService;

    @Autowired
    @Qualifier("apiUserDetailsService")
    SecurityUserDetailsService userDetailsService;

    @Autowired
    private SearchService searchService;

    /**
     * 处理活动返回数据
     *
     * @param activityResult
     * @param mark           标记，用作活动状态区分1.活动状态分7种 2活动状态分4种
     */
    private void handleActivityResult(ActivityResult activityResult, int mark) {
        Map<Integer, String> typeMap = activityService.activityType(activityResult.getCategory());
        activityResult.setArea(areaService.accessObject(activityResult.getAreaId()).getCityName());
        activityResult.setCity(areaService.accessObject(activityResult.getCityId()).getCityName());
        activityResult.setProvince(areaService.accessObject(activityResult.getProvinceId()).getCityName());
        activityResult.setPrice(AmountConversionUtil.out(activityResult.getPrice()));
        activityResult.setTypeName(typeMap.get(activityResult.getType()));
        activityResult.setCategoryName(activityResult.getCategory().equals(Activity.CATEGORY_INNOVATE) ? "创新活动" : "培训活动");
        if (mark == 1) {
            Map<Integer, String> activityMap = activityService.activityStatusApi(ControllerPageHandle.convertTo(activityResult, Activity.class));
            activityResult.setActivityStatus(activityMap.keySet().iterator().next());
            activityResult.setActivityStatusName(activityMap.get(activityMap.keySet().iterator().next()));
        } else {
            activityResult.setActivityStatusName(activityService.activityStatusAdmin(ControllerPageHandle.convertTo(activityResult, Activity.class)));
        }
    }

    @ApiOperation(value = "创新培训学院->首页")
    @GetMapping("/v1/train/activity/index/list")
    public JSONResult<Page<ActivityResult>> indexActivityPageV1(PageParam page) {
        ActivityQueryParam param = new ActivityQueryParam();
        param.setIndexType(SystemConst.INDEX_TYPE_YES);
        Page<ActivityResult> activityResultPage = ControllerPageHandle.jpaPageConvertToPage(activityService.page(page, param), page, ActivityResult.class);
        activityResultPage.getList().forEach(a -> handleActivityResult(a, 1));
        return JSONResult.ok(activityResultPage);
    }

    @ApiOperation(value = "培训学院->创新活动")
    @GetMapping("access/v1/train/activity/innovate/list")
    public JSONResult<Page<ActivityResult>> activityInnovatePageV1(PageParam page, ActivityQueryParam param) {
        param.setStatus(SystemConst.STATUS_UPPER_SHELF);
        param.setCategory(Activity.CATEGORY_INNOVATE);
        if (StringUtils.isNotEmpty(param.getName())) {
            searchService.increasingScore(param.getName());
        }
        Page<ActivityResult> activityResultPage = ControllerPageHandle.jpaPageConvertToPage(activityService.page(page, param), page, ActivityResult.class);
        activityResultPage.getList().forEach(a -> handleActivityResult(a, 1));
        return JSONResult.ok(activityResultPage);
    }

    @ApiOperation(value = "培训学院->培训活动")
    @GetMapping("access/v1/train/activity/training/list")
    public JSONResult<Page<ActivityResult>> activityTrainingPageV1(PageParam page, ActivityQueryParam param) {
        param.setStatus(SystemConst.STATUS_UPPER_SHELF);
        param.setCategory(Activity.CATEGORY_TRAIN);
        if (StringUtils.isNotEmpty(param.getName())) {
            searchService.increasingScore(param.getName());
        }
        Page<ActivityResult> activityResultPage = ControllerPageHandle.jpaPageConvertToPage(activityService.page(page, param), page, ActivityResult.class);
        activityResultPage.getList().forEach(a -> handleActivityResult(a, 1));
        return JSONResult.ok(activityResultPage);
    }

    @ApiOperation(value = "培训学院->活动详情")
    @GetMapping("access/v1/train/activity/details/{id}")
    public JSONResult<ActivityDetailsResult> activityDetailsV1(@ApiParam("活动Id") @PathVariable Long id) {
        ActivityDetailsResult detailsResult = ControllerPageHandle.convertTo(activityService.accessObject(id), ActivityDetailsResult.class);
        handleActivityResult(detailsResult, 1);
        return JSONResult.ok(detailsResult);
    }

    @ApiOperation(value = "培训学院->活动报名")
    @PutMapping("access/v1/train/activity/enroll")
    public JSONResult<ActivityLogResult> activityEnrollV1(@Valid @RequestBody ActivityLogParam param) {
        Long memberId = Long.valueOf(SecurityContextHolder.getSubject().getId());
        ActivityLog activityLog = ControllerPageHandle.convertTo(param, ActivityLog.class);
        activityLog.setMemberId(memberId);
        ActivityLogResult activityLogResult = activityLogService.activityLogSave(activityLog);
        return JSONResult.ok(activityLogResult);
    }

    @ApiOperation(value = "收费活动入场码(支付成功后使用)")
    @GetMapping("access/v1/train/charge/{orderNo}")
    public JSONResult<ActivityLogResult> trainChargeV1(@ApiParam("订单号") @PathVariable String orderNo) {
        ActivityLogResult activityLogResult = activityLogService.activityVoucherCode(orderNo);
        return JSONResult.ok(activityLogResult);
    }

    @ApiOperation(value = "培训学院->回执单下载(用于PC)")
    @GetMapping("access/v1/train/receipt/download/{id}")
    public JSONResult receiptDownloadV1(@ApiParam("活动报名Id") @PathVariable Long id, HttpServletResponse response) throws IOException {
        activityLogService.activityReceiptDownload(response, id);
        return JSONResult.ok();
    }

    @ApiOperation(value = "培训学院->活动报名信息下载")
    @GetMapping("/v1/train/excel/download/{token}/{activityId}")
    public JSONResult excelDownloadV1(@ApiParam("token") @PathVariable String token, @ApiParam("活动ID") @PathVariable Long activityId, HttpServletResponse response) {
        SecurityUserDetails user = (SecurityUserDetails) userDetailsService.loadUserByUsername(token);
        SecuritySubject subject = user.getSubject();
        if(subject != null){
            activityLogService.activityExcelDownload(response, activityId);
        }
        return JSONResult.ok();
    }


    @ApiOperation(value = "活动发布->已发布活动")
    @GetMapping("access/v1/train/activity/list")
    public JSONResult<Page<ActivityResult>> activityPageV1(PageParam page, ActivityQueryParam param) {
        Long memberId = Long.valueOf(SecurityContextHolder.getSubject().getId());
        param.setPublisher(memberId);
        Page<ActivityResult> activityResultPage = ControllerPageHandle.jpaPageConvertToPage(activityService.page(page, param), page, ActivityResult.class);
        activityResultPage.getList().forEach(a -> handleActivityResult(a, 2));
        return JSONResult.ok(activityResultPage);
    }

    @ApiOperation(value = "发布活动")
    @PutMapping("access/v1/train/activity")
    public JSONResult<ActivityResult> activityCreateV1(@Valid @RequestBody ActivityParam param) {
        Long memberId = Long.valueOf(SecurityContextHolder.getSubject().getId());
        ActivityParamDTO activityParamDTO = ControllerPageHandle.convertTo(param, ActivityParamDTO.class);
        activityParamDTO.setPrice(new BigDecimal(-1));
        activityParamDTO.setCategory(Activity.CATEGORY_INNOVATE);
        Activity activity = activityService.saveActivity(memberId, activityParamDTO);
        return JSONResult.ok(ControllerPageHandle.convertTo(activity, ActivityResult.class));
    }

    @ApiOperation(value = "发布活动审核结果")
    @GetMapping("access/v1/train/activity/result/{id}")
    public JSONResult<VerifyResult> activityVerifyV1(@ApiParam("活动Id") @PathVariable Long id) {
        VerifyResult verifyResult = ControllerPageHandle.convertTo(activityService.accessObject(id), VerifyResult.class);
        return JSONResult.ok(verifyResult);
    }

}