package com.ozs.web.controller.plan;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ozs.base.domain.BaseNoticeType;
import com.ozs.base.vo.BasePolicyPageReqVo;
import com.ozs.common.annotation.Log;
import com.ozs.common.constant.Constants;
import com.ozs.common.constant.ModularConstans;
import com.ozs.common.core.controller.BaseController;
import com.ozs.common.core.domain.AjaxResult;
import com.ozs.common.core.domain.entity.SysDept;
import com.ozs.common.core.domain.entity.SysDictData;
import com.ozs.common.core.domain.entity.SysRole;
import com.ozs.common.core.domain.entity.SysUser;
import com.ozs.common.enums.BusinessType;
import com.ozs.common.enums.SysFileRefEnum;
import com.ozs.plan.doman.MonthlyReconciliation;
import com.ozs.plan.doman.vo.requestVo.MonthlyReconciliationPageReqVo;
import com.ozs.plan.service.MonthlyReconciliationService;
import com.ozs.system.domain.SysFileInfo;
import com.ozs.system.domain.SysFileRef;
import com.ozs.system.domain.vo.responseVo.SysDeptResponseVo;
import com.ozs.system.service.ISysDeptService;
import com.ozs.system.service.ISysDictTypeService;
import com.ozs.system.service.SysFileRefService;
import com.ozs.system.service.SysFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/monthly/reconciliation")
@Api(tags = ModularConstans.monthly)
public class MonthlyReconciliationController extends BaseController {


    @Autowired
    private MonthlyReconciliationService monthlyReconciliationService;
    @Autowired
    private SysFileRefService sysFileRefService;
    @Autowired
    private SysFileService sysFileService;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private ISysDictTypeService dictTypeService;

    @ApiOperation(value = "分页查询月度对表")
    @PostMapping("/page")
    @PreAuthorize("@ss.hasPermi('base:monthly:list')")
    @Log(title = ModularConstans.monthly, businessType = BusinessType.QUERY)
    public AjaxResult page(@NotEmpty(message = "数据为空")
                           @RequestBody MonthlyReconciliationPageReqVo vo) {
        vo.setDeptId(getDeptId());
        vo.setIsAdmin(SysUser.isAdmin(getUserId()));
        vo.setRoleFlay(false);
        // 添加数据权限
        List<String> roleKeys = getLoginUser().getUser().getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        if (roleKeys.contains(Constants.PURCHASING_MANAGEMENT)
                || roleKeys.contains(Constants.PURCHASE_SERVICES)) {
            vo.setRoleFlay(true);
        }
        // 分页查询
        IPage<MonthlyReconciliation> page = monthlyReconciliationService.queryPage(vo);
        if (!ObjectUtils.isEmpty(page.getRecords()) && page.getRecords().size() > 0) {
            page.setRecords(page.getRecords().stream().map(dto -> {
                // 采购单位名称
                Map<String, Object> stringObjectMap = iSysDeptService.selectDeptById(dto.getPurchaseDeptId());
                if (!ObjectUtils.isEmpty(stringObjectMap)) {
                    SysDeptResponseVo sysDept = (SysDeptResponseVo) stringObjectMap.get("sysDept");
                    dto.setPurchaseDeptName(sysDept.getDeptName());
                }
                // 项目状态
                List<SysDictData> projectStatus = dictTypeService.selectDictDataByType(Constants.SYS_PROJECT_STATUS);
                if (!ObjectUtils.isEmpty(projectStatus)) {
                    List<SysDictData> collect = projectStatus.stream()
                            .filter(d -> d.getDictValue().equals(dto.getProjectStatus().toString())).collect(Collectors.toList());
                    if (!ObjectUtils.isEmpty(collect)) {
                        dto.setProjectStatusStr(collect.get(0).getDictLabel());
                    }
                }

                // 报警状态
                List<SysDictData> warnStatus = dictTypeService.selectDictDataByType(Constants.PROJECT_WARN_STATUS);
                if (!ObjectUtils.isEmpty(warnStatus)) {
                    List<SysDictData> collect = warnStatus.stream()
                            .filter(d -> d.getDictValue().equals(dto.getWarnStatus())).collect(Collectors.toList());
                    if (!ObjectUtils.isEmpty(collect)) {
                        dto.setWarnStatusStr(collect.get(0).getDictLabel());
                    }
                }
                return dto;
            }).collect(Collectors.toList()));
        }
        return success(page);

    }


    @ApiOperation(value = "查看月度对表详情")
    @PostMapping("/getInfo")
    @PreAuthorize("@ss.hasPermi('base:monthly:query')")
    @Log(title = ModularConstans.monthly, businessType = BusinessType.QUERY)
    public AjaxResult getInfo(@NotEmpty(message = "主键id不能为空")
                              @RequestParam(value = "id", required = true)
                                      Long id) {
        MonthlyReconciliation vo = monthlyReconciliationService.getById(id);

        if (!ObjectUtils.isEmpty(vo)) {
            LambdaQueryWrapper<SysFileRef> lw = new LambdaQueryWrapper();
            lw.eq(SysFileRef::getType, SysFileRefEnum.PLAN_TEMPORARY.getType());
            lw.eq(SysFileRef::getRedId, vo.getPlanId());
            List<SysFileRef> list = sysFileRefService.list(lw);
            if (!ObjectUtils.isEmpty(list)) {
                LambdaQueryWrapper<SysFileInfo> l = new LambdaQueryWrapper();
                l.in(SysFileInfo::getFileId, list.stream().map(SysFileRef::getFileId).collect(Collectors.toList()));
                vo.setFileList(sysFileService.list(l));
            }
            Map<String, Object> stringObjectMap = iSysDeptService.selectDeptById(vo.getPurchaseDeptId());
            if (!ObjectUtils.isEmpty(stringObjectMap)) {
                SysDeptResponseVo sysDept = (SysDeptResponseVo) stringObjectMap.get("sysDept");
                vo.setPurchaseDeptName(sysDept.getDeptName());
            }

            // 采购服务站名称
            List<SysDictData> data = dictTypeService.selectDictDataByType("purchase_services");
            if (!ObjectUtils.isEmpty(data)) {
                List<SysDictData> collect = data.stream()
                        .filter(d -> d.getDictValue().equals(vo.getPurchaseServices())).collect(Collectors.toList());
                if (!ObjectUtils.isEmpty(collect)) {
                    vo.setPurchaseServicesName(collect.get(0).getDictLabel());
                }
            }
        }

        return success(vo);
    }

    @ApiOperation(value = "根据项目名称模糊查询项目信息")
    @PostMapping("/listProjectInfoLikeName")
    @Log(title = ModularConstans.monthly, businessType = BusinessType.QUERY)
    public AjaxResult listProjectInfoLikeName(@NotEmpty(message = "数据为空")
                                              @RequestBody BasePolicyPageReqVo vo) {
        LambdaQueryWrapper<MonthlyReconciliation> lw = new LambdaQueryWrapper<>();
        if (!StringUtils.isBlank(vo.getName())) {
            lw.like(MonthlyReconciliation::getProjectName, vo.getName());
        }
        return success(monthlyReconciliationService.list(lw));
    }
}
