package com.yunfeiyun.agmp.fms.controller;

import com.yunfeiyun.agmp.common.annotation.Log;
import com.yunfeiyun.agmp.common.constant.ErrorCode;
import com.yunfeiyun.agmp.common.constant.ResConstants;
import com.yunfeiyun.agmp.common.core.controller.BaseController;
import com.yunfeiyun.agmp.common.core.domain.AjaxResult;
import com.yunfeiyun.agmp.common.core.page.TableDataInfo;
import com.yunfeiyun.agmp.common.enums.BusinessType;
import com.yunfeiyun.agmp.common.enums.CommonEnums;
import com.yunfeiyun.agmp.common.framework.manager.ResManager;
import com.yunfeiyun.agmp.common.utils.poi.ExcelUtil;
import com.yunfeiyun.agmp.common.web.system.domain.SysRes;
import com.yunfeiyun.agmp.fms.domain.FmsBlock;
import com.yunfeiyun.agmp.fms.domain.FmsLand;
import com.yunfeiyun.agmp.fms.domain.reqvo.FmsBlockReqVo;
import com.yunfeiyun.agmp.fms.domain.reqvo.FmsPlanReqVo;
import com.yunfeiyun.agmp.fms.domain.resvo.FmsBlockResVo;
import com.yunfeiyun.agmp.fms.domain.resvo.FmsPlanResVo;
import com.yunfeiyun.agmp.fms.mapper.FmsBlockMapper;
import com.yunfeiyun.agmp.fms.util.DataAuthUtil;
import com.yunfeiyun.agmp.fms.service.IFmsBlockService;
import com.yunfeiyun.agmp.fms.service.IFmsLandService;
import com.yunfeiyun.agmp.fms.service.IFmsPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 地块Controller
 * 
 * @author 杨晓辉
 * @date 2023-05-15
 */
@RestController
@RequestMapping("/fms/block")
public class FmsBlockController extends BaseController
{
    @Autowired
    private IFmsBlockService fmsBlockService;
    @Autowired
    private FmsBlockMapper fmsBlockMapper;
    @Autowired
    private IFmsLandService fmsLandService;
    @Autowired
    private IFmsPlanService fmsPlanService;
    @Autowired
    private ResManager resManager;
    @Autowired
    private DataAuthUtil dataAuthUtil;


    /**
     * 查询地块列表
     */
    @PreAuthorize("@ss.hasPermi('fms:block:list')")
    @GetMapping("/list")
    public TableDataInfo list(FmsBlock fmsBlock)
    {
        boolean b = dataAuthUtil.isValidate();
        if (b) {
            //true需要进行权限校验。下拉框基地列表查询需要包含分配的基地以及分配地块所属基地
            List<String> strings = dataAuthUtil.blockList();
            if (strings.size() == 0) {
                return getDataTable(new ArrayList<>());
            }
            fmsBlock.setDataFilter(true);
            fmsBlock.setBlockIds(strings);
        }

        startPage();
        List<FmsBlock> list = fmsBlockService.selectFmsBlockList(fmsBlock);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('fms:block:select:list')")
    @GetMapping("/select/list")
    public TableDataInfo selectList(FmsBlock fmsBlock)
    {
        boolean b = dataAuthUtil.isValidate();
        if (b) {
            //true需要进行权限校验。下拉框基地列表查询需要包含分配的基地以及分配地块所属基地
            List<String> strings = dataAuthUtil.blockList();
            if (strings.size() == 0) {
                return getDataTable(new ArrayList<>());
            }
            fmsBlock.setDataFilter(true);
            fmsBlock.setBlockIds(strings);
        }

        List<FmsBlock> list = fmsBlockService.selectFmsBlockList(fmsBlock);
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (FmsBlock block : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("blockId", block.getBlockId());
            map.put("blockName", block.getBlockName());
            resultList.add(map);
        }
        return getDataTable(resultList);
    }

    /**
     * 查询地块列表
     */
    @PreAuthorize("@ss.hasPermi('fms:block:plan:list')")
    @GetMapping("/plan/list")
    public TableDataInfo selectFmsBlockHasPlan(FmsBlockReqVo reqVo)
    {
        boolean b = dataAuthUtil.isValidate();
        if (b) {
            //true需要进行权限校验。下拉框基地列表查询需要包含分配的基地以及分配地块所属基地
            List<String> strings = dataAuthUtil.blockList();
            if (strings.size() == 0) {
                return getDataTable(new ArrayList<>());
            }
            reqVo.setDataFilter(true);
            reqVo.setBlockIds(strings);
        }

        startPage();
        List<FmsBlockResVo> list = fmsBlockService.selectFmsBlockHasPlan(reqVo);
        return getDataTable(list);
    }


    /**
     * 导出地块列表
     */
    @PreAuthorize("@ss.hasPermi('fms:block:export')")
    @Log(title = "地块", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FmsBlock fmsBlock)
    {
        List<FmsBlock> list = fmsBlockService.selectFmsBlockList(fmsBlock);
        ExcelUtil<FmsBlock> util = new ExcelUtil<FmsBlock>(FmsBlock.class);
        util.exportExcel(response, list, "地块数据");
    }

    /**
     * 获取地块详细信息
     */
    @PreAuthorize("@ss.hasPermi('fms:block:info')")
    @GetMapping(value = "/info")
    public AjaxResult getInfo(@RequestParam("blockId") String blockId)
    {
        return success(fmsBlockService.selectFmsBlockByBlockId(blockId));
    }

    /**
     * 获取地块详细信息
     */
    @PreAuthorize("@ss.hasPermi('fms:block:plan:info')")
    @GetMapping(value = "/plan/info")
    public AjaxResult getBlockInfo(@RequestParam("blockId") String blockId)
    {
        FmsBlockResVo fmsBlockResVo = fmsBlockService.selectFmsBlockInfoByBlockId(blockId);
        FmsPlanReqVo reqVo = new FmsPlanReqVo();
        reqVo.setBlockId(blockId);
        reqVo.setPlanStatus(CommonEnums.PLAN_STATUS_NOT_START.getCode() + "," + CommonEnums.PLAN_STATUS_START.getCode());
        List<FmsPlanResVo> fmsPlanResVos = fmsPlanService.selectPlanList(reqVo);
        fmsBlockResVo.setPlanList(fmsPlanResVos);
        return success(fmsBlockResVo);
    }

    /**
     * 新增地块
     */
    @PreAuthorize("@ss.hasPermi('fms:block:add')")
    @Log(title = "地块", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody @Valid FmsBlock fmsBlock)
    {
        FmsLand fmsLand = fmsLandService.selectFmsLandByLandId(fmsBlock.getLandId());
        if (fmsLand == null) {
            return AjaxResult.error(ErrorCode.INVALID_PARAMETER.getCode());
        }

        /* 判断同一基地下地块名称是否重复 */
        FmsBlock reqVo = new FmsBlock();
        reqVo.setLandId(fmsBlock.getLandId());
        reqVo.setBlockNameEq(fmsBlock.getBlockName());
        List<FmsBlock> list = fmsBlockService.selectFmsBlockList(fmsBlock);
        if (list.size() > 0) {
            return AjaxResult.error(ErrorCode.FMS_BLOCK_EXIST.getCode(), ErrorCode.FMS_BLOCK_EXIST.getMessage());
        }

        return fmsBlockService.insertFmsBlock(fmsBlock, fmsLand);
    }

    /**
     * 修改地块
     */
    @PreAuthorize("@ss.hasPermi('fms:block:edit')")
    @Log(title = "地块", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody @Valid FmsBlock fmsBlock)
    {
        FmsLand fmsLand = fmsLandService.selectFmsLandByLandId(fmsBlock.getLandId());
        if (fmsLand == null) {
            return AjaxResult.error(ErrorCode.INVALID_PARAMETER.getCode());
        }

        /* 判断同一基地下地块名称是否重复 */
        FmsBlock fmsBlock1 = fmsBlockService.selectFmsBlockByBlockId(fmsBlock.getBlockId());
        if (!fmsBlock1.getBlockName().equals(fmsBlock.getBlockName())) {
            FmsBlock reqVo = new FmsBlock();
            reqVo.setLandId(fmsBlock.getLandId());
            reqVo.setBlockNameEq(fmsBlock.getBlockName());
            List<FmsBlock> list = fmsBlockService.selectFmsBlockList(fmsBlock);
            if (list.size() > 0) {
                return AjaxResult.error(ErrorCode.FMS_BLOCK_EXIST.getCode(), ErrorCode.FMS_BLOCK_EXIST.getMessage());
            }
        }

        return fmsBlockService.updateFmsBlock(fmsBlock, fmsLand);
    }

    /**
     * 删除地块
     */
    @PreAuthorize("@ss.hasPermi('fms:block:delete')")
    @Log(title = "地块", businessType = BusinessType.DELETE)
	@DeleteMapping("/delete")
    public AjaxResult remove(@RequestParam("blockIds") String[] blockIds)
    {
        for (int i = 0; i < blockIds.length; i++) {
            int count = fmsBlockMapper.selectValidDataNumber(blockIds[i]);
            if (count > 0) {
                return AjaxResult.error(ErrorCode.DEL_CURNODE_ERROR.getCode(), ErrorCode.DEL_CURNODE_ERROR.getMessage());
            }
        }
        return fmsBlockService.deleteFmsBlockByBlockIds(blockIds);
    }

    /**
     * 地块图片上传
     */
    @PreAuthorize("@ss.hasPermi('fms:block:preview:upload')")
    @Log(title = "地块图片上传", businessType = BusinessType.UPDATE)
    @PostMapping("/preview/upload")
    public AjaxResult uploadBlockPreview(MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
            SysRes sysRes  = resManager.uploadRes( ResConstants.BizType.BLOCK, ResConstants.mediaType.IMG,"", file,getLoginUser());
            return success(sysRes);
        }
        return error(ErrorCode.UPLOAD_FAIL.getCode());
    }
}
