package com.ruoyi.web.controller.dz;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.dz.domain.DzSchool;
import com.ruoyi.dz.service.IDzSchoolService;
import com.ruoyi.enums.UserTypeEnum;
import com.ruoyi.system.domain.SysArea;
import com.ruoyi.system.service.ISysAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

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

    /**
     * 查询机构校区列表
     */
    // @PreAuthorize("@ss.hasPermi('dz:campus:list')")
    @GetMapping("/list")
    public TableDataInfo list(DzSchool dzSchool)
    {
        dzSchool.setCampus(true);
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if(!UserTypeEnum.isSys(sysUser.getUserType())) {
            dzSchool.setDeptId(SecurityUtils.getDeptId());
            if (UserTypeEnum.isSchool(sysUser.getUserType())) {
                dzSchool.setId(sysUser.getUserTypeId());
            }
        }
        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);
    }

    /**
     * 导出机构校区列表
     */
    @PreAuthorize("@ss.hasPermi('dz:campus:export')")
    @Log(title = "机构校区", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DzSchool dzSchool)
    {
        dzSchool.setCampus(true);
        if(!UserTypeEnum.isSys(SecurityUtils.getLoginUser().getUser().getUserType())) {
            dzSchool.setDeptId(SecurityUtils.getDeptId());
        }
        List<DzSchool> list = dzSchoolService.selectDzSchoolList(dzSchool);
        ExcelUtil<DzSchool> util = new ExcelUtil<DzSchool>(DzSchool.class);
        util.exportExcel(response, list, "机构校区数据");
    }

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

    /**
     * 新增机构校区
     */
    @PreAuthorize("@ss.hasPermi('dz:campus:add')")
    @Log(title = "机构校区", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DzSchool dzSchool)
    {
        if(null == dzSchool.getDeptId()) {
            dzSchool.setDeptId(SecurityUtils.getDeptId());
        }
        return toAjax(dzSchoolService.insertDzSchool(dzSchool));
    }

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

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

    /**
     * 校验校区名称是否唯一
     */
    @GetMapping("/checkCampusName")
    public AjaxResult checkCampusName(@RequestParam("name") String name, @RequestParam(value = "id", required = false) Long id)
    {
        boolean isUnique = dzSchoolService.checkSchoolName(name, id);
        return AjaxResult.success(isUnique);
    }
}
