package com.jeequan.jeepay.mch.ctrl.merchant;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.PackageInfo;
import com.jeequan.jeepay.db.entity.PackageOrder;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/packageInfo")
public class PackageInfoController extends CommonCtrl {

    @Autowired private PackageInfoService packageInfoService;
    @Autowired private PackageProductService packageProductService;
    @Autowired private ProductInfoService productInfoService;
    @Autowired private PackageOrderService packageOrderService;
    @Autowired private PackageTypeService packageTypeService;

    @RequestMapping(value = "/getPackageList", method = RequestMethod.GET)
    @MethodLog(remark = "方案中心列表")
    public ApiRes getPackageList() throws BizException {
        PackageInfo packageInfo = getObject(PackageInfo.class);
        Page<PackageInfo> page = new Page<>();
        List<PackageInfo> packageInfoList = packageInfoService.getPackageList(packageInfo.getName(),packageInfo.getState(),packageInfo.getPackageType());
        page.setRecords(packageInfoList);
        page.setTotal(packageInfoList.size());
        page.setCurrent(1);
        return ApiRes.ok(page);
    }

    @RequestMapping(value = "/getPackageById", method = RequestMethod.GET)
    @MethodLog(remark = "商户端方案详情")
    public ApiRes getPackageById() throws BizException {
        //获取查询条件
        PackageInfo packageInfo = getObject(PackageInfo.class);
        PackageInfo info  = packageInfoService.getPackageById(packageInfo.getPackageId());
        //查询已关联已开通的应用数量，
        List<PackageOrder> packageOrderList = packageOrderService.getList(packageInfo.getPackageId(),getCurrentMchNo());
        List<String> bindingApp = packageOrderList.stream().map(PackageOrder::getAppId).filter(str-> !str.isEmpty()).distinct().collect(Collectors.toList());
        info.setApplyCount(packageOrderList.size());
        info.setBindingAppList(bindingApp);
        //返回收费信息和剩余天数
        List<PackageOrder> packageOrderListSave =new ArrayList<>();
        long allRemainingDays = 0L;
        for (PackageOrder packageOrder : packageOrderList) {
            if (packageOrder.getCostRule() != null){
                JSONArray costRule = packageOrder.getCostRule();
                //目前规则只能选取一条
                int validTime = costRule.getJSONObject(0).getIntValue("validTime");
                if (costRule.getJSONObject(0).getDate("autoTime") != null){
                    LocalDate currentDate = costRule.getJSONObject(0).getDate("autoTime").toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    // 计算到期后的日期
                    LocalDate futureDate = currentDate.plusDays(validTime);
                    // 计算剩余天数
                    LocalDate today = new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    long remainingDays = ChronoUnit.DAYS.between(today, futureDate);
                    packageOrder.setRemainingDays(remainingDays);
                    //暂时不需要
                    //productAppListSave.add(productApp);
                    allRemainingDays += remainingDays;
                }
            }
        }
        //暂时不需要
        //info.setProductAppList(productAppListSave);
        info.setAllRemainingDays(allRemainingDays);
        return ApiRes.ok(info);
    }


    @GetMapping("/getPackageOder")
    @MethodLog(remark = "开通记录")
    public ApiRes getPackageOder(){
        Page<PackageOrder> page=getIPage(true);
        PackageOrder packageOrder = getObject(PackageOrder.class);
        // 时间搜索
        Date[] searchDateRange = packageOrder.buildQueryDateRange();
        packageOrder.setFirstDate(searchDateRange[0]);
        packageOrder.setLastDate(searchDateRange[1]);
        packageOrder.setMchNo(getCurrentMchNo());
        Page<PackageOrder> result = packageOrderService.getList(page, packageOrder);
        return ApiRes.ok(result);
    }

    @RequestMapping(value = "/getPackageOderById", method = RequestMethod.GET)
    @MethodLog(remark = "开通记录详情")
    public ApiRes getPackageOderById() throws BizException {
        //获取查询条件
        PackageOrder packageOrder = getObject(PackageOrder.class);
        PackageOrder serviceById = packageOrderService.getDetail(packageOrder.getId());
        return ApiRes.ok(serviceById);
    }

    @MethodLog(remark = "更新开通记录")
    @RequestMapping(value="/{id}", method = RequestMethod.PUT)
    public ApiRes reSubmit(@PathVariable("id") String id) {
        PackageOrder packageOrder = getObject(PackageOrder.class);
        packageOrder.setId(id);//设置主键
        packageOrder.setUpdatedAt(new Date());
        packageOrder.setState(PackageOrder.STATE_AUDITING);
        packageOrderService.updateById(packageOrder);
        return ApiRes.ok();
    }

    @RequestMapping(value = "/getPackageTypeList", method = RequestMethod.GET)
    @MethodLog(remark = "获取所有方案分类列表")
    public ApiRes getPackageTypeList() throws BizException {
        return ApiRes.ok(packageTypeService.list());
    }

}
