package quant.rich.emoney.controller.manage;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import lombok.extern.slf4j.Slf4j;
import quant.rich.emoney.controller.common.BaseController;
import quant.rich.emoney.entity.sqlite.Plan;
import quant.rich.emoney.exception.RException;
import quant.rich.emoney.pojo.dto.LayPageReq;
import quant.rich.emoney.pojo.dto.LayPageResp;
import quant.rich.emoney.pojo.dto.R;
import quant.rich.emoney.service.sqlite.PlanService;

@Slf4j
@Controller
@RequestMapping("/admin/v1/manage/plan")
public class PlanControllerV1 extends BaseController {
    
    @Autowired
    PlanService planService;
    
    @GetMapping({"", "/", "/index"})
    public String index() {
        return "/admin/v1/manage/plan/index";
    }
	
	@GetMapping("/list")
	@ResponseBody
	public LayPageResp<?> list(LayPageReq<Plan> pageReq) {
	    Page<Plan> planPage = planService.page(pageReq);
	    return new LayPageResp<>(planPage);
	}
	
	@GetMapping("/getOne")
	@ResponseBody
	public R<?> getOne(String planId) {
	    
	    // 如果 planId 是空，说明可能希望新建一个 Plan，需要返回默认实例化对象
	    if (planId == null) {
	        return R.ok(new Plan());
	    }
	    
	    // 否则从数据库取
	    Plan plan = planService.getById(planId);
	    return R.judge(plan != null, plan, "无法找到对应 ID 的 Plan");
	}
	
	@PostMapping("/updateEnabledStatus")
	@ResponseBody
	public R<?> updateEnabledStatus(String planId, Boolean enabled) {
	    if (planService.update(new LambdaUpdateWrapper<Plan>()
	            .eq(Plan::getPlanId, planId)
	            .set(Plan::getEnabled, enabled))) {
	        return R.ok();
	    }
	    throw RException.badRequest();
	}
	
	@PostMapping("/updateBool")
	@ResponseBody
	public R<?> updateBool(String planId, String field, Boolean value) {
	    TableInfo tableInfo = TableInfoHelper.getTableInfo(Plan.class);
	    try {
	        Field declaredField = Plan.class.getDeclaredField(field);

	        Optional<TableFieldInfo> fieldInfo = tableInfo.getFieldList().stream()
	                .filter(f -> f.getProperty().equals(field))
	                .findFirst();
	        if (declaredField.getType().equals(Boolean.class)) {
	            planService.update(
                    new UpdateWrapper<Plan>()
                        .eq("plan_id", planId)
                        .set(fieldInfo.get().getColumn(), value));
	            return R.ok();
	        }
	    }
	    catch (Exception e) {}
        throw RException.badRequest();
	}
	
	@PostMapping("/save")
	@ResponseBody
	public R<?> save(@RequestBody Plan plan) {
	    if (StringUtils.isNotBlank(plan.getPlanId())) {
	        planService.updateById(plan);
	    }
	    else {
	        planService.save(plan.setPlanId(null));
	    }
	    return R.ok();
	}
	
	@PostMapping("/delete")
	@ResponseBody
	public R<?> delete(String planId) {
	    return R.judge(planService.removeById(planId), "删除失败，是否已删除？");
	}
	
	@PostMapping("/batchOp")
    @ResponseBody
    public R<?> batchOp(
            @RequestParam(value="ids[]", required=true)
            String[] ids, String op) {
        if (Objects.isNull(ids) || ids.length == 0) {
            throw RException.badRequest("提供的计划 ID 不能为空");
        }
        List<String> idArray = Arrays.asList(ids);
        
        if (StringUtils.isBlank(op)) {
            // op 为空是删除
            return R.judge(
                    planService.removeBatchByIds(idArray));
        }
        
        LambdaUpdateWrapper<Plan> uw = new LambdaUpdateWrapper<>();
        uw.in(Plan::getPlanId, idArray);
        
        if ("enable".equals(op)) {
            uw.set(Plan::getEnabled, true);
        }
        else if ("disable".equals(op)) {
            uw.set(Plan::getEnabled, false);
        }
        else if ("enableOpenDayCheck".equals(op)) {
            uw.set(Plan::getOpenDayCheck, true);
        }
        else if ("disableOpenDayCheck".equals(op)) {
            uw.set(Plan::getOpenDayCheck, false);
        }
        else {
            throw RException.badRequest("未识别的操作");
        }
        
        return R.judge(planService.update(uw));
    }

}
