package cn.iocoder.yudao.server.controller.admin;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.system.dal.dataobject.oa.IotOaPersonDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.oa.IotOaPersonMapper;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
import cn.iocoder.yudao.server.controller.admin.vo.FlowGroupPageReqVO;
import cn.iocoder.yudao.server.controller.admin.vo.FlowGroupRespVO;
import cn.iocoder.yudao.server.controller.admin.vo.FlowGroupSaveReqVO;
import cn.iocoder.yudao.server.controller.admin.vo.FlowRespVO;
import cn.iocoder.yudao.server.dal.dataobject.FlowDO;
import cn.iocoder.yudao.server.dal.dataobject.FlowGroupDO;
import cn.iocoder.yudao.server.dal.mysql.FlowGroupMapper;
import cn.iocoder.yudao.server.dal.mysql.FlowMapper;
import cn.iocoder.yudao.server.service.FlowGroupService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;


@Tag(name = "管理后台 - 门户流程分组信息")
@RestController
@RequestMapping("/portal/flow-group")
@Validated
public class FlowGroupController {

    @Resource
    private FlowGroupService flowGroupService;
    @Autowired
    private FlowGroupMapper flowGroupMapper;
    @Autowired
    private FlowMapper flowMapper;
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private IotOaPersonMapper iotOaPersonMapper;

    @PostMapping("/create")
    @Operation(summary = "创建门户流程分组信息")
    @PreAuthorize("@ss.hasPermission('portal:flow-group:create')")
    public CommonResult<Long> createFlowGroup(@Valid @RequestBody FlowGroupSaveReqVO createReqVO) {
        return success(flowGroupService.createFlowGroup(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新门户流程分组信息")
    @PreAuthorize("@ss.hasPermission('portal:flow-group:update')")
    public CommonResult<Boolean> updateFlowGroup(@Valid @RequestBody FlowGroupSaveReqVO updateReqVO) {
        flowGroupService.updateFlowGroup(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除门户流程分组信息")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('portal:flow-group:delete')")
    public CommonResult<Boolean> deleteFlowGroup(@RequestParam("id") Long id) {
        flowGroupService.deleteFlowGroup(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得门户流程分组信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('portal:flow-group:query')")
    @PermitAll
    public CommonResult<FlowGroupRespVO> getFlowGroup(@RequestParam("id") Long id) {
        FlowGroupDO flowGroup = flowGroupService.getFlowGroup(id);
        return success(BeanUtils.toBean(flowGroup, FlowGroupRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得门户流程分组信息分页")
    @PreAuthorize("@ss.hasPermission('portal:flow-group:query')")
    public CommonResult<PageResult<FlowGroupRespVO>> getFlowGroupPage(@Valid FlowGroupPageReqVO pageReqVO) {
        PageResult<FlowGroupDO> pageResult = flowGroupService.getFlowGroupPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, FlowGroupRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出门户流程分组信息 Excel")
    @PreAuthorize("@ss.hasPermission('portal:flow-group:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportFlowGroupExcel(@Valid FlowGroupPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<FlowGroupDO> list = flowGroupService.getFlowGroupPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "门户流程分组信息.xls", "数据", FlowGroupRespVO.class,
                        BeanUtils.toBean(list, FlowGroupRespVO.class));
    }

    @GetMapping("/all")
    @Operation(summary = "获得门户流程分组及子项信息")
//    @PreAuthorize("@ss.hasPermission('portal:flow-group:query')")
    @PermitAll
    public CommonResult<List<FlowGroupRespVO>> getFlowGroupDetails(@Valid FlowGroupPageReqVO pageReqVO) {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<FlowGroupDO> list = flowGroupService.getFlowGroupPage(pageReqVO).getList();
        List<FlowGroupRespVO> groups = BeanUtils.toBean(list, FlowGroupRespVO.class);
        groups.forEach(item -> {
            List<FlowDO> groupId = flowMapper.selectList("group_id", item.getId()).stream().filter(e -> e.getStatus()==0).collect(Collectors.toList());
            List<FlowRespVO> bean = BeanUtils.toBean(groupId, FlowRespVO.class);
            item.setFlowRespVOS(bean.stream().sorted(Comparator.comparing(FlowRespVO::getSort)).collect(Collectors.toList()));
        });
        List<FlowGroupRespVO> collect = groups.stream().sorted(Comparator.comparing(FlowGroupRespVO::getSort)).collect(Collectors.toList());
        return success(collect);
    }

    @GetMapping("/init-oa-person")
    @PermitAll
    public void initPerson() {
        List<AdminUserDO> adminUserDOS = adminUserMapper.selectList();
        List<String> collect = adminUserDOS.stream().map(AdminUserDO::getUsername).collect(Collectors.toList());
        List<IotOaPersonDO> iotOaPersonDOS = iotOaPersonMapper.selectList();

        List<AdminUserDO> userDOS = new ArrayList<>();
        iotOaPersonDOS.forEach(e ->{
            //如果系统用户里面没有包含oa里面的
            if (!collect.contains(e.getWorkcode())&& StringUtils.isNotBlank(e.getWorkcode())&&"1".equals(e.getStatus())) {
                AdminUserDO adminUserDO = new AdminUserDO();
                if (Objects.nonNull(e.getMobile())&&e.getMobile().length()<=11) {
                    adminUserDO.setMobile(e.getMobile());
                }
                adminUserDO.setStatus(0);
                adminUserDO.setUsername(e.getWorkcode());
                adminUserDO.setCreator("1");
                adminUserDO.setCreateTime(LocalDateTime.now());
                adminUserDO.setDeleted(false);
                adminUserDO.setTenantId(1L);
                adminUserDO.setDeptId(157L);
                adminUserDO.setNickname(e.getLastname());
                userDOS.add(adminUserDO);
            }
        });
        adminUserMapper.insertBatch(userDOS);
    }
}