package com.xdap.self_development.controller;

import com.definesys.mpaas.common.http.Response;
import com.definesys.mpaas.query.db.PageQueryResult;
import com.xdap.api.moudle.department.pojo.entity.XdapDepartments;
import com.xdap.api.moudle.user.pojo.XdapUsers;
import com.xdap.self_development.common.BusinessDatabase;
import com.xdap.self_development.common.MyResponse;
import com.xdap.self_development.controller.form.*;
import com.xdap.self_development.domain.pojo.ResponsiblePersonPojo;
import com.xdap.self_development.domain.view.DepartmentUserView;
import com.xdap.self_development.exception.CommonException;
import com.xdap.self_development.service.ResponsiblePersonService;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 责任人控制器
 * 提供责任人管理相关的功能，包括责任人导入导出、查询、保存、修改、删除等
 *
 * @version 1.0
 * @since 2025
 */
@RestController
@RequestMapping("/custom/responsible")
public class ResponsiblePersonController {
    @Resource
    private BusinessDatabase bd;
    @Resource
    private ResponsiblePersonService responsiblePersonService;

    /*
     * 获取责任部门
     *
     * */
    @GetMapping("/getResponsibleDepartment")
    public Response getResponsibleDepartment() {
        return Response.ok().data(responsiblePersonService.getResponsibleDepartment());
    }

    /**
     * 导入责任人
     *
     * @param file   文件
     * @param userId 用户ID
     * @return 操作结果响应
     */
    @PostMapping("/import")
    public Response importPerson(
            @RequestPart("file") MultipartFile file,
            @RequestPart("userId") String userId
    ) {
        MyResponse templateImportView = responsiblePersonService.importPerson(file, userId);
        if (templateImportView.isFlag()) {
            return Response.error("导入异常").data(templateImportView);
        } else {
            return Response.ok().setMessage("导入成功");
        }
    }

    /**
     * 导出责任人
     *
     * @param response HTTP响应
     */
    @GetMapping("/export")
    public void exportPerson(
            HttpServletResponse response
    ) {
        responsiblePersonService.exportPerson(response);
    }

    /**
     * 获取导入模板
     *
     * @param response HTTP响应
     */
    @GetMapping("/getImportTemplate")
    public void getImportTemplate(
            HttpServletResponse response
    ) {
        responsiblePersonService.exportVoidPerson(response);
    }

    /**
     * 判断是否为责任人
     *
     * @param userId 用户ID
     * @return 是否为责任人的判断结果
     */
    @GetMapping("/isResponsiblePerson")
    public Response isResponsiblePerson(
            @NotBlank String userId
    ) {
        return Response.ok().data(responsiblePersonService.isResponsiblePerson(userId));
    }

    /**
     * 查询所有部门责任人
     *
     * @param form          部门责任人页面表单
     * @return 部门责任人分页查询结果
     */
    @GetMapping("/getDeptResponsible")
    public Response getDeptResponsible(
            @Valid DeptResponsiblePageForm form,
            BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            bindingResult.getFieldErrors().forEach(error -> {
                throw new CommonException(error.getDefaultMessage());
            });
        }
        PageQueryResult<ResponsiblePersonPojo> deptResponsible =
                responsiblePersonService.getDeptResponsible(form);
        return Response.ok().data(deptResponsible);
    }

    /**
     * 查询所有部门填写人
     *
     * @param form          部门责任人页面表单
     * @return 部门填写人分页查询结果
     */
    @GetMapping("/getDeptFilled")
    public Response getDeptFilled(
            @Valid DeptResponsiblePageForm form,
            BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            bindingResult.getFieldErrors().forEach(error -> {
                throw new CommonException(error.getDefaultMessage());
            });
        }
        PageQueryResult<ResponsiblePersonPojo> deptResponsible =
                responsiblePersonService.getDeptFilled(form);
        return Response.ok().data(deptResponsible);
    }

    /**
     * 根据部门id获取子部门
     *
     * @param departmentId 部门ID
     * @return 子部门列表
     */
    @GetMapping("/getSubDepartmentById")
    public Response getSubDepartmentById(
            @RequestParam(defaultValue = "") String departmentId
    ) {
        List<XdapDepartments> xdapDepartments;
        if (departmentId == null || departmentId.isEmpty()) {
            xdapDepartments = bd.getSystemDatabase()
                    .eq("level", 1)
                    .eq("status", "ENABLE")
                    .doQuery(XdapDepartments.class);
        } else {
            xdapDepartments = bd.getSystemDatabase()
                    .eq("parent_id", departmentId)
                    .eq("status", "ENABLE")
                    .doQuery(XdapDepartments.class);
        }

        return Response.ok().data(xdapDepartments);
    }

    /**
     * 根据部门id获取部门的用户
     *
     * @param form 部门用户表单
     * @return 部门用户视图列表
     */
    @GetMapping("/getUserByDepartmentId")
    public Response getUserByDepartmentId(
            @Valid DepartmentUserForm form
    ) {
        List<DepartmentUserView> responsiblePeoples = bd.getSystemDatabase()
                .viewQueryMode(true)
                .view("getUserByDepartment")
                .setVar("departmentId", form.getDepartmentId())
                .like("username", form.getKey())
                .doQuery(DepartmentUserView.class);
        return Response.ok().data(responsiblePeoples);
    }

    /**
     * 获取全部子系统名
     *
     * @return 子系统名称集合
     */
    @GetMapping("/getAllSubsystem")
    public Response getAllSubsystem() {
        Set<String> set = responsiblePersonService.getAllSubsystem();
        return Response.ok().data(set);
    }

    /**
     * 保存部门责任人
     *
     * @param form          责任人表单
     * @return 操作结果响应
     */
    @PostMapping("/saveResponsiblePerson")
    public Response saveResponsiblePerson(
            @Valid @RequestBody ResponsiblePersonForm form,
            BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            bindingResult.getFieldErrors().forEach(error -> {
                throw new CommonException(error.getDefaultMessage());
            });
        }
        responsiblePersonService.saveResponsiblePerson(form);
        return Response.ok().setMessage("添加成功");
    }

    /**
     * 保存部门填写人
     *
     * @param form          填写人表单
     * @return 操作结果响应
     */
    @PostMapping("/saveFilledPerson")
    public Response saveFilledPerson(
            @Valid @RequestBody FilledPersonForm form,
            BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            bindingResult.getFieldErrors().forEach(error -> {
                throw new CommonException(error.getDefaultMessage());
            });
        }
        responsiblePersonService.saveFilledPerson(form);
        return Response.ok().setMessage("添加成功");
    }

    /**
     * 修改部门责任人
     *
     * @param form          更新责任人表单
     * @return 操作结果响应
     */
    @PostMapping("/updateResponsiblePerson")
    public Response updateResponsiblePerson(
            @Valid @RequestBody UpdateResponsiblePersonForm form,
            BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            bindingResult.getFieldErrors().forEach(error -> {
                throw new CommonException(error.getDefaultMessage());
            });
        }

        responsiblePersonService.updateResponsiblePerson(form);
        return Response.ok().setMessage("添加成功");
    }

    /**
     * 修改部门填写人
     *
     * @param form          更新填写人表单
     * @return 操作结果响应
     */
    @PostMapping("/updateFilledPerson")
    public Response updateFilledPerson(
            @Valid @RequestBody UpdateFilledPersonForm form,
            BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            bindingResult.getFieldErrors().forEach(error -> {
                throw new CommonException(error.getDefaultMessage());
            });
        }

        responsiblePersonService.updateFilledPerson(form);
        return Response.ok().setMessage("添加成功");
    }

    /**
     * 删除部门责任人
     *
     * @param rowId 行ID
     * @return 操作结果响应
     */
    @GetMapping("/deleteResponsiblePerson")
    public Response deleteResponsiblePerson(
            @NotBlank @RequestParam String rowId
    ) {
        responsiblePersonService.deleteResponsiblePerson(rowId);
        return Response.ok();
    }
    /**
     * 查询部门责任人
     *
     * @param deptName   部门名称
     * @param subsystem 子系统
     * @return 部门用户列表
     */
    @GetMapping("/getUserBydepartment")
    public Response getUserBydepartment(
           @RequestParam("deptName")String deptName,@RequestParam("subsystem")String subsystem
    ) {
        ArrayList<XdapUsers> userBydepartment = responsiblePersonService.getUserBydepartment(deptName, subsystem);
        return Response.ok().data(userBydepartment);
    }
}
