package tech.glinfo.enbao.modules.sh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tech.glinfo.enbao.common.annotation.ApiLog;
import tech.glinfo.enbao.common.annotation.Login;
import tech.glinfo.enbao.common.utils.DateUtils;
import tech.glinfo.enbao.common.utils.R;
import tech.glinfo.enbao.common.utils.StringUtils;
import tech.glinfo.enbao.common.validator.ValidatorUtils;
import tech.glinfo.enbao.modules.sh.entity.ShDeviceTimingEntity;
import tech.glinfo.enbao.modules.sh.form.ShDeviceTimingForm;
import tech.glinfo.enbao.modules.sh.service.OtherShDeviceTimingService;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/shDeviceTiming")
@Api(value = "智能家居定时")
public class ShDeviceTimingController {


    @Autowired
    private OtherShDeviceTimingService otherShDeviceTimingService;

    @Login
    @PostMapping("saveOrUpdate")
    @ApiOperation("新增、修改定时(智能插座、开关、窗帘)")
    @ApiLog("新增、修改定时")
    public R saveOrUpdate(@RequestBody ShDeviceTimingForm form) throws InvocationTargetException, IllegalAccessException {
        //表单校验
        ValidatorUtils.validateEntity(form);

        ShDeviceTimingEntity timingEntity = new ShDeviceTimingEntity();
        BeanUtils.copyProperties(timingEntity, form);
        if (StringUtils.isBlank(form.getRepeatTime())) {
            //设置执行时间
            String today = DateUtils.format(new Date());
            if (StringUtils.isNotBlank(form.getTime())) {
                timingEntity.setTime(today + " " + form.getTime());
            }
            if (StringUtils.isNotBlank(form.getCloseTime())) {
                timingEntity.setCloseTime(today + " " + form.getCloseTime());
            }
            timingEntity.setRepeats(0);
        } else {
            timingEntity.setRepeats(1);
        }
        return otherShDeviceTimingService.saveOrUpdate(timingEntity) ? R.ok() : R.error("操作失败");
    }


    @Login
    @PostMapping("saveOrUpdate1")
    @ApiOperation("新增、修改定时(智能插座、开关、窗帘)")
    @ApiLog("新增、修改定时")
    public R saveOrUpdate1(@RequestBody List<ShDeviceTimingForm> list) throws InvocationTargetException, IllegalAccessException {
        //表单校验
//        ValidatorUtils.validateEntity(form);
        String position = null;
        for (ShDeviceTimingForm timingForm : list) {
            ValidatorUtils.validateEntity(timingForm);
            ShDeviceTimingEntity timingEntity = new ShDeviceTimingEntity();
            BeanUtils.copyProperties(timingEntity, timingForm);
            if (StringUtils.isBlank(timingForm.getRepeatTime())) {
                timingEntity.setRepeats(0);
            } else {
                timingEntity.setRepeats(1);
            }
            if (timingForm.getId() == null) {
                if (position == null) {
                    position = DateUtils.format(new Date(), "yyyyMMddHHmmssSSS") + StringUtils.random(4, StringUtils.RandomType.INT);
                }
//                timingEntity.setPosition(position);
            }
            otherShDeviceTimingService.saveOrUpdate(timingEntity);
        }

        return R.ok();
    }

    @Login
    @GetMapping("listById/{id}")
    @ApiOperation("定时列表(智能插座、开关、窗帘)")
    @ApiLog("定时列表")
    public R listById(@PathVariable("id") Integer id) {
        List<ShDeviceTimingEntity> list = otherShDeviceTimingService.listById(id);
        for (ShDeviceTimingEntity entity : list) {
            /*if (entity.getTime().length() > 5) {
                entity.setTime(entity.getTime().substring(11, 16));
            }*/
            if (entity.getRepeats() == 0) {
                entity.setRepeatTime("一次");
            } else {
                StringBuilder sb = new StringBuilder();
                String[] repeatTimes = entity.getRepeatTime().split(",");
                for (int i = 0; i < repeatTimes.length; i++) {
                    switch (repeatTimes[i]) {
                        case "1":
                            sb.append("周一");
                            break;
                        case "2":
                            sb.append("周二");
                            break;
                        case "3":
                            sb.append("周三");
                            break;
                        case "4":
                            sb.append("周四");
                            break;
                        case "5":
                            sb.append("周五");
                            break;
                        case "6":
                            sb.append("周六");
                            break;
                        case "7":
                            sb.append("周日");
                            break;
                    }
                    if (i + 1 != repeatTimes.length) {
                        sb.append('、');
                    }
                }
                entity.setRepeatTime(sb.toString());
            }
        }
        return R.ok().put("list", list);
    }


    @Login
    @GetMapping("info/{id}")
    @ApiOperation("定时详情(智能插座、开关、窗帘)")
    @ApiLog("定时详情")
    public R info(@PathVariable("id") Integer id) {
        return R.ok().put("timing", otherShDeviceTimingService.getById(id));
    }

    @Login
    @GetMapping("info1")
    @ApiOperation("定时详情(智能插座、开关、窗帘)")
    @ApiLog("定时详情")
    public R info1(@RequestParam Map<String, Object> params) {
        String id = (String) params.get("id");
        List<ShDeviceTimingEntity> list = otherShDeviceTimingService.list(new QueryWrapper<ShDeviceTimingEntity>().eq("position", id));

        return R.ok().put("list", list);
    }

    @Login
    @PostMapping("delete")
    @ApiOperation("删除定时(智能插座、开关、窗帘)")
    @ApiLog("删除定时")
    public R delete(@RequestBody Map<String, Object> params) {
        Integer id = (Integer) params.get("id");
        if (StringUtils.isBlank(id)) {
            return R.error("缺少参数");
        }
        return otherShDeviceTimingService.removeById(id) ? R.ok() : R.error("操作失败");
    }

    @Login
    @PostMapping("updateStatus")
    @ApiOperation("修改状态(智能插座、开关、窗帘)")
    @ApiLog("修改状态")
    public R updateStatus(@RequestBody Map<String, Object> params) {
        Integer id = (Integer) params.get("id");
        Integer status = (Integer) params.get("status");
        if (StringUtils.isBlank(id, status)) {
            return R.error("缺少参数");
        }
        ShDeviceTimingEntity timingEntity = new ShDeviceTimingEntity();
        timingEntity.setId(id);
        timingEntity.setStatus(status);
        return otherShDeviceTimingService.updateById(timingEntity) ? R.ok() : R.error("操作失败");
    }

}