package com.ruoyi.web.controller.dz;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ValidationException;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.enums.BoolValues;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.dz.domain.DzClasses;
import com.ruoyi.dz.service.IDzClassesService;
import com.ruoyi.dz.service.impl.DzClassesServiceImpl;
import com.ruoyi.enums.UserTypeEnum;
import com.ruoyi.system.domain.SysArea;
import com.ruoyi.system.service.ISysAreaService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.dz.domain.DzSchool;
import com.ruoyi.dz.service.IDzSchoolService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 机构校区Controller
 *
 * @author ruoyi
 * @date 2025-09-12
 */
@RestController
@RequestMapping("/dz/school")
public class DzSchoolController extends BaseController
{
    @Autowired
    private IDzSchoolService dzSchoolService;
    @Autowired
    private ISysAreaService areaService;
    @Autowired
    private IDzClassesService classesService;

    /**
     * 查询机构校区列表
     */
    @PreAuthorize("@ss.hasPermi('dz:school:list')")
    @GetMapping("/list")
    public TableDataInfo list(DzSchool dzSchool)
    {
//        if (null==dzSchool.getDeptId()){
//            dzSchool.setDeptId(getLoginUser().getDeptId());
//        }
//        if(!UserTypeEnum.Sys.getVal().equals(SecurityUtils.getLoginUser().getUser().getUserType())) {
//            dzSchool.setCampus(true);
//        }else {
//            dzSchool.setCampus(false);
//        }
        startPage();
        List<DzSchool> list= dzSchoolService.selectDzSchoolList(dzSchool);
        //处理省市区
        List<Long> areaIds = list.stream()
                .flatMap(school -> Stream.of(
                        school.getPro(),school.getCity(),school.getArea()
                ))
                .filter(Objects::nonNull).distinct().collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(areaIds)){
            Map<Long, SysArea> areaMap = areaService.selectSysAreaListByIds(areaIds)
                    .stream().collect(Collectors.toMap(SysArea::getAreaId,area -> area));
            list.forEach(school -> {
                StringBuilder proCityAreaName = new StringBuilder();
                if (null!=school.getPro()&&areaMap.containsKey(school.getPro())){
                    proCityAreaName.append(areaMap.get(school.getPro()).getAreaName());
                }
                if (null!=school.getCity()&&areaMap.containsKey(school.getCity())){
                    proCityAreaName.append(areaMap.get(school.getCity()).getAreaName());
                }
                if (null!=school.getArea()&&areaMap.containsKey(school.getArea())){
                    proCityAreaName.append(areaMap.get(school.getArea()).getAreaName());
                }
                if (StringUtils.isNotEmpty(proCityAreaName.toString())){
                    school.setProCityAreaName(proCityAreaName.toString());
                }
            });
        }

        return getDataTable(list);
    }

    @GetMapping("/getCampusSchoolList")
    public AjaxResult getCampusSchoolList(DzSchool dzSchool)
    {
        if(null == dzSchool.getCampus() && !UserTypeEnum.isSys(SecurityUtils.getLoginUser().getUser().getUserType())) {
            dzSchool.setCampus(true);
        }
        List<DzSchool> list = dzSchoolService.selectDzSchoolList(dzSchool);
        return AjaxResult.success(list);
    }

//    @GetMapping("/getSchoolList")
//    public AjaxResult getSchoolList(DzSchool dzSchool)
//    {
//        if(!UserTypeEnum.Sys.getVal().equals(SecurityUtils.getLoginUser().getUser().getUserType())) {
//            dzSchool.setCampus(false);
//        }
//        List<DzSchool> list = dzSchoolService.selectDzSchoolList(dzSchool);
//        return AjaxResult.success(list);
//    }

    @GetMapping("/getSchoolList")
    public AjaxResult getSchoolList(DzSchool dzSchool)
    {
//        if(!UserTypeEnum.Sys.getVal().equals(SecurityUtils.getLoginUser().getUser().getUserType())) {
//            dzSchool.setCampus(true);
//        }else {
//            dzSchool.setCampus(false);
//        }
        List<DzSchool> list = dzSchoolService.selectDzSchoolList(dzSchool);
        return AjaxResult.success(list);
    }

    /**
     * 导出机构校区列表
     */
    @PreAuthorize("@ss.hasPermi('dz:school:export')")
    @Log(title = "机构校区", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DzSchool dzSchool)
    {
        List<DzSchool> list = dzSchoolService.selectDzSchoolList(dzSchool);
        ExcelUtil<DzSchool> util = new ExcelUtil<DzSchool>(DzSchool.class);
        util.exportExcel(response, list, "机构校区数据");
    }

    /**
     * 获取机构校区详细信息
     */
    @PreAuthorize("@ss.hasPermi('dz:school:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(dzSchoolService.selectDzSchoolById(id));
    }

    /**
     * 新增机构校区
     */
    @PreAuthorize("@ss.hasPermi('dz:school:add')")
    @Log(title = "机构校区", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DzSchool dzSchool)
    {
        int id = dzSchoolService.insertDzSchool(dzSchool);
        //创建学校时，如果没有班级则默认创建30个班级
        for (int i = 0; i < 30; i++) {
            DzClasses dzClass = new DzClasses();
            dzClass.setSchoolId(Long.valueOf(id));
            dzClass.setName( String.valueOf(i + 1));
            dzClass.setIsDefault(BoolValues.yes.getValue());
            dzClass.setOnline(BoolValues.yes.getValue());
            dzClass.setStatus(BoolValues.yes.getValue());
            classesService.insertDzClasses(dzClass);
        }
        return toAjax(id);
    }

    /**
     * 修改机构校区
     */
    @PreAuthorize("@ss.hasPermi('dz:school:edit')")
    @Log(title = "机构校区", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DzSchool dzSchool)
    {
        return toAjax(dzSchoolService.updateDzSchool(dzSchool));
    }

    /**
     * 删除机构校区
     */
    @PreAuthorize("@ss.hasPermi('dz:school:remove')")
    @Log(title = "机构校区", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(dzSchoolService.deleteDzSchoolByIds(ids));
    }
}
