package com.repair.controller;


import com.repair.api.RepairSchoolControllerAPI;
import com.repair.common.utils.paramUtils;
import com.repair.model.pojo.RepairSchool;
import com.repair.model.result.CommonResult;
import com.repair.model.result.PageUtils;
import com.repair.services.RepairSchoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2023-07-12
 */
@RestController
public class RepairSchoolController implements RepairSchoolControllerAPI {

    @Autowired
    private RepairSchoolService repairSchoolService;

    /**
     * 新增校区数据
     * @param repairSchool 校区数据
     * @param bindingResult 是否为空判断
     * @return
     */
    @Override
    public CommonResult InsertRepairSchool(RepairSchool repairSchool, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }
        int result = 0;
        try {
            result = repairSchoolService.insertRepairSchool(repairSchool);
        } catch (Exception e) {
            if (e.getCause().getMessage().contains("'repair_school.name_unique'")) {
                return CommonResult.fail("该校区名称已存在！");
            }
            return CommonResult.fail("系统异常，用户数据添加失败！");
        }

        return result > 0 ? CommonResult.ok("添加成功") : CommonResult.fail("添加失败");
    }

    /**
     * 更新校区数据
     * @param ra 校区数据
     * @param bindingResult 是否为空判断
     * @return
     */
    @Override
    public CommonResult updateRepairSchoolById(RepairSchool ra, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }
        int result = repairSchoolService.updateRepairSchool(ra);

        return result > 0 ? CommonResult.ok("修改成功") : CommonResult.fail("修改失败");
    }

    /**
     * 校区分页数据查询
     * @param currentPage 当前页数
     * @param pageCount 一页数据条数
     * @param name 查询名称
     * @return
     */
    @Override
    public CommonResult queryPageRepairSchools(int currentPage, int pageCount, String name) {
        PageUtils<RepairSchool> result = repairSchoolService.queryPageRepairSchools(currentPage, pageCount, name);
        return CommonResult.ok(result);
    }

    /**
     * 根据数据ID删除校区数据
     * @param id 数据ID
     * @return
     */
    @Override
    public CommonResult deleteRepairSchoolById(int id) {
        RepairSchool data = repairSchoolService.getRepairById(id);
        if (data == null) {
            return CommonResult.fail("当前数据不存在，删除失败！");
        }

        int result = repairSchoolService.deleteRepairSchoolById(id);

        return result > 0 ? CommonResult.ok("删除成功") : CommonResult.fail("删除失败");
    }
}

