package com.yida.data.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yida.data.common.core.common.ResultBean;
import com.yida.data.common.core.entity.system.Dept;
import com.yida.data.common.core.entity.system.EduDeptWxPublic;
import com.yida.data.common.core.entity.system.EduHotWord;
import com.yida.data.common.core.entity.system.EduLabel;
import com.yida.data.system.dto.FindSchoolPageListDTO;
import com.yida.data.system.dto.SchoolInformationDTO;
import com.yida.data.system.dto.SchoolPageDTO;
import com.yida.data.system.mapper.EduDeptWxPublicMapper;
import com.yida.data.system.service.EduLabelService;
import com.yida.data.system.service.IDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Slf4j
@Validated
@Api(tags = "部门管理（无鉴权）")
@RestController
@RequestMapping("/in/dept")
@RequiredArgsConstructor
public class InDeptController {

    private final IDeptService deptService;
    private final EduDeptWxPublicMapper eduDeptWxPublicMapper;
    private final EduLabelService labelService;

    @ApiOperation("根据corpId查询学校id")
    @GetMapping("/getSchoolByCorp")
    public ResultBean<Dept> getSchoolByCorp(@RequestParam String corpId) {
        return ResultBean.buildSuccess(
            deptService.getOne(Wrappers.lambdaQuery(new Dept()).eq(Dept::getCorpId, corpId).eq(Dept::getDeptType, 0)));
    }

    @ApiOperation("获取父部门")
    @GetMapping("/getParentById")
    public ResultBean<Dept> getParentById(Long id) {
        return ResultBean.buildSuccess(deptService.getParentById(id));
    }

    @ApiOperation("向下获取包含的班级id")
    @GetMapping("/listClassByDept")
    public ResultBean<List<Long>> listClassByDept(Long[] ids) {
        return ResultBean.buildSuccess(deptService.listClassByDept(new ArrayList<>(Arrays.asList(ids))));
    }

    @GetMapping("/getInfoById")
    public ResultBean<Dept> getInfoById(Long deptId) {
        return ResultBean.buildSuccess(deptService.getById(deptId));
    }

    @GetMapping("/getSchoolByName")
    public ResultBean<Dept> getSchoolByName(String schoolName) {
        return ResultBean.buildSuccess(deptService
            .getOne(Wrappers.lambdaQuery(new Dept()).eq(Dept::getDeptName, schoolName)));
    }

    /**
     * 获取学校下属部门（非家校部门）
     */
    @GetMapping("/getDeptBySchoolAndName")
    public ResultBean<Dept> getDeptBySchoolAndName(Long schoolId, String deptName) {
        return ResultBean.buildSuccess(deptService.getDeptBySchoolAndName(Arrays.asList(schoolId), deptName));
    }

    @ApiOperation("根据学校与微信id查询班级信息")
    @GetMapping("/getClassBySchoolAndWx")
    public ResultBean<Dept> getClassBySchoolAndWx(Long schoolId, Long classWxId) {
        return ResultBean.buildSuccess(deptService.getClassBySchoolAndWx(
            schoolId, classWxId));
    }

    @ApiOperation("根据学校类型查询学校")
    @GetMapping("/listSchoolBySchoolType")
    public ResultBean<List<Dept>> listSchoolBySchoolType(@RequestParam("schoolType") String schoolType) {
        return ResultBean.buildSuccess(deptService.list(Wrappers.<Dept>lambdaQuery()
            .eq(Dept::getDeptType, 0)
            .like(Dept::getSchoolType, schoolType)));
    }

    @ApiOperation("同步企业微信部门")
    @GetMapping("/syncQywxDept")
    public ResultBean syncQywxDept() {
        log.info("进入同步企业微信");
        deptService.syncQywxDept(null);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("同步指定学校企业微信部门")
    @GetMapping("/syncSchoolDept")
    public ResultBean<String> syncSchoolDept(@RequestParam Long schoolId) {
        log.info("同步企业微信部门数据: schoolId: [{}]", schoolId);
        deptService.syncQywxDept(schoolId);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("处理挂载在学校下的部门")
    @GetMapping("/dealNoParentDept")
    public ResultBean dealNoParentDept() {
        deptService.dealNoParentDept();
        return ResultBean.buildSuccess();
    }

    @ApiOperation("查询学校部门")
    @GetMapping("/getDeptBySchoolAndWxId")
    ResultBean<Dept> getDeptBySchoolAndWxId(@RequestParam("schoolId") Long schoolId,
        @RequestParam("wxId") Long wxId) {
        return ResultBean.buildSuccess(deptService.getSysDeptByDeptAndWx(Arrays.asList(schoolId), wxId));
    }

    @ApiOperation("查询学校列表")
    @PostMapping("/listDept")
    ResultBean<List<Dept>> listDept(@RequestBody List<Long> ids) {
        return ResultBean.buildSuccess(deptService.listByIds(ids));
    }

    @ApiOperation("根据公众号id查询学校")
    @GetMapping("/getSchoolByAppId")
    public ResultBean<Dept> getSchoolByAppId(String appId) {
        Dept school = null;
        EduDeptWxPublic deptWxPublic = eduDeptWxPublicMapper.selectOne(Wrappers.<EduDeptWxPublic>lambdaQuery()
            .eq(EduDeptWxPublic::getAppId, appId));
        if (deptWxPublic != null) {
            school = deptService.getById(deptWxPublic.getDeptId());
        }
        return ResultBean.buildSuccess(school);
    }

    @ApiOperation("查询教育局，代理商下面学校")
    @GetMapping("/findSchoolListByDeptId")
    public ResultBean<Page<SchoolInformationDTO>> findSchoolListByDeptId(
        @RequestParam(required = false) @ApiParam("学校类型") Integer schoolType,
        @RequestParam(required = false) @ApiParam("学校性质") Integer natureType,
        @RequestParam(required = false) @ApiParam("公立，民办") Integer schoolOwnership,
        @RequestParam(required = false) @ApiParam("学校名称") String schoolName,
        @RequestParam(required = false) @ApiParam("区域id") String address,
        @RequestParam(required = false) @ApiParam("标签") String label,
        @RequestParam(required = false) @ApiParam("部门id") Long deptId,
        @RequestParam(required = false, defaultValue = "1") Integer pageNum,
        @RequestParam(required = false, defaultValue = "10") Integer pageSize) {

        Page<SchoolInformationDTO> page = new Page();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        return ResultBean.buildSuccess(deptService
            .findSchoolListByDeptId(deptId, schoolName, schoolType, natureType, address, label, page, schoolOwnership));
    }

    @ApiOperation("新增或编辑教育局/代理商与学校关联关系")
    @PostMapping("/saveOrUpdateDeptSchool")
    public ResultBean saveOrUpdateDeptSchool(@RequestBody SchoolInformationDTO information) {

        deptService.saveOrUpdateDeptSchool(information);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("条件查询学校(入学早知道学校查询)")
    @PostMapping("/findSchoolPageList")
    public ResultBean<Page<SchoolInformationDTO>> findSchoolPageList(@RequestBody FindSchoolPageListDTO dto) {

        Page<SchoolInformationDTO> page = new Page();
        page.setCurrent(dto.getPageNum());
        page.setSize(dto.getPageSize());
        return ResultBean.buildSuccess(deptService
            .findSchoolPageList(dto.getSchoolName(), dto.getSchoolType(), dto.getNatureType(), page, dto.getTag(),
                dto.getDeptId(), dto.getSchoolOwnership()));
    }

    @ApiOperation("根据名称和类型查询教育局学校列表")
    @PostMapping("/listSchoolPage")
//    @Cacheable(value = CachePrefixConstant.SCHOOL_LIST_SEARCH, key = "#dto.deptId + '-' + #dto.schoolName")
    public ResultBean<IPage<SchoolInformationDTO>> listSchoolPage(@RequestBody SchoolPageDTO dto) {
        IPage<SchoolInformationDTO> page = deptService.listSchoolPage(dto);
        return ResultBean.buildSuccess(page);
    }

    @ApiOperation("根据住所查询对应可读学校")
    @GetMapping("/findSchoolByAddress")
    public ResultBean<Page<SchoolInformationDTO>> findSchoolByAddress(
        @RequestParam(required = false) @ApiParam("住所") String address,
        @RequestParam(required = false) @ApiParam("教育局id或代理商id") Long deptId,
        @RequestParam(required = false, defaultValue = "1") Integer pageNum,
        @RequestParam(required = false, defaultValue = "10") Integer pageSize) {

        Page<SchoolInformationDTO> page = new Page();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        return ResultBean.buildSuccess(deptService.findSchoolByAddress(page, address, deptId));
    }

    @ApiOperation("查询所有标签")
    @GetMapping("/findDeptLabelList")
    public ResultBean<Page<EduLabel>> findDeptLabelList(@RequestParam(required = false) @ApiParam("部门id") Long deptId,
        @RequestParam(required = false) @ApiParam("标签") String label,
        @RequestParam(required = false) @ApiParam("1为教育局对应下属学校标签，2为学校对应招生政策标签,3为入学咨询标签") Integer type,
        @RequestParam(required = false, defaultValue = "1") Integer pageNum,
        @RequestParam(required = false, defaultValue = "10") Integer pageSize) {

        Page<EduLabel> page = new Page();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        return ResultBean.buildSuccess(deptService.findDeptLabelList(page, deptId, type, label));
    }

    @ApiOperation("新建或修改标签")
    @PostMapping("/saveOrUpdateLabel")
    public ResultBean saveOrUpdateLabel(@RequestBody EduLabel label) {
        label.setType(2);
        List<EduLabel> list = labelService.list(Wrappers.query(new EduLabel()).lambda().eq(EduLabel::getLabel, label.getLabel())
            .eq(EduLabel::getDeptId, label.getDeptId()).eq(EduLabel::getType, label.getType()));
        if (CollectionUtil.isNotEmpty(list)) {
            return ResultBean.buildError("已有该标签请勿重复创建");
        }
        deptService.saveOrUpdateLabel(label);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("删除标签")
    @GetMapping("/removeLabel")
    public ResultBean removeLabel(@RequestParam Long id) {
        deptService.removeLabel(id);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("查询热门词汇")
    @GetMapping("/findHotWord")
    public ResultBean<List<EduHotWord>> findHotWord(
        @RequestParam(defaultValue = "1", required = false) @ApiParam("词汇类型：1-学校招生范围，默认1") Integer type,
        @RequestParam(required = false) @ApiParam("部门id") Long deptId,
        @RequestParam(defaultValue = "10", required = false) @ApiParam("返回数量：默认10") Integer num) {

        return ResultBean.buildSuccess(deptService.findHotWord(num, type, deptId));
    }


    @ApiOperation("查询父级部门集合")
    @PostMapping("/findParentDeptByChilds")
    public ResultBean<List<Dept>> findParentDeptByChilds(@RequestBody List<Long> deptIds) {
        return ResultBean.buildSuccess(deptService.findParentDeptByChild(deptIds));
    }


    @ApiOperation("获取部门树")
    @PostMapping("/getDeptTree")
    public ResultBean<List> getDeptTree(@RequestBody List<Long> deptIds) {
        return ResultBean.buildSuccess(deptService.getDeptTree(deptIds));
    }


}
