package com.apobates.forum.trident.controller.admin;

import com.apobates.forum.member.api.service.MemberService;
import com.apobates.forum.member.api.service.MemberVipExchangeRecordsService;
import com.apobates.forum.member.entity.Member;
import com.apobates.forum.member.entity.MemberVipExchangeRecords;
import com.apobates.forum.trident.controller.form.MemberExchangeForm;
import com.apobates.forum.trident.exception.ResourceNotFoundException;
import com.apobates.forum.utils.Commons;
import com.apobates.forum.utils.DateTimeUtils;
import com.apobates.forum.utils.FrontPageURL;
import com.apobates.forum.utils.TipMessage;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.PageRequest;
import com.apobates.forum.utils.persistence.Pageable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 *
 * @author xiaofanku
 * @since 20200921
 */
@Controller
@RequestMapping(value = "/admin/member/exchange")
public class AdminMemberVipExchangeRecordsController {
    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberVipExchangeRecordsService memberVipExchangeRecordsService;
    @Value("${site.pageSize}")
    private int pageSize;

    @GetMapping(path = "/")
    public String listPage(
            HttpServletRequest request,
            Model model) {
        Stream<MemberVipExchangeRecords> rs = memberVipExchangeRecordsService.getRecent(pageSize);
        model.addAttribute("rs", rs.collect(Collectors.toList()));
        return "admin/member_exchange/index";
    }

    //创建
    @GetMapping(path = "/create")
    public String createForm(
            @RequestParam(name = "member", required = false, defaultValue = "0") long memberId,
            @RequestParam(name = "names", required = false, defaultValue = "") String names,
            HttpServletRequest request,
            Model model) {
        MemberExchangeForm form = new MemberExchangeForm();
        form.setMemberId(memberId);
        form.setNames(names);
        form.setLimit("1");
        form.setUnit("5");
        model.addAttribute("form", form);
        return "admin/member_exchange/create";
    }
    @PostMapping(path = "/create")
    public String createAction(
            HttpServletRequest request,
            @ModelAttribute("form") MemberExchangeForm form,
            BindingResult bindingResult,
            Model model) {
        Member m = memberService.get(form.getMemberId()).orElseThrow(()->new ResourceNotFoundException("会员不存在或暂时无法访问"));
        String errMsg = "创建VIP交易记录操作失败";
        try {
            if (memberService.exchangeVIP(m.getId(), form.getIntegerLimit(), form.getEnumUnit(), form.getSerial()).orElse(false)) {
                return "redirect:/admin/member/exchange/";
            }
        } catch (Exception e) {
            errMsg = e.getMessage();
        }
        model.addAttribute("errors", errMsg);
        model.addAttribute("form", form);
        return "admin/member_exchange/create";
    }
    //指定会员的
    @GetMapping(path="/query")
    public String getMemberResult(
            @RequestParam("uid") String memberUId,
            @RequestParam(value = "p", required = false, defaultValue = "1") int page,
            HttpServletRequest request,
            Model model){
        FrontPageURL fpbuild = new FrontPageURL(request.getContextPath() + "/admin/member/exchange/query").addPageSize("number", pageSize);
        long memberId = 0L;
        if (Commons.isNotBlank(memberUId) && memberUId.startsWith("u")) {
            fpbuild = fpbuild.addParameter("uid", memberUId);
            memberId = Commons.stringToLong(memberUId.substring(1), 0L);
        }
        Pageable pr = new PageRequest(page, fpbuild.getPageSize());
        Page<MemberVipExchangeRecords> rs = (memberId > 0) ? memberVipExchangeRecordsService.getAll(memberId, pr) : memberVipExchangeRecordsService.getAll(pr);
        model.addAttribute("rs", rs.getResult().collect(Collectors.toList()));
        model.addAttribute("pageData", pr.toData(fpbuild, rs.getTotalElements()));
        return "admin/member_exchange/query_member";
    }
    //指定日期区间
    @GetMapping(path="/range")
    public String getDateRangeResult(
            @RequestParam("start") String startDateString,
            @RequestParam("end") String endDateString,
            @RequestParam(value = "p", required = false, defaultValue = "1") int page,
            HttpServletRequest request,
            Model model){
        FrontPageURL fpbuild = new FrontPageURL(request.getContextPath() + "/admin/member/exchange/range").addPageSize("number", pageSize);
        LocalDateTime start = null, end = null;
        try{
            if (Commons.isNotBlank(startDateString)) {
                start = DateTimeUtils.parseDate(startDateString);
            }
        }catch(Exception e){
            start = DateTimeUtils.getTodayEarlyMorning();
        }
        try{
            if(Commons.isNotBlank(endDateString)){
                end = DateTimeUtils.parseDate(endDateString);
            }
        }catch(Exception e){
            start = DateTimeUtils.getTodayMidnight();
        }
        fpbuild = fpbuild.addParameter("start", DateTimeUtils.getRFC3339(start));
        fpbuild = fpbuild.addParameter("end", DateTimeUtils.getRFC3339(end));
        Pageable pr = new PageRequest(page, fpbuild.getPageSize());
        Page<MemberVipExchangeRecords> rs = memberVipExchangeRecordsService.getAll(start, end, pr);
        model.addAttribute("rs", rs.getResult().collect(Collectors.toList()));
        model.addAttribute("pageData", pr.toData(fpbuild, rs.getTotalElements()));
        return "admin/member_exchange/query_range";
    }
    //手动作废交易记录
    @PostMapping(path = "/expire", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public TipMessage recycleExchangeAction(
            @RequestParam("id") long id,
            HttpServletRequest request,
            Model model) {
        return TipMessage.Builder.take(()->memberVipExchangeRecordsService.expired(id)).success("交易记录成功作废").error("操作失败");
    }
}
