package com.hotent.baseInfo.controller;

import com.hotent.base.annotation.ApiGroup;
import com.hotent.base.constants.ApiGroupConsts;
import com.hotent.base.exception.BaseException;
import com.hotent.base.model.CommonResult;
import com.hotent.base.query.PageList;
import com.hotent.baseInfo.model.AuditedUnit;
import com.hotent.baseInfo.manager.AuditedUnitManager;
import com.hotent.baseInfo.req.AuditedUnitPageReq;
import com.hotent.baseInfo.resp.AuditedUnitDetailResp;
import com.hotent.common.CrudService;
import com.hotent.constant.BaseConstant;
import com.hotent.project.model.CostAnnualPlan;
import com.hotent.project.req.CostAnnualPlanPageReq;
import com.hotent.resp.PageResp;
import com.hotent.uc.util.ContextUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;

@Api(tags = "被监审单位管理")
@RestController
@RequestMapping("/api/audited-unit")
@ApiGroup(group = {ApiGroupConsts.GROUP_COST})
public class AuditedUnitController {

    @Autowired
    private AuditedUnitManager auditedUnitManager;

    // 创建通用服务实例
    private final CrudService crudService = new CrudService();


    @GetMapping("/detail")
    @ApiOperation(value = "查询单位详情", notes = "按id查询单位详情")
    public CommonResult<AuditedUnitDetailResp> detail(@ApiParam("单位id") @RequestParam(value = "unitId", required = true) String unitId) {
        try {
            AuditedUnitDetailResp unit = auditedUnitManager.detail(unitId);

            return CommonResult.<AuditedUnitDetailResp>ok().value(unit);
        } catch (Exception e) {
            return CommonResult.<AuditedUnitDetailResp>error().message("查询失败：" + e.getMessage());
        }
    }


    @GetMapping("/list")
    @ApiOperation(value = "查询单位列表", notes = "按区域与名称过滤，上级可查看下级单位")
    public CommonResult<List<AuditedUnit>> list(
            @ApiParam("需要过滤单位id") @RequestParam(value = "unitId", required = false) String unitId) {
        try {
            return CommonResult.<List<AuditedUnit>>ok().value(auditedUnitManager.listByRegionAndName(unitId));
        } catch (Exception e) {
            return CommonResult.<List<AuditedUnit>>error().message("查询失败：" + e.getMessage());
        }
    }

    @GetMapping("/getList")
    @ApiOperation(value = "查询单位列表", notes = "按区域与名称过滤，上级可查看下级单位")
    public CommonResult<List<AuditedUnit>> getList(
            @ApiParam("需要过滤单位id") @RequestParam(value = "unitId", required = false) String unitId) {
        try {
            return CommonResult.<List<AuditedUnit>>ok().value(auditedUnitManager.getList(unitId));
        } catch (Exception e) {
            return CommonResult.<List<AuditedUnit>>error().message("查询失败：" + e.getMessage());
        }
    }

    //分页查询
    /*@PostMapping("/pageList")
    @ApiOperation(value = "分页查询pageList", notes = "分页查询pageList")
    public PageResp<AuditedUnit> page(@RequestBody AuditedUnitPageReq req) {
        try {
           return crudService.pageQuery(req, auditedUnitManager::auditUnitPage);

        } catch (Exception e) {
            throw new BaseException("查询错误");
        }
    }*/

    @PostMapping(value="/pageList")
    @ApiOperation(value="分页查询pageList",httpMethod = "POST",notes = "分页查询pageList")
    public PageList<AuditedUnit> pageList(@RequestBody AuditedUnitPageReq req) throws Exception {
        return  auditedUnitManager.pageList(req);
    }



    @PostMapping
    @ApiOperation(value = "新增单位", notes = "按表单创建被监审单位")
    public CommonResult<String> create(@Valid @RequestBody AuditedUnit unit) {
        try {
            unit.setIsDeleted(BaseConstant.NORMAL_STATUS);
            unit.setStatus(1);
            unit.setCreateTime(LocalDateTime.now());
            unit.setUpdateTime(LocalDateTime.now());
            unit.setCreateBy(ContextUtil.getCurrentUser().getAccount());
            unit.setUpdateBy(ContextUtil.getCurrentUser().getAccount());

            auditedUnitManager.create(unit);

            return CommonResult.<String>ok().message("新增成功").value(unit.getUnitId());
        } catch (Exception e) {
            return CommonResult.<String>error().message("新增失败：" + e.getMessage());
        }
    }

    @PutMapping
    @ApiOperation(value = "修改单位", notes = "编辑被监审单位信息")
    public CommonResult<String> update(@Valid @RequestBody AuditedUnit unit) {
        try {
            unit.setUpdateTime(LocalDateTime.now());
            unit.setUpdateBy("system");
            //子单位不能包含自己
            if(unit.getRelatedUnits().contains(unit.getUnitId())){
                throw new BaseException("子单位不能包含自己");
            }
            auditedUnitManager.update(unit);
            return CommonResult.<String>ok().message("修改成功");
        } catch (Exception e) {
            return CommonResult.<String>error().message("修改失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除单位", notes = "逻辑删除")
    public CommonResult<String> delete(@PathVariable("id") String id) {
        try {
            boolean ok = auditedUnitManager.deleteLogical(id);
            return ok ? CommonResult.<String>ok().message("删除成功") : CommonResult.<String>error().message("删除失败");
        } catch (Exception e) {
            return CommonResult.<String>error().message("删除失败：" + e.getMessage());
        }
    }

    @PatchMapping("/{id}/status")
    @ApiOperation(value = "启用/停用", notes = "企业账号启用/停用")
    public CommonResult<String> toggleStatus(@PathVariable("id") String id,
                                             @ApiParam("true启用 false停用") @RequestParam("enable") Integer enable) {
        try {
            boolean ok = auditedUnitManager.toggleStatus(id, enable);
            return ok ? CommonResult.<String>ok().message(enable==1 ? "已启用" : "已停用")
                    : CommonResult.<String>error().message("状态更新失败");
        } catch (Exception e) {
            return CommonResult.<String>error().message("状态更新失败：" + e.getMessage());
        }
    }
}


