package com.xjrsoft.module.attendance.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.attendance.dto.AddAttendanceRuleCategoryDto;
import com.xjrsoft.module.attendance.dto.AddAttendanceUserRelationDto;
import com.xjrsoft.module.attendance.dto.AttendanceRuleCategoryPageDto;
import com.xjrsoft.module.attendance.dto.UpdateAttendanceRuleCategoryDto;
import com.xjrsoft.module.attendance.entity.AttendanceRuleCategory;
import com.xjrsoft.module.attendance.service.IAttendanceRuleCategoryService;
import com.xjrsoft.module.attendance.vo.AttendanceRuleCategoryPageVo;
import com.xjrsoft.module.attendance.vo.AttendanceRuleCategoryVo;
import com.xjrsoft.module.base.entity.BaseClass;
import com.xjrsoft.module.base.service.IBaseClassService;
import com.xjrsoft.module.concat.service.IXjrUserService;
import com.xjrsoft.module.organization.entity.Department;
import com.xjrsoft.module.organization.service.IDepartmentService;
import com.xjrsoft.module.teacher.entity.XjrUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
* @title: 考勤规则
* @Author dzx
* @Date: 2024-05-08
* @Version 1.0
*/
@RestController
@RequestMapping("/attendance" + "/attendanceRuleCategory")
@Api(value = "/attendance"  + "/attendanceRuleCategory",tags = "考勤规则代码")
@AllArgsConstructor
public class AttendanceRuleCategoryController {


    private final IAttendanceRuleCategoryService attendanceRuleCategoryService;
    private final IBaseClassService classService;
    private final IDepartmentService departmentService;
    private final IXjrUserService xjrUserService;

    @GetMapping(value = "/page")
    @ApiOperation(value="考勤规则列表(分页)")
    @SaCheckPermission("attendancerulecategory:detail")
    public RT<PageOutput<AttendanceRuleCategoryPageVo>> page(@Valid AttendanceRuleCategoryPageDto dto){

        LambdaQueryWrapper<AttendanceRuleCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                    .orderByDesc(AttendanceRuleCategory::getId)
                .select(AttendanceRuleCategory.class,x -> VoToColumnUtil.fieldsToColumns(AttendanceRuleCategoryPageVo.class).contains(x.getProperty()));
        IPage<AttendanceRuleCategory> page = attendanceRuleCategoryService.page(ConventPage.getPage(dto), queryWrapper);
        PageOutput<AttendanceRuleCategoryPageVo> pageOutput = ConventPage.getPageOutput(page, AttendanceRuleCategoryPageVo.class);
        return RT.ok(pageOutput);
    }

    @GetMapping(value = "/info")
    @ApiOperation(value="根据id查询考勤规则信息")
    @SaCheckPermission("attendancerulecategory:detail")
    public RT<AttendanceRuleCategoryVo> info(@RequestParam Long id){
        AttendanceRuleCategory attendanceRuleCategory = attendanceRuleCategoryService.getByIdDeep(id);
        if (attendanceRuleCategory == null) {
           return RT.error("找不到此数据！");
        }
        AttendanceRuleCategoryVo categoryVo = BeanUtil.toBean(attendanceRuleCategory, AttendanceRuleCategoryVo.class);
        if(attendanceRuleCategory.getUserRelation() != null && !"".equals(attendanceRuleCategory.getUserRelation())){
            JsonParser parser = new JsonParser();
            JsonArray asJsonArray = parser.parse(attendanceRuleCategory.getUserRelation()).getAsJsonArray();
            List<AddAttendanceUserRelationDto> attendanceUserRelationList = new ArrayList<>();
            for (JsonElement jsonElement : asJsonArray) {
                AddAttendanceUserRelationDto relationDto = JSONUtil.toBean(jsonElement.getAsJsonObject().toString(), AddAttendanceUserRelationDto.class);
                if(relationDto.getUserId() != null){
                    XjrUser xjrUser = xjrUserService.getById(relationDto.getUserId());
                    if(xjrUser != null){
                        relationDto.setName(xjrUser.getName());
                    }
                }else if(relationDto.getDeptId() != null){
                    Department department = departmentService.getById(relationDto.getDeptId());
                    if(department != null){
                        relationDto.setName(department.getName());
                    }

                }else if(relationDto.getClassId() != null){
                    BaseClass aClass = classService.getById(relationDto.getClassId());
                    if(aClass != null){
                        relationDto.setName(aClass.getName());
                    }
                }
                attendanceUserRelationList.add(relationDto);
            }
            categoryVo.setAttendanceUserRelationList(attendanceUserRelationList);
        }

        return RT.ok(categoryVo);
    }


    @PostMapping
    @ApiOperation(value = "新增考勤规则")
    @SaCheckPermission("attendancerulecategory:add")
    public RT<Boolean> add(@Valid @RequestBody AddAttendanceRuleCategoryDto dto){
        boolean isSuccess = attendanceRuleCategoryService.add(dto);
        return RT.ok(isSuccess);
    }

    @PutMapping
    @ApiOperation(value = "修改考勤规则")
    @SaCheckPermission("attendancerulecategory:edit")
    public RT<Boolean> update(@Valid @RequestBody UpdateAttendanceRuleCategoryDto dto){
        return RT.ok(attendanceRuleCategoryService.update(dto));
    }

    @DeleteMapping
    @ApiOperation(value = "删除考勤规则")
    @SaCheckPermission("attendancerulecategory:delete")
    public RT<Boolean> delete(@Valid @RequestBody List<Long> ids){
        return RT.ok(attendanceRuleCategoryService.delete(ids));
    }

}