package org.springblade.business.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.business.entity.WeatherInfo;
import org.springblade.business.vo.WeatherInfoVo;
import org.springblade.business.service.WeatherInfoService;
import org.springblade.manager.entity.ProjectContractArea;
import org.springblade.manager.feign.ProjectContractAreaClient;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springblade.core.mp.support.Condition;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 天气台账控制器
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping(value = "weather")
@Api(tags = "天气台账接口")
public class WeatherController {

    private final WeatherInfoService weatherInfoService;

    private final ProjectContractAreaClient projectContractAreaClient;

    /**
     * 单个或批量删除天气台账
     * @param ids 数据id集合
     * @return 删除结果
     */
    @PostMapping(value = "removeWeatherByIds")
    @ApiOperation(value = "删除(批量或单个)", notes = "传入ids")
    public R<Boolean> removeWeatherByIds(@ApiParam(value = "主键集合", required = true) @RequestParam String ids){
        return R.status(this.weatherInfoService.removeBatchByIds(Func.toLongList(ids)));
    }

    /**
     * 修改天气台账
     * @param weatherInfo 天气台账新数据
     * @return 修改结果
     */
    @PostMapping(value = "updateWeatherById")
    @ApiOperation(value = "修改", notes = "传入WeatherInfo")
    public R<Boolean> updateWeatherById(@RequestBody WeatherInfo weatherInfo){
        //记录修改时间及修改人
        setUserData(weatherInfo, true);
        return R.status(this.weatherInfoService.updateById(weatherInfo));
    }

    /**
     * 根据年份获取当年所有天气情况
     * @param yearMonthDay 所选年份-月-日，也可以其他组合
     * @return 结果集
     */
    @GetMapping(value = "queryWeatherAllByYear")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yearMonthDay", value = "年份", required = true),
            @ApiImplicitParam(name = "contractId", value = "合同段ID", required = true)
    })
    public R<List<Map<String,List<Map<String,Object>>>>> queryWeatherAllByYear(@RequestParam String yearMonthDay, @RequestParam String contractId){
        return R.data(this.weatherInfoService.queryWeatherAllByYear(yearMonthDay, contractId));
    }

    /**
     * 天气台账列表分页
     * @param vo 查询条件
     * @param query 分页条件
     * @return 查询结果
     */
    @GetMapping(value = "queryWeatherPage")
    @ApiOperation(value = "天气台账列表分页", notes = "传入WeatherInfo")
    public R<IPage<WeatherInfo>> queryWeatherPage(WeatherInfoVo vo,Query query){
        Map<String,Object> weatherMap = new HashMap<>();

        //通过合同段获取区域编码
        ProjectContractArea area = this.projectContractAreaClient.queryContractAreaByContractId(vo.getContractId());
        if(area == null){
            return R.data(-1, null, "数据操作失败");
        }
        weatherMap.put("contractAreaId", area.getId());

        if(StringUtils.isNotEmpty(vo.getRecordTime())){
            weatherMap.put("recordTime", vo.getRecordTime());
        }
        if(StringUtils.isNotEmpty(vo.getWeather())){
            weatherMap.put("weather", vo.getWeather());
        }

        if(weatherMap.containsKey("recordTime") && weatherMap.get("recordTime") != null && StringUtils.isNotEmpty(weatherMap.get("recordTime").toString())){
            String recordTime = weatherMap.get("recordTime").toString();
            if(recordTime.contains("~")){
                //说明是时间区间
                String[] recordTimes = recordTime.split("~");
                //因为是区间，所以需要删除原本的条件
                weatherMap.remove("recordTime");
                return R.data(this.weatherInfoService.page(Condition.getPage(query), Condition.getQueryWrapper(weatherMap, WeatherInfo.class).lambda().between(WeatherInfo::getRecordTime, recordTimes[0].trim(), recordTimes[1].trim()).orderByDesc(WeatherInfo::getRecordTime)));
            } else {
                return R.data(this.weatherInfoService.page(Condition.getPage(query), Condition.getQueryWrapper(weatherMap, WeatherInfo.class).lambda().orderByDesc(WeatherInfo::getRecordTime)));
            }
        } else {
            return R.data(this.weatherInfoService.page(Condition.getPage(query), Condition.getQueryWrapper(weatherMap, WeatherInfo.class).lambda().orderByDesc(WeatherInfo::getRecordTime)));
        }
    }

    /**
     * 查询单个数据
     * @param id 数据Id
     * @return 数据
     */
    @PostMapping(value = "queryWeatherById")
    @ApiOperation(value = "详情", notes = "传入WeatherInfo")
    public R<WeatherInfo> queryWeatherById(@RequestParam String id){
        try{
            return R.data(this.weatherInfoService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.data(null);
    }

    /**
     * 普通新增，多用于补天气
     * @param weatherInfoVo 新增的天气信息
     * @return 新增结果
     */
    @PostMapping(value = "saveWeatherInfo")
    @ApiOperation(value = "新增", notes = "传入WeatherInfo")
    public R<Boolean> saveWeatherInfo(@RequestBody WeatherInfoVo weatherInfoVo){
        try{

            //通过合同段获取区域编码
            ProjectContractArea area = this.projectContractAreaClient.queryContractAreaByContractId(weatherInfoVo.getContractId());
            if(area == null){
                return R.data(-1, null, "数据操作失败");
            }
            //设置信息
            weatherInfoVo.setContractAreaId(String.valueOf(area.getId()));

            WeatherInfo weatherInfo = new WeatherInfo();
            BeanUtils.copyProperties(weatherInfoVo, weatherInfo);
            //设置用户信息
            setUserData(weatherInfo, false);
            weatherInfo.setRecordTime(DateUtil.parse(weatherInfoVo.getRecordTime(), "yyyy-MM-dd"));

            return R.status(this.weatherInfoService.save(weatherInfo));
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.status(false);
    }

    //设置登录用户信息
    private void setUserData(WeatherInfo weatherInfo, boolean isUpd){
        //获取当前登录人
        BladeUser user = AuthUtil.getUser();
        //记录修改时间及修改人
        if(isUpd){
            weatherInfo.setUpdateUser(user.getUserId());
            weatherInfo.setUpdateTime(new Date());
        } else {
            weatherInfo.setCreateUser(user.getUserId());
            weatherInfo.setCreateDept(user.getDeptId());
        }
    }

}
