package com.ruoyi.web.controller.dz;

import java.util.Arrays;
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 cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
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.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.RequestParam;
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);
//        }
        dzSchool.setCampus(false);
        if (StringUtils.isNotBlank(dzSchool.getAreaCode())) {
            if (dzSchool.getAreaCode().endsWith("0000")) {
                dzSchool.setPro(Long.parseLong(dzSchool.getAreaCode()));
            } else if (dzSchool.getAreaCode().endsWith("00")) {
                dzSchool.setCity(Long.parseLong(dzSchool.getAreaCode()));
            } else {
                dzSchool.setArea(Long.parseLong(dzSchool.getAreaCode()));
            }
        }
        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)
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if(null == dzSchool.getCampus() && !UserTypeEnum.isSys(sysUser.getUserType())) {
            dzSchool.setCampus(true);
        }
        if (UserTypeEnum.isSchool(sysUser.getUserType())) {
            dzSchool.setId(sysUser.getUserTypeId());
        }
        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);
//        }
        dzSchool.setCampus(false);
        List<DzSchool> list = dzSchoolService.selectDzSchoolList(dzSchool);
        return AjaxResult.success(list);
    }

    /**
     * 获取所有学校列表（不分页）
     */
    @GetMapping("/getAllSchool")
    public AjaxResult getAllSchool()
    {
        DzSchool dzSchool = new DzSchool();
        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)
    {
        dzSchool.setCampus(false);
        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);
        }
//        generate();
        return toAjax(id);
    }

    private void generate(){
        List<Integer> schoolList = Arrays.asList(2,4,8,14,29,30,31,32,33,34,42,43,45,51,54,55,56,66,70,71,73,74,76,77,79,80,86,87,89,91,
                92,93,94,95,97,98,108,110,111,112,114,115,117,118,119,121,122,124,126,127,130,131,132,133,134,135,136,137,138,139,140,142,143,145,146,149,151,153,173,174,175,176,182,183,184,185,186,187,188,189,204,205,206,207,250,251,252,253,254,255,257,262,263,264,265,266,273,274,275,284,358,359,360,361,362,363,364,365,366,376,377,427,428,440,441,452,453,454,455,456,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,480,481,482,483,484,485,486,487,488,489,527,528,555,557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,591,592,593,594,595,596,
                597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,668,669,670,671,672,673,674,675,679,680,681,682,683,688,689,690,691,692,723,724,725,726,727,728,732,733,734,735,736,747,748,749,760,761,762,763,764,765,766,784,785,786,787,812,813,814,815,816,817,818,819,820,821,822,823,824,825,826,827,832,833,834,835,836,837,838,839,840,
                841,842,843,847,848,856,857,865,866,867,868,877,878,879,880,881,882,883,884,889,890,906,907,908,909,910,911,920,921,922,923,924,929,930,931,932,933,934,935,936,937,938,939,1000,1001,1002,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1071,1072,1073,1074,1075,1076,1077,1078,1083,1084,1085,1086,1087,1114,1115,1116,1117,1118,1119,1120,1121,1122,1123,1124,1125,1126,1127,1128,1129,1130,1131,1132,1133,1134,1135,1136,1137,1138,1139,1140,1141,1142,1143,1144,1145,1146,1147,1148,1149,1150,1151,1152,1153,1154,1155,1156,1157,1158,1159,1160,1161,1162,1163,1164,1165,
                1166,1167,1168,1169,1170,1171,1172,1173,1174,1175,1176,1177,1178,1208,1209,1210,1211,1212,1247,1248,1267,1268,1269,1270,1271,1272,1273,1274,1275,1276,1277,1278,1279,1280,1281,1285,1286,1287,1288,1289,1299,1300,1301,1302,1303,1304,1305,1306,1307,1317,1318,1319,1320,1326,1327,1328,1329,1330,1331,1332,1333,1343,1344,1345,1349,1350,1351,1361,1362,1366,1367,1368,1369,1370,1371,1372,1373,1374,1375,1376,1377,1378,1379,1380,1381,1382,1383,1384,1385,1386,
                1387,1388,1389,1390,1391,1392,1393,1394,1395,1396,1397,1398,1399,1400,1401,1402,1417,1430,1439,1440,1447,1448,1452,1453,1454,1455,1473,1474,1475,1476,1477,1478,1479,1480,1481,1482,1483,1484,1485,1486,1487,1488,1489,1490,1491,1492,1493,1494,1495,1595,1596,1597,1598,1599,1600,1601,1602,1603,1620,1621,1622,1623,1624,1625,1639,1640,1641,1642,1643,1644,1645,1646,1647,1648,1649,1650,1651,1652,1653,1654,1655,1656,1657,1658,1659,1660,1661,1662,1663,1664,1665,1666,1667,1668,1669,1670,1671,1672,1673,1674,1675,1683,1684,1685,1686,1687,1688,1689,1723,1724,1725,1727,1728
                );
        for (Integer id : schoolList) {
            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);
            }
        }

    }

    /**
     * 修改机构校区
     */
    @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));
    }

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