package com.izouma.nineth.web;

import com.izouma.nineth.domain.ActivityCollection;
import com.izouma.nineth.domain.ActivityOrder;
import com.izouma.nineth.domain.Asset;
import com.izouma.nineth.domain.User;
import com.izouma.nineth.dto.ActivityOrderInput;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.lock.RedisLockException;
import com.izouma.nineth.repo.ActivityOrderRepo;
import com.izouma.nineth.service.ActivityOrderService;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.utils.SecurityUtils;
import com.izouma.nineth.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/activityOrder")
@AllArgsConstructor
public class ActivityOrderController extends BaseController {
    private ActivityOrderService activityOrderService;
    private ActivityOrderRepo    activityOrderRepo;

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public ActivityOrder save(@RequestBody ActivityOrder record) {
        if (record.getId() != null) {
            ActivityOrder orig = activityOrderRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return activityOrderRepo.save(orig);
        }
        return activityOrderRepo.save(record);
    }


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<ActivityOrder> all(@RequestBody PageQuery pageQuery) {
        return activityOrderService.all(pageQuery);
    }

    @GetMapping("/get/{id}")
    public ActivityOrder get(@PathVariable Long id) {
        return activityOrderRepo.findById(id).orElseThrow(new BusinessException("活动订单无记录"));
    }

    /**
     * 获取活动要求兑换物和详情
     * @param id 活动ID
     * @return 活动
     */
    @GetMapping("/detail/{projectId}/{id}")
    public ActivityCollection activityDetail(@PathVariable Integer projectId, @PathVariable Long id) {
        final User user = currentUser();
        return activityOrderService.activityDetail(projectId, id, user);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        activityOrderRepo.softDelete(id);
    }

    @PostMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response,@RequestBody PageQuery pageQuery) throws IOException {
        List<ActivityOrder> data = all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }

    /**
     * 活动收集 兑换
     * @param mintActivityId 兑换的活动Id
     * @param collectionId 兑换的藏品Id
     * @param assetIds 消耗的个人资产Id
     * @return 兑换结果
     */
    @PostMapping("/create")
    public Asset create(@RequestBody ActivityOrderInput input) {
        try {
            final User user = SecurityUtils.getAuthenticatedUser();
            return activityOrderService.create(user, input.getMintActivityId(), input.getProjectId(), input.getCollectionId(), input.getAssetIds());
        }
        catch (RedisLockException err) {
            throw new BusinessException("活动火爆,请稍后再试");
        }
    }
}

