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.BaseNotice;
import com.ozs.base.domain.BaseNoticeType;
import com.ozs.base.domain.BasePolicy;
import com.ozs.base.service.BaseNoticeService;
import com.ozs.base.service.BaseNoticeTypeService;
import com.ozs.base.service.BasePolicyService;
import com.ozs.base.vo.BaseNoticePageReqVo;
import com.ozs.base.vo.BaseNoticeVo;
import com.ozs.base.vo.BasePolicyPageReqVo;
import com.ozs.common.annotation.Log;
import com.ozs.common.config.PurchaseConfig;
import com.ozs.common.constant.ModularConstans;
import com.ozs.common.core.controller.BaseController;
import com.ozs.common.core.domain.AjaxResult;
import com.ozs.common.enums.BusinessType;
import com.ozs.common.utils.file.FileUploadUtils;
import com.ozs.common.utils.file.FileUtils;
import com.ozs.common.utils.uuid.UUID;
import com.ozs.common.vo.EsMessage;
import com.ozs.framework.config.ServerConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
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 org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotEmpty;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

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


    @Autowired
    private BasePolicyService basePolicyService;

    @Autowired
    private ServerConfig serverConfig;

    @ApiOperation(value = "分页查询政策法规")
    @PostMapping("/page")
    @PreAuthorize("@ss.hasPermi('base:policy:list')")
    @Log(title = ModularConstans.policy, businessType = BusinessType.QUERY)
    public AjaxResult page(@NotEmpty(message = "数据为空")
                           @RequestBody BasePolicyPageReqVo vo) {
        LambdaQueryWrapper<BasePolicy> lw = new LambdaQueryWrapper<>();
        if (!StringUtils.isBlank(vo.getName())) {
            List<EsMessage> maps = null;
            try {
                maps = FileUtils.eSearch(vo.getName());
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            List<String> ids = maps.stream().map(EsMessage::getId).collect(Collectors.toList());
//            lw.like(BasePolicy::getName,vo.getName());
            if(!ObjectUtils.isEmpty(ids)){
                lw.in(BasePolicy::getEsId, ids);
            }else {
                lw.like(BasePolicy::getName, vo.getName());
            }

        }
        if (!ObjectUtils.isEmpty(vo.getStartTime())) {
            lw.ge(BasePolicy::getReleaseTime, vo.getStartTime());
        }
        if (!ObjectUtils.isEmpty(vo.getStartTime())) {
            lw.le(BasePolicy::getReleaseTime, vo.getEntTime());
        }
        IPage<BasePolicy> page = basePolicyService.page(new Page<>(vo.getPageNum(), vo.getPageSize()), lw);
        return success(page);

    }


    @ApiOperation("PDF上传")
    @ApiImplicitParam(name = "file", value = "文件", required = true, dataTypeClass = MultipartFile.class)
    @PostMapping("/pdfUpload")
    public AjaxResult pdfUpload(MultipartFile file) {
        try {
            // 上传到服务器，返回一个服务器硬盘地址
            String esId = UUID.randomUUID().toString();
            // 上传文件路径
            String filePath = PurchaseConfig.getUploadPath();
            // 上传并返回新文件名称
            String upload = FileUploadUtils.upload(filePath, file);
            String filePathStr = filePath + upload.substring("/profile/upload".length(),upload.length());
            FileUtils.uploadESFile(filePathStr, esId);
            AjaxResult ajax = AjaxResult.success();
            String url = serverConfig.getUrl() + upload;
            ajax.put("url", url);
            ajax.put("fileName", file.getOriginalFilename());
            ajax.put("esId", esId);
            return ajax;
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }

    }

    @ApiOperation(value = "新增政策法规")
    @PostMapping("/insert")
    @PreAuthorize("@ss.hasPermi('base:policy:add')")
    @Log(title = ModularConstans.policy, businessType = BusinessType.INSERT)
    public AjaxResult insert(@NotEmpty(message = "数据为空")
                             @RequestBody BasePolicy vo) {
        vo.setCreated(getUserId().toString());
        vo.setCreateTime(new Date());
        vo.setUpdated(vo.getCreated());
        vo.setUpdateTime(vo.getCreateTime());
        vo.setState("1");
        return toAjax(basePolicyService.save(vo));
    }

    @ApiOperation(value = "在用")
    @PostMapping("/statusUse")
    @PreAuthorize("@ss.hasPermi('base:policy:update')")
    @Log(title = ModularConstans.policy, businessType = BusinessType.INSERT)
    public AjaxResult statusUse(@NotEmpty(message = "数据为空") @RequestBody BasePolicy vo) {
        vo.setState("1");
        return toAjax(basePolicyService.updateById(vo));
    }

    @ApiOperation(value = "止用")
    @PostMapping("/statusNonUse")
    @PreAuthorize("@ss.hasPermi('base:policy:update')")
    @Log(title = ModularConstans.policy, businessType = BusinessType.INSERT)
    public AjaxResult statusNonUse(@NotEmpty(message = "数据为空") @RequestBody BasePolicy vo) {
        vo.setState("0");
        return toAjax(basePolicyService.updateById(vo));
    }

    @ApiOperation(value = "删除政策法规")
    @PostMapping("/remove")
    @PreAuthorize("@ss.hasPermi('base:policy:remove')")
    @Log(title = ModularConstans.policy, businessType = BusinessType.DELETE)
    public AjaxResult remove(@NotEmpty(message = "主键id不能为空")
                             @RequestBody List<Long> ids) {
        return toAjax(basePolicyService.removeBatchByIds(ids));
    }

    @ApiOperation(value = "查看政策法规")
    @PostMapping("/getInfo")
    @PreAuthorize("@ss.hasPermi('base:policy:query')")
    @Log(title = ModularConstans.policy, businessType = BusinessType.QUERY)
    public AjaxResult getInfo(@NotEmpty(message = "主键id不能为空")
                              @RequestParam(value = "id", required = true)
                                      Long id) {
        return success(basePolicyService.getById(id));
    }


}
