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.domain.entity.SysDictData;
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.StringUtils;
import com.yunfeiyun.agmp.common.utils.poi.ExcelUtil;
import com.yunfeiyun.agmp.common.web.system.domain.SysRes;
import com.yunfeiyun.agmp.common.web.system.service.ISysDictDataService;
import com.yunfeiyun.agmp.fms.domain.FmsCrop;
import com.yunfeiyun.agmp.fms.domain.reqvo.AddNoValueReqVo;
import com.yunfeiyun.agmp.fms.domain.resvo.FmsCropResVo;
import com.yunfeiyun.agmp.fms.service.IFmsCropService;
import com.yunfeiyun.agmp.fms.service.IFmsPeriodService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
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-16
 */
@RestController
@RequestMapping("/fms/crop")
public class FmsCropController extends BaseController
{
    @Autowired
    private IFmsCropService fmsCropService;
    @Autowired
    private ResManager resManager;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private IFmsPeriodService fmsPeriodService;

    /**
     * 查询作物列表
     */
    @PreAuthorize("@ss.hasPermi('fms:crop:list')")
    @GetMapping("/list")
    public TableDataInfo list(FmsCrop fmsCrop)
    {
        startPage();
        List<FmsCropResVo> list = fmsCropService.selectFmsCropList(fmsCrop);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('fms:crop:select:list')")
    @GetMapping("/select/list")
    public TableDataInfo selectList(FmsCrop fmsCrop)
    {
        List<FmsCropResVo> list = fmsCropService.selectFmsCropList(fmsCrop);
        return getDataTable(list);
    }

    /**
     * 导出作物列表
     */
    @PreAuthorize("@ss.hasPermi('fms:crop:export')")
    @Log(title = "作物", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FmsCrop fmsCrop)
    {
        List<FmsCropResVo> list = fmsCropService.selectFmsCropList(fmsCrop);
        ExcelUtil<FmsCropResVo> util = new ExcelUtil<FmsCropResVo>(FmsCropResVo.class);
        util.exportExcel(response, list, "作物数据");
    }

    /**
     * 获取作物详细信息
     */
    @PreAuthorize("@ss.hasPermi('fms:crop:info')")
    @GetMapping(value = "/info")
    public AjaxResult getInfo(@RequestParam("cropId") String cropId)
    {
        return success(fmsCropService.selectFmsCropByCropId(cropId));
    }

    /**
     * 根据类型查询作物名称集合
     */
    @PreAuthorize("@ss.hasPermi('fms:crop:name:list')")
    @GetMapping(value = "/name/list")
    public AjaxResult selectFmsCropNameByCropMaintype(@RequestParam(value = "cropMaintype", required = false) String cropMaintype)
    {
        return success(fmsCropService.selectFmsCropNameByCropMaintype(cropMaintype));
    }

    @PreAuthorize("@ss.hasPermi('fms:crop:name:select:list')")
    @GetMapping(value = "/name/select/list")
    public AjaxResult selectNameList(@RequestParam(value = "cropMaintype", required = false) String cropMaintype)
    {
        List<FmsCrop> fmsCrops = fmsCropService.selectFmsCropNameByCropMaintype(cropMaintype);
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (FmsCrop crop : fmsCrops) {
            Map<String, Object> map = new HashMap<>();
            map.put("cropName", crop.getCropName());
            resultList.add(map);
        }
        return success(resultList);
    }

    /**
     * 获取有生长周期的作物
     */
    @PreAuthorize("@ss.hasPermi('fms:crop:period:list')")
    @GetMapping(value = "/period/list")
    public AjaxResult selectFmsCropHasPeriod()
    {
        return success(fmsPeriodService.selectFmsCropHasPeriod());
    }

    /**
     * 新增作物
     */
    @PreAuthorize("@ss.hasPermi('fms:crop:add')")
    @Log(title = "作物", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Valid @RequestBody FmsCrop fmsCrop)
    {
        FmsCrop reqVo = new FmsCrop();
        reqVo.setCropName(fmsCrop.getCropName());
        reqVo.setCropType(fmsCrop.getCropType());
        List<FmsCropResVo> list = fmsCropService.selectFmsCropList(reqVo);
        if (list.size() > 0) {
            return AjaxResult.error(ErrorCode.FMS_CROP_EXIST.getCode(), ErrorCode.FMS_CROP_EXIST.getMessage());
        }
        return toAjax(fmsCropService.insertFmsCrop(fmsCrop));
    }

    /**
     * 修改作物
     */
    @PreAuthorize("@ss.hasPermi('fms:crop:edit')")
    @Log(title = "作物", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@Valid @RequestBody FmsCrop fmsCrop)
    {
        FmsCrop fmsCrop1 = fmsCropService.selectFmsCropByCropId(fmsCrop.getCropId());
        if (!fmsCrop1.getCropName().equals(fmsCrop.getCropName()) || !fmsCrop1.getCropType().equals(fmsCrop.getCropType())) {
            FmsCrop reqVo = new FmsCrop();
            reqVo.setCropName(fmsCrop.getCropName());
            reqVo.setCropType(fmsCrop.getCropType());
            List<FmsCropResVo> list = fmsCropService.selectFmsCropList(reqVo);
            if (list.size() > 0) {
                return AjaxResult.error(ErrorCode.FMS_CROP_EXIST.getCode(), ErrorCode.FMS_CROP_EXIST.getMessage());
            }
        }

        return toAjax(fmsCropService.updateFmsCrop(fmsCrop));
    }

    /**
     * 删除作物
     */
    @PreAuthorize("@ss.hasPermi('fms:crop:delete')")
    @Log(title = "作物", businessType = BusinessType.DELETE)
	@DeleteMapping("/delete")
    public AjaxResult remove(@RequestParam("cropIds") String[] cropIds)
    {
        return toAjax(fmsCropService.deleteFmsCropByCropIds(cropIds));
    }

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

    /**
     * 新增字典类型
     */
    @PreAuthorize("@ss.hasPermi('fms:crop:type:add')")
    @Log(title = "字典数据", businessType = BusinessType.INSERT)
    @PostMapping("/type/add")
    public AjaxResult addNoValue(@Validated @RequestBody AddNoValueReqVo reqVo)
    {
        /* 判断是否存在 */
        SysDictData dictData = new SysDictData();
        dictData.setDicttypeCode(reqVo.getDicttypeCode());
        dictData.setDictNameEq(reqVo.getDictName());
        List<SysDictData> dictDataList = dictDataService.selectDictDataList(dictData);
        if (dictDataList.size() > 0) {
            return AjaxResult.error(ErrorCode.ADD_DUPLICATE_ERROR.getCode(), ErrorCode.ADD_DUPLICATE_ERROR.getMessage());
        }

        /* 新增 */
        SysDictData dict = new SysDictData();
        BeanUtils.copyProperties(reqVo, dict);
        //查询当前字典类型的数值的最大值
        Integer max = dictDataService.maxValueByDictType(dict.getDicttypeCode());
        max = max == null ? 0 : max;
        if (StringUtils.isEmpty(dict.getDictValue())) {
            dict.setDictValue(String.valueOf(max+1));
        }

        if (dict.getDictSeq() == null) {
            dict.setDictSeq(Long.valueOf(max+1));
        }
        dict.setDictAvlstatus(CommonEnums.DICT_STATUS_NORMAL.getCode());
        dict.setDictCreator(getUserId());
        return toAjax(dictDataService.insertDictData(dict));
    }
}
