package com.xjrsoft.module.asset.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.TreeUtil;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.asset.dto.*;
import com.xjrsoft.module.asset.entity.WfAssetManage;
import com.xjrsoft.module.asset.service.IWfAssetManageService;
import com.xjrsoft.module.asset.vo.BaseOfficeBuildVo;
import com.xjrsoft.module.asset.vo.PlaceTreeVo;
import com.xjrsoft.module.asset.vo.WfAssetManagePageVo;
import com.xjrsoft.module.asset.vo.WfAssetManageVo;
import com.xjrsoft.module.base.entity.BaseClassroom;
import com.xjrsoft.module.base.entity.BaseOfficeBuild;
import com.xjrsoft.module.base.service.IBaseClassroomService;
import com.xjrsoft.module.base.service.IBaseOfficeBuildService;
import com.xjrsoft.module.oa.entity.WfOaPull;
import com.xjrsoft.module.oa.vo.FileReceivePullPageVo;
import com.xjrsoft.module.organization.entity.Department;
import com.xjrsoft.module.organization.entity.User;
import com.xjrsoft.module.system.entity.DictionaryDetail;
import com.xjrsoft.module.teacher.entity.XjrUser;
import com.xjrsoft.module.textbook.dto.TextbookClaimExportQueryDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @title: 资产管理
* @Author dzx
* @Date: 2024-03-28
* @Version 1.0
*/
@RestController
@RequestMapping("/asset" + "/wfAssetManage")
@Api(value = "/asset"  + "/wfAssetManage",tags = "资产管理代码")
@AllArgsConstructor
public class WfAssetManageController {


    private final IWfAssetManageService wfAssetManageService;

    private final IBaseOfficeBuildService baseOfficeBuildService;

    private final IBaseClassroomService baseClassroomService;

    @GetMapping(value = "/buildingfloorclassroomtree")
    @ApiOperation(value = "楼栋楼层教室树")
    @SaCheckPermission("studentmanager:detail")
    public RT<List<PlaceTreeVo>> buildingFloorClassroomTree() {
        List<PlaceTreeVo> voList = new ArrayList<>();
        long customUniqueId = 101010;

        //获取楼栋信息记录
        MPJLambdaWrapper<BaseOfficeBuild> baseOfficeBuildMPJLambdaWrapper = new MPJLambdaWrapper<>();
        baseOfficeBuildMPJLambdaWrapper
                .select(BaseOfficeBuild::getId)
                .selectAs(DictionaryDetail::getName, BaseOfficeBuildVo::getBuildTypeCn)
                .select(BaseOfficeBuild.class,x -> VoToColumnUtil.fieldsToColumns(BaseOfficeBuildVo.class).contains(x.getProperty()))
                .leftJoin(DictionaryDetail.class, DictionaryDetail::getCode, BaseOfficeBuild::getBuildType)
        ;

        List<BaseOfficeBuildVo> baseOfficeBuildVoList = baseOfficeBuildService.selectJoinList(BaseOfficeBuildVo.class, baseOfficeBuildMPJLambdaWrapper);

        Map<String, List<BaseOfficeBuildVo>> officeBuildByAddress = baseOfficeBuildVoList.stream().collect(Collectors.groupingBy(BaseOfficeBuildVo::getAddress));

        for (Map.Entry<String, List<BaseOfficeBuildVo>> entry : officeBuildByAddress.entrySet()){
            String key = entry.getKey();
            List<BaseOfficeBuildVo> value = entry.getValue();

            voList.add(new PlaceTreeVo(){{
                setId(8888L);
                setName(key);
            }});

            if(!value.isEmpty()){
                Map<String, List<BaseOfficeBuildVo>> officeBuildByType = value.stream().collect(Collectors.groupingBy(BaseOfficeBuildVo::getBuildType));
                for (Map.Entry<String, List<BaseOfficeBuildVo>> e : officeBuildByType.entrySet()){
                    String k = e.getKey();
                    List<BaseOfficeBuildVo> v = e.getValue();

                    PlaceTreeVo placeTreeVo = new PlaceTreeVo();
                    placeTreeVo.setId(customUniqueId);
                    if(!v.isEmpty() && v.get(0) != null){
                        placeTreeVo.setName(v.get(0).getBuildTypeCn());
                    }
                    placeTreeVo.setParentId(8888L);
                    voList.add(placeTreeVo);

                    if(!v.isEmpty()){
                        for (BaseOfficeBuildVo baseOfficeBuildVo : v){
                            PlaceTreeVo p = new PlaceTreeVo();
                            p.setId(baseOfficeBuildVo.getId());
                            p.setName(baseOfficeBuildVo.getName());
                            p.setParentId(customUniqueId);
                            voList.add(p);
                        }
                    }

                    customUniqueId++;
                }
            }
        }

        //获取教室信息
        List<BaseClassroom> baseClassroomList = baseClassroomService.list();

        Map<Long, List<BaseClassroom>> baseClassroomMap = baseClassroomList.stream().collect(Collectors.groupingBy(BaseClassroom::getOfficeBuildId));
        for (Map.Entry<Long, List<BaseClassroom>> entry : baseClassroomMap.entrySet()){
            Long key = entry.getKey();
            List<BaseClassroom> value = entry.getValue();

            if(!value.isEmpty()){
                Map<Integer, List<BaseClassroom>> baseClassroomByFloorNum = value.stream().collect(Collectors.groupingBy(BaseClassroom::getFloorNum));
                for (Map.Entry<Integer, List<BaseClassroom>> e : baseClassroomByFloorNum.entrySet()){
                    Integer k = e.getKey();
                    List<BaseClassroom> v = e.getValue();

                    PlaceTreeVo placeTreeVo = new PlaceTreeVo();
                    placeTreeVo.setId(customUniqueId);
                    placeTreeVo.setName(k + "楼");
                    placeTreeVo.setParentId(key);
                    voList.add(placeTreeVo);

                    if(!v.isEmpty()){
                        for (BaseClassroom baseClassroom : v){
                            PlaceTreeVo p = new PlaceTreeVo();
                            p.setId(baseClassroom.getId());
                            p.setName(baseClassroom.getName());
                            p.setParentId(customUniqueId);
                            voList.add(p);
                        }
                    }

                    customUniqueId++;
                }
            }
        }

        List<PlaceTreeVo> treeVoList = TreeUtil.build(voList);

        return RT.ok(treeVoList);
    }

    @GetMapping(value = "/page")
    @ApiOperation(value="资产管理列表(分页)")
    @SaCheckPermission("wfassetmanage:detail")
    public RT<PageOutput<WfAssetManagePageVo>> page(@Valid WfAssetManagePageDto dto){
        IPage<WfAssetManagePageVo> page = wfAssetManageService.getPage(dto);
        PageOutput<WfAssetManagePageVo> pageOutput = ConventPage.getPageOutput(page, WfAssetManagePageVo.class);
        return RT.ok(pageOutput);
    }

    @GetMapping(value = "/info")
    @ApiOperation(value="根据id查询资产管理信息")
    @SaCheckPermission("wfassetmanage:detail")
    public RT<WfAssetManageVo> info(@RequestParam Long id){
        MPJLambdaWrapper<WfAssetManage> wfAssetManageMPJLambdaWrapper = new MPJLambdaWrapper<>();
        wfAssetManageMPJLambdaWrapper
                .select(WfAssetManage::getId)
                .select(WfAssetManage.class, x -> VoToColumnUtil.fieldsToColumns(WfAssetManageVo.class).contains(x.getProperty()))
                .leftJoin(DictionaryDetail.class, DictionaryDetail::getCode, WfAssetManage::getAssetType, ext -> ext.selectAs(DictionaryDetail::getName, WfAssetManageVo::getAssetTypeCn))
                .leftJoin(DictionaryDetail.class, DictionaryDetail::getCode, WfAssetManage::getAssetCategory, ext -> ext.selectAs(DictionaryDetail::getName, WfAssetManageVo::getAssetCategoryCn))
                .leftJoin(DictionaryDetail.class, DictionaryDetail::getCode, WfAssetManage::getAssetSpecies, ext -> ext.selectAs(DictionaryDetail::getName, WfAssetManageVo::getAssetSpeciesCn))
                .leftJoin(XjrUser.class, XjrUser::getId, WfAssetManage::getUserId, ext -> ext.selectAs(XjrUser::getName, WfAssetManageVo::getUserIdCn))
                .leftJoin(Department.class, Department::getId, WfAssetManage::getDeptId, ext -> ext.selectAs(Department::getName, WfAssetManageVo::getDeptIdCn))
                .eq(WfAssetManage::getId, id)
        ;

        WfAssetManageVo wfAssetManageVo = wfAssetManageService.selectJoinOne(WfAssetManageVo.class, wfAssetManageMPJLambdaWrapper);
        if (wfAssetManageVo == null) {
           return RT.error("找不到此数据！");
        }
        return RT.ok(wfAssetManageVo);
    }


    @PostMapping
    @ApiOperation(value = "新增资产管理")
    @SaCheckPermission("wfassetmanage:add")
    public RT<Boolean> add(@Valid @RequestBody AddWfAssetManageDto dto){
        WfAssetManage wfAssetManage = BeanUtil.toBean(dto, WfAssetManage.class);
        boolean isSuccess = wfAssetManageService.save(wfAssetManage);
    return RT.ok(isSuccess);
    }

    @PutMapping
    @ApiOperation(value = "修改资产管理")
    @SaCheckPermission("wfassetmanage:edit")
    public RT<Boolean> update(@Valid @RequestBody UpdateWfAssetManageDto dto){

        WfAssetManage wfAssetManage = BeanUtil.toBean(dto, WfAssetManage.class);
        return RT.ok(wfAssetManageService.updateById(wfAssetManage));

    }

    @DeleteMapping
    @ApiOperation(value = "删除资产管理")
    @SaCheckPermission("wfassetmanage:delete")
    public RT<Boolean> delete(@Valid @RequestBody List<Long> ids){
        return RT.ok(wfAssetManageService.removeBatchByIds(ids));

    }

    @PostMapping("/select-record-export-query")
    @ApiOperation(value = "选中记录导出")
    public ResponseEntity<byte[]> assetManageSelectRecordQuery(@Valid @RequestBody WfAssetManageSelectRecordQueryDto dto) {
//    @GetMapping("/select-record-export-query")
//    @ApiOperation(value = "选中记录导出")
//    public ResponseEntity<byte[]> assetManageSelectRecordQuery(@Valid WfAssetManageSelectRecordQueryDto dto) {
        ByteArrayOutputStream bot = wfAssetManageService.listWfAssetManageSelectRecordQuery(dto);
        return RT.fileStream(bot.toByteArray(), "WfAssetManage" + ExcelTypeEnum.XLSX.getValue());
    }

    @PostMapping("/conditional-search-export-query")
    @ApiOperation(value = "条件搜索导出")
    public ResponseEntity<byte[]> assetManageConditionalSearchQuery(@Valid @RequestBody WfAssetManageConditionalSearchQueryDto dto) {
//    @GetMapping("/conditional-search-export-query")
//    @ApiOperation(value = "条件搜索导出")
//    public ResponseEntity<byte[]> textbookClaimExportQuery(@Valid WfAssetManageConditionalSearchQueryDto dto) {
        ByteArrayOutputStream bot = wfAssetManageService.listWfAssetManageConditionalSearchQuery(dto);
        return RT.fileStream(bot.toByteArray(), "WfAssetManage" + ExcelTypeEnum.XLSX.getValue());
    }

}