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.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.FmsLand;
import com.yunfeiyun.agmp.fms.domain.resvo.FmsLandTotalResVo;
import com.yunfeiyun.agmp.fms.util.DataAuthUtil;
import com.yunfeiyun.agmp.fms.service.IFmsBlockService;
import com.yunfeiyun.agmp.fms.service.IFmsLandService;
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/land")
public class FmsLandController extends BaseController
{
    @Autowired
    private IFmsLandService fmsLandService;
    @Autowired
    private IFmsBlockService fmsBlockService;

    @Autowired
    private ResManager resManager;
    @Autowired
    private DataAuthUtil dataAuthUtil;

    /**
     * 查询基地列表
     */
    @PreAuthorize("@ss.hasPermi('fms:land:list')")
    @GetMapping("/list")
    public TableDataInfo list(FmsLand fmsLand)
    {
        boolean b = dataAuthUtil.isValidate();
        if (b) {
            //true需要进行权限校验。基地列表需要分配的基地才能查询
            List<String> strings = dataAuthUtil.landList();
            if (strings.size() == 0) {
                return getDataTable(new ArrayList<>());
            }
            fmsLand.setDataFilter(true);
            fmsLand.setLandIds(strings);
        }
        startPage();
        List<FmsLand> list = fmsLandService.selectFmsLandList(fmsLand);
        return getDataTable(list);
    }

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

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

        List<FmsLand> list = fmsLandService.selectFmsLandList(fmsLand);
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (FmsLand land : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("landId", land.getLandId());
            map.put("landName", land.getLandName());
            resultList.add(map);
        }
        return getDataTable(resultList);
    }

    /**
     * 导出基地列表
     */
    @PreAuthorize("@ss.hasPermi('fms:land:export')")
    @Log(title = "基地", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FmsLand fmsLand)
    {
        List<FmsLand> list = fmsLandService.selectFmsLandList(fmsLand);
        ExcelUtil<FmsLand> util = new ExcelUtil<FmsLand>(FmsLand.class);
        util.exportExcel(response, list, "基地数据");
    }

    /**
     * 获取基地详细信息
     */
    @PreAuthorize("@ss.hasPermi('fms:land:info')")
    @GetMapping(value = "/info")
    public AjaxResult getInfo(@RequestParam("landId") String landId)
    {
        return success(fmsLandService.selectFmsLandByLandId(landId));
    }

    /**
     * 获取基地统计信息
     */
    @PreAuthorize("@ss.hasPermi('fms:land:top:stat')")
    @GetMapping(value = "/top/stat")
    public AjaxResult selectFmsLandTotal(FmsLand fmsLand)
    {
        boolean b = dataAuthUtil.isValidate();
        if (b) {
            //true需要进行权限校验。下拉框基地列表查询需要包含分配的基地以及分配地块所属基地
            List<String> strings = dataAuthUtil.landListOfBlock();
            if (strings.size() == 0) {
                FmsLandTotalResVo resVo = new FmsLandTotalResVo();
                resVo.setCount("0");
                resVo.setLandAreaSum("0");
                resVo.setLandBlockcountSum("0");
                resVo.setLandDevcountSum("0");
                return success(resVo);
            }
            fmsLand.setDataFilter(true);
            fmsLand.setLandIds(strings);
        }
        FmsLandTotalResVo resVo = fmsLandService.selectFmsLandTotal(fmsLand);
        int i = fmsLandService.selectDevCount(fmsLand);
        resVo.setLandDevcountSum(i+"");
        return success(resVo);
    }

    /**
     * 新增基地
     */
    @PreAuthorize("@ss.hasPermi('fms:land:add')")
    @Log(title = "基地", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    public AjaxResult add(@RequestBody @Valid FmsLand fmsLand)
    {
        /* 判断基地名称不能重复 */
        FmsLand reqVo = new FmsLand();
        reqVo.setLandNameEq(fmsLand.getLandName());
        List<FmsLand> list = fmsLandService.selectFmsLandList(reqVo);
        if (list.size() > 0) {
            return AjaxResult.error(ErrorCode.FMS_LAND_EXIST.getCode(), ErrorCode.FMS_LAND_EXIST.getMessage());
        }

        fmsLand.setLandDevcount(0l);
        fmsLand.setLandBlockcount(0l);
        return toAjax(fmsLandService.insertFmsLand(fmsLand));
    }

    /**
     * 修改基地
     */
    @PreAuthorize("@ss.hasPermi('fms:land:edit')")
    @Log(title = "基地", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/edit")
    public AjaxResult edit(@RequestBody @Valid FmsLand fmsLand)
    {
        /* 判断基地名称不能重复 */
        FmsLand fmsLand1 = fmsLandService.selectFmsLandByLandId(fmsLand.getLandId());
        if (!fmsLand1.getLandName().equals(fmsLand.getLandName())) {
            FmsLand reqVo = new FmsLand();
            reqVo.setLandNameEq(fmsLand.getLandName());
            List<FmsLand> list = fmsLandService.selectFmsLandList(reqVo);
            if (list.size() > 0) {
                return AjaxResult.error(ErrorCode.FMS_LAND_EXIST.getCode(), ErrorCode.FMS_LAND_EXIST.getMessage());
            }
        }

        return toAjax(fmsLandService.updateFmsLand(fmsLand));
    }

    /**
     * 删除基地
     */
    @PreAuthorize("@ss.hasPermi('fms:land:delete')")
    @Log(title = "基地", businessType = BusinessType.DELETE)
	@DeleteMapping("/delete")
    public AjaxResult delete(@RequestParam("landIds") String[] landIds)
    {
        Integer count = 0;
        for (String landId : landIds) {
            Integer integer = fmsBlockService.selectCountByLandId(landId);
            count += integer;
        }
        if (count > 0) {
            return AjaxResult.error(ErrorCode.DEL_CURNODE_ERROR.getCode(), ErrorCode.DEL_CURNODE_ERROR.getMessage());
        }
        return toAjax(fmsLandService.deleteFmsLandByLandIds(landIds));
    }


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

}
