package com.ozs.web.controller.base;


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.BaseAgency;
import com.ozs.base.domain.BasePolicy;
import com.ozs.base.service.BaseAgencyService;
import com.ozs.base.vo.BaseAgentPageReqVo;
import com.ozs.base.vo.BasePolicyPageReqVo;
import com.ozs.base.vo.BaseProjectInfo;
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.SysDictData;
import com.ozs.common.enums.BusinessType;
import com.ozs.common.enums.PmProjectStatus;
import com.ozs.plan.doman.MonthlyReconciliation;
import com.ozs.plan.service.MonthlyReconciliationService;
import com.ozs.system.domain.vo.responseVo.SysDeptResponseVo;
import com.ozs.system.service.ISysDeptService;
import com.ozs.system.service.ISysDictTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
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.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;


@Api(tags = ModularConstans.agency)
@RestController
@RequestMapping("/base/agency")
public class BaseAgencyController extends BaseController {

    @Autowired
    private BaseAgencyService baseAgencyService;

    @Autowired
    private MonthlyReconciliationService monthlyReconciliationService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService dictTypeService;


    @ApiOperation(value = "新增招标代理机构")
    @PostMapping("/insertBaseAgency")
    @PreAuthorize("@ss.hasPermi('base:agency:add')")
    @Log(title = ModularConstans.agency, businessType = BusinessType.INSERT)
    public AjaxResult insertBaseAgency(@NotEmpty(message = "数据为空")
                                       @RequestBody BaseAgency baseAgency) {
//        if (ObjectUtils.isEmpty(baseAgency)) {
//            return error("数据为空");
//        }
        baseAgency.setStatus(0);
        baseAgency.setCreated(getUserId().toString());
        baseAgency.setCreateTime(new Date());
        baseAgency.setUpdated(baseAgency.getCreated());
        baseAgency.setUpdateTime(baseAgency.getCreateTime());
        return toAjax(baseAgencyService.insert(baseAgency));
    }


    @ApiOperation(value = "查看招标代理机构")
    @PostMapping("/getInfo")
    @PreAuthorize("@ss.hasPermi('base:agency:query')")
    @Log(title = ModularConstans.agency, businessType = BusinessType.QUERY)
    public AjaxResult getInfo(@NotEmpty(message = "主键id不能为空")
                              @RequestParam(value = "id", required = true)
                                      Long id) {
        return success(baseAgencyService.getInfo(id));
    }


    @ApiOperation(value = "修改招标代理机构信息")
    @PostMapping("/updateInfo")
    @PreAuthorize("@ss.hasPermi('base:agency:edit')")
    @Log(title = ModularConstans.agency, businessType = BusinessType.UPDATE)
    public AjaxResult updateInfo(@NotEmpty(message = "数据为空")
                                 @RequestBody BaseAgency baseAgency) {
        baseAgency.setUpdateTime(new Date());
        baseAgency.setUpdated(getUserId().toString());
        return toAjax(baseAgencyService.updateInfo(baseAgency));
    }

    @ApiOperation(value = "操作招标代理机构黑白名单")
    @PostMapping("/operationBlacklist")
    @PreAuthorize("@ss.hasPermi('base:agency:edit')")
    @Log(title = ModularConstans.agency, businessType = BusinessType.UPDATE)
    public AjaxResult operationBlacklist(@NotEmpty(message = "主键id不能为空")
                                         @RequestParam(value = "id", required = true)
                                                 Long id,
                                         @NotEmpty(message = "状态不能为空")
                                         @RequestParam(value = "status", required = true)
                                                 Integer status) {

        BaseAgency build = BaseAgency.builder().id(id).status(status).build();
        build.setUpdated(getUserId().toString());
        build.setUpdateTime(new Date());
        return toAjax(baseAgencyService.operationBlacklist(build));
    }

    @ApiOperation(value = "删除招标代理机构信息")
    @PostMapping("/remove")
    @PreAuthorize("@ss.hasPermi('base:agency:remove')")
    @Log(title = ModularConstans.agency, businessType = BusinessType.DELETE)
    public AjaxResult remove(@NotEmpty(message = "主键id不能为空")
                             @RequestParam(value = "id", required = true)
                                     Long id) {
        return toAjax(baseAgencyService.remove(id));
    }

    @ApiOperation(value = "分页查询招标代理机构信息")
    @PostMapping("/page")
    @PreAuthorize("@ss.hasPermi('base:agency:list')")
    @Log(title = ModularConstans.agency, businessType = BusinessType.QUERY)
    public AjaxResult page(@NotEmpty(message = "数据为空") @RequestBody BaseAgentPageReqVo vo) {
        LambdaQueryWrapper<BaseAgency> lw = new LambdaQueryWrapper<BaseAgency>();
        if (!StringUtils.isBlank(vo.getCompanyName())) {
            lw.like(BaseAgency::getCompanyName, vo.getCompanyName());
        }
        if (!StringUtils.isBlank(vo.getCompanyNature())) {
            lw.eq(BaseAgency::getCompanyNature, vo.getCompanyNature());
        }
        if (!ObjectUtils.isEmpty(vo.getStatus())) {
            lw.eq(BaseAgency::getStatus, vo.getStatus());
        }
        if (!ObjectUtils.isEmpty(vo.getCompanyType())) {
            lw.eq(BaseAgency::getCompanyType, vo.getCompanyType());
        }
        IPage<BaseAgency> page = baseAgencyService.page(new Page<BaseAgency>(vo.getPageNum(), vo.getPageSize()), lw);
        if (!ObjectUtils.isEmpty(page) && !ObjectUtils.isEmpty(page.getRecords())) {

            List<SysDictData> dictData = dictTypeService.selectDictDataByType(Constants.SYS_COMPANY_NATURE);
            if (!ObjectUtils.isEmpty(dictData)) {
                List<BaseAgency> collect = page.getRecords().stream().map(o -> {
                    List<SysDictData> dl = dictData.stream()
                            .filter(d -> d.getDictValue().equals(o.getCompanyNature())).collect(Collectors.toList());
                    if (!ObjectUtils.isEmpty(dl)) {
                        o.setCompanyNature(dl.get(0).getDictLabel());
                    }
                    return o;
                }).collect(Collectors.toList());
                page.setRecords(collect);
            }

        }
        return success(page);
    }

    @ApiOperation(value = "抽取招标代理机构（分页查询项目代理信息）")
    @PostMapping("/pageProjectInfo")
    @PreAuthorize("@ss.hasPermi('base:agency:pageProjectInfo')")
    @Log(title = ModularConstans.agency, businessType = BusinessType.QUERY)
    public AjaxResult pageProjectInfo(@NotEmpty(message = "数据为空")
                                      @RequestBody BasePolicyPageReqVo vo) {
        LambdaQueryWrapper<MonthlyReconciliation> lw = new LambdaQueryWrapper<>();
        lw.isNotNull(MonthlyReconciliation::getAgencyId);
        if (!StringUtils.isBlank(vo.getName())) {
            lw.like(MonthlyReconciliation::getProjectName, vo.getName());
        }
        if (!ObjectUtils.isEmpty(vo.getStartTime())) {
            lw.ge(MonthlyReconciliation::getExtractAgencyTime, vo.getStartTime());
        }
        if (!ObjectUtils.isEmpty(vo.getStartTime())) {
            lw.le(MonthlyReconciliation::getExtractAgencyTime, vo.getEntTime());
        }

        IPage<BaseProjectInfo> page = new Page<>();
        IPage<MonthlyReconciliation> pageInfo = monthlyReconciliationService.page(new Page<>(vo.getPageNum(), vo.getPageSize()), lw);
        if (!ObjectUtils.isEmpty(pageInfo)) {
            List<BaseProjectInfo> collect = pageInfo.getRecords().stream().map(o -> {
                BaseProjectInfo baseProjectInfo = new BaseProjectInfo();
                BeanUtils.copyProperties(o, baseProjectInfo);
                // 采购单位名称
                Map<String, Object> stringObjectMap = iSysDeptService.selectDeptById(o.getPurchaseDeptId());
                if (!ObjectUtils.isEmpty(stringObjectMap)) {
                    SysDeptResponseVo sysDept = (SysDeptResponseVo) stringObjectMap.get("sysDept");
                    baseProjectInfo.setPurchaseDeptName(sysDept.getDeptName());
                }
                // 项目属性
                List<SysDictData> projectAttr = dictTypeService.selectDictDataByType(Constants.SYS_PROJECT_ATTR);
                if (!ObjectUtils.isEmpty(projectAttr)
                        && !ObjectUtils.isEmpty(o.getProjectAttr())) {
                    List<SysDictData> slist = projectAttr.stream()
                            .filter(d -> d.getDictValue().equals(o.getProjectAttr()))
                            .collect(Collectors.toList());
                    if (!ObjectUtils.isEmpty(slist)) {
                        baseProjectInfo.setProjectAttrStr(slist.get(0).getDictLabel());
                    }
                }

                // 项目类型
                List<SysDictData> projectType = dictTypeService.selectDictDataByType(Constants.SYS_PROJECT_TYPE);
                if (!ObjectUtils.isEmpty(projectType)
                        && !ObjectUtils.isEmpty(o.getProjectType())) {
                    List<SysDictData> slist = projectType.stream()
                            .filter(d -> d.getDictValue().equals(o.getProjectType()))
                            .collect(Collectors.toList());
                    if (!ObjectUtils.isEmpty(slist)) {
                        baseProjectInfo.setProjectTypeStr(slist.get(0).getDictLabel());
                    }
                }
                // 招标代理机构
                if (!ObjectUtils.isEmpty(o.getAgencyId())) {
                    BaseAgency info = baseAgencyService.getInfo(o.getAgencyId());
                    baseProjectInfo.setAgencyName(ObjectUtils.isEmpty(info) ? null : info.getCompanyName());
                }
                return baseProjectInfo;
            }).collect(Collectors.toList());
            page.setRecords(collect);
            page.setTotal(pageInfo.getTotal());
            page.setPages(pageInfo.getPages());
            page.setTotal(pageInfo.getTotal());
            page.setCurrent(pageInfo.getCurrent());
        }
        return success(page);
    }

    @ApiOperation(value = "根据项目名称模糊查询项目信息-代理抽取查询用")
    @PostMapping("/listProjectInfoLikeName")
    @PreAuthorize("@ss.hasPermi('base:agency:listProjectInfoLikeName')")
    @Log(title = ModularConstans.agency, businessType = BusinessType.QUERY)
    public AjaxResult listProjectInfoLikeName(@NotEmpty(message = "数据为空")
                                              @RequestBody BasePolicyPageReqVo vo) {
        LambdaQueryWrapper<MonthlyReconciliation> lw = new LambdaQueryWrapper<>();
        lw.isNull(MonthlyReconciliation::getAgencyId);
        lw.eq(MonthlyReconciliation::getProjectStatus, PmProjectStatus.PURCHASE_DEMAND_DOCKING.getCode());
        if (!StringUtils.isBlank(vo.getName())) {
            lw.like(MonthlyReconciliation::getProjectName, vo.getName());
        }
        return success(monthlyReconciliationService.list(lw));
    }


    @ApiOperation(value = "确认抽取")
    @PostMapping("/extract")
    @PreAuthorize("@ss.hasPermi('base:agency:extract')")
    @Log(title = ModularConstans.agency, businessType = BusinessType.OTHER)
    public AjaxResult extract(@NotEmpty(message = "主键id不能为空")
                              @RequestParam(value = "demandId", required = true)
                                      Long demandId) {
        LambdaQueryWrapper<BaseAgency> lw = new LambdaQueryWrapper<>();
        MonthlyReconciliation byId = monthlyReconciliationService.getById(demandId);
        if (ObjectUtils.isEmpty(byId)) {
            return error("参数错误");
        }
        byId.setExtractAgencyTime(new Date());
        lw.eq(BaseAgency::getCompanyType, byId.getProjectType());
        lw.eq(BaseAgency::getStatus, 0);
        Optional<BaseAgency> any = baseAgencyService.list(lw).stream().findAny();
        if (ObjectUtils.isEmpty(any)) {
            return error("没有符合的招标代理机构，抽取失败！");
        }
        byId.setAgencyId(any.get().getId());
        byId.setUpdateTime(byId.getExtractAgencyTime());
        byId.setUpdateBy(getUserId().toString());


        return success(monthlyReconciliationService.updateById(byId));
    }

}
