package com.gxwebsoft.tower.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.tower.entity.TowerProject;
import com.gxwebsoft.tower.service.TowerProjectService;
import com.gxwebsoft.tower.service.TowerSecurityService;
import com.gxwebsoft.tower.entity.TowerSecurity;
import com.gxwebsoft.tower.param.TowerSecurityParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 安全检查控制器
 *
 * @author 科技小王子
 * @since 2024-02-22 13:44:23
 */
@Api(tags = "安全检查管理")
@RestController
@RequestMapping("/api/tower/tower-security")
public class TowerSecurityController extends BaseController {
    @Resource
    private TowerSecurityService towerSecurityService;
    @Resource
    private TowerProjectService towerProjectService;

    @PreAuthorize("hasAuthority('tower:towerSecurity:list')")
    @OperationLog
    @ApiOperation("分页查询安全检查")
    @GetMapping("/page")
    public ApiResult<PageResult<TowerSecurity>> page(TowerSecurityParam param) {
//        PageParam<TowerSecurity, TowerSecurityParam> page = new PageParam<>(param);
//        page.setDefaultOrder("create_time desc");
//        return success(towerSecurityService.page(page, page.getWrapper()));
        // 使用关联查询
        return success(towerSecurityService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('tower:towerSecurity:list')")
    @OperationLog
    @ApiOperation("查询全部安全检查")
    @GetMapping()
    public ApiResult<List<TowerSecurity>> list(TowerSecurityParam param) {
        PageParam<TowerSecurity, TowerSecurityParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        return success(towerSecurityService.list(page.getOrderWrapper()));
        // 使用关联查询
        //return success(towerSecurityService.listRel(param));
    }

    @PreAuthorize("hasAuthority('tower:towerSecurity:list')")
    @OperationLog
    @ApiOperation("根据id查询安全检查")
    @GetMapping("/{id}")
    public ApiResult<TowerSecurity> get(@PathVariable("id") Integer id) {
        return success(towerSecurityService.getById(id));
        // 使用关联查询
        //return success(towerSecurityService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('tower:towerSecurity:save')")
    @OperationLog
    @ApiOperation("添加安全检查")
    @PostMapping()
    public ApiResult<?> save(@RequestBody TowerSecurity towerSecurity) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
          towerSecurity.setUserId(loginUser.getUserId());
        }
        // 生成编号
        DateTime date = DateUtil.date();
        final String code = DateUtil.format(date, "yyyyMMddHH");
        towerSecurity.setSecurityCode(code.concat(towerSecurity.getProjectId().toString()));
        if (towerSecurityService.save(towerSecurity)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('tower:towerSecurity:update')")
    @OperationLog
    @ApiOperation("修改安全检查")
    @PutMapping()
    public ApiResult<?> update(@RequestBody TowerSecurity towerSecurity) {
        if (towerSecurityService.updateById(towerSecurity)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('tower:towerSecurity:remove')")
    @OperationLog
    @ApiOperation("删除安全检查")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (towerSecurityService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('tower:towerSecurity:save')")
    @OperationLog
    @ApiOperation("批量添加安全检查")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<TowerSecurity> list) {
        if (towerSecurityService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('tower:towerSecurity:update')")
    @OperationLog
    @ApiOperation("批量修改安全检查")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<TowerSecurity> batchParam) {
        if (batchParam.update(towerSecurityService, "security_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('tower:towerSecurity:remove')")
    @OperationLog
    @ApiOperation("批量删除安全检查")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (towerSecurityService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

//  @Scheduled(cron = "0 0 0 1 * ?")
  @Scheduled(fixedDelay = 5000, initialDelay = 5000)
  @Transactional(rollbackFor = {Exception.class})
  public void wxAccountTask() {
    System.out.println("任务：在建项目每月1号生产保养计划 = ");
    final DateTime currentDate = DateUtil.date();
    int currentMonth = DateUtil.month(currentDate) + 1;
    final List<TowerProject> list = towerProjectService.list(new LambdaQueryWrapper<TowerProject>().eq(TowerProject::getProjectStatus, "建设中").ne(TowerProject::getPlanMonth,currentMonth));
    System.out.println("list = " + list.size());
    if (!CollectionUtils.isEmpty(list)) {
      list.forEach(d -> {
        // 生成保养计划
        TowerSecurity towerSecurity = new TowerSecurity();
        towerSecurity.setProjectId(d.getProjectId());
        towerSecurity.setProjectName(d.getProjectName());
        towerSecurity.setAddress(d.getProjectAddress());
        towerSecurity.setTenantId(10049);
        DateTime date = DateUtil.date();
        final String code = DateUtil.format(date, "yyyyMMdd");
        towerSecurity.setSecurityCode(code.concat(d.getProjectId().toString()));
        d.setPlanMonth(currentMonth);
        towerProjectService.updateById(d);
        towerSecurityService.save(towerSecurity);
      });
    }
  }

}
