package com.gci.boot.modules.vehicles.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gci.boot.annotation.Query.handle.QueryGenerator;
import com.gci.boot.common.log.annotation.AddSysLog;
import com.gci.boot.common.validated.SaveValidated;
import com.gci.boot.common.validated.UpdateValidated;
import com.gci.boot.common.vo.Result;
import com.gci.boot.modules.projects.entity.Projects;
import com.gci.boot.modules.system.vo.LoginUser;
import com.gci.boot.modules.vehicles.entity.TbUpkeepRule;
import com.gci.boot.modules.vehicles.entity.TbViolationRecord;
import com.gci.boot.modules.vehicles.service.ITbUpkeepRuleService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

@Api(tags="保养规则")
@Slf4j
@RestController
@RequestMapping("/vehicles/upkeepRule")
public class UpKeepRuleController {

    @Autowired
    private ITbUpkeepRuleService upkeepRuleService;

    /**
     * 分页列表查询
     *
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AddSysLog("保养规则-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(TbUpkeepRule tbUpkeepRule,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        Page<TbUpkeepRule> page = new Page<TbUpkeepRule>(pageNo, pageSize);
        LambdaQueryWrapper<TbUpkeepRule> lambdaQueryWrapper = QueryGenerator.initQueryWrapper(TbUpkeepRule.class, tbUpkeepRule);
        lambdaQueryWrapper.orderByDesc(TbUpkeepRule::getCreateTime);
        IPage<TbUpkeepRule> pageList = upkeepRuleService.page(page, lambdaQueryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     */
    @AddSysLog("保养规则-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody @Validated(SaveValidated.class) TbUpkeepRule tbUpkeepRule) {
        LambdaQueryWrapper<TbUpkeepRule> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TbUpkeepRule::getVehicleBrand,tbUpkeepRule.getVehicleBrand())
                .eq(TbUpkeepRule::getVehicleModel,tbUpkeepRule.getVehicleModel())
                .eq(TbUpkeepRule::getVehicleType,tbUpkeepRule.getVehicleType())
                .eq(TbUpkeepRule::getRuleType,tbUpkeepRule.getRuleType());
        int count = upkeepRuleService.count(lambdaQueryWrapper);
        if(count > 0){
            return Result.error(101,"存在相同的 车种、车型、品牌 规则,请修改！");
        }else{
            LambdaQueryWrapper<TbUpkeepRule> nameQuery = new LambdaQueryWrapper<>();
            nameQuery.eq(TbUpkeepRule::getName,tbUpkeepRule.getName());
            int nameCount = upkeepRuleService.count(nameQuery);
            if(nameCount > 0){
                return Result.error(101,"存在相同的规则名称,请修改！");
            }
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String username = "";
            if(Objects.nonNull(sysUser)){
                username = sysUser.getUsername();
                if(StrUtil.isBlank(tbUpkeepRule.getCreateBy())){
                    tbUpkeepRule.setCreateBy(username);
                }
            }

            upkeepRuleService.save(tbUpkeepRule);
            return Result.ok("添加成功！");
        }
    }

    /**
     * 编辑
     */
    @AddSysLog("保养规则-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody @Validated(UpdateValidated.class) TbUpkeepRule tbUpkeepRule) {
        LambdaQueryWrapper<TbUpkeepRule> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TbUpkeepRule::getVehicleBrand,tbUpkeepRule.getVehicleBrand())
                .eq(TbUpkeepRule::getVehicleModel,tbUpkeepRule.getVehicleModel())
                .eq(TbUpkeepRule::getVehicleType,tbUpkeepRule.getVehicleType())
                .eq(TbUpkeepRule::getRuleType,tbUpkeepRule.getRuleType())
                .ne(TbUpkeepRule::getId,tbUpkeepRule.getId());
        int count = upkeepRuleService.count(lambdaQueryWrapper);
        if(count > 0){
            return Result.error(101,"存在相同的 车种、车型、品牌 规则,请修改！");
        }else{
            LambdaQueryWrapper<TbUpkeepRule> nameQuery = new LambdaQueryWrapper<>();
            nameQuery.eq(TbUpkeepRule::getName,tbUpkeepRule.getName()).ne(TbUpkeepRule::getId,tbUpkeepRule.getId());
            int nameCount = upkeepRuleService.count(nameQuery);
            if(nameCount > 0){
                return Result.error(101,"存在相同的规则名称,请修改！");
            }
            upkeepRuleService.updateById(tbUpkeepRule);
            return Result.ok("编辑成功！");
        }
    }

    /**
     * 删除
     */
    @AddSysLog("保养规则-删除")
    @DeleteMapping(value = "/realDelete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        upkeepRuleService.removeById(id);
        return Result.ok("删除成功！");
    }

    /**
     * 禁用
     */
    @AddSysLog("保养规则-禁用")
    @DeleteMapping(value = "/cancel")
    public Result<?> cancel(@RequestParam(name = "id", required = true) String id) {
        upkeepRuleService.update(new LambdaUpdateWrapper<TbUpkeepRule>().eq(TbUpkeepRule::getId,id).set(TbUpkeepRule::getRuleStatus,2));
        return Result.ok("禁用成功！");
    }

    /**
     * 启用
     */
    @AddSysLog("保养规则-启用")
    @DeleteMapping(value = "/unCancel")
    public Result<?> unCancel(@RequestParam(name = "id", required = true) String id) {
        upkeepRuleService.update(new LambdaUpdateWrapper<TbUpkeepRule>().eq(TbUpkeepRule::getId,id).set(TbUpkeepRule::getRuleStatus,1));
        return Result.ok("启用成功！");
    }

    /**
     * 导出
     * @return
     */
    @AddSysLog("保养规则-导出")
    @GetMapping("/export")
    public Result<?> export(TbUpkeepRule tbUpkeepRule, HttpServletResponse response){
        try (OutputStream output = response.getOutputStream()){

            String fileName = "保养规则表.xlsx";
            try {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ";" + "filename*=utf-8''" + fileName);

            LambdaQueryWrapper<TbUpkeepRule> lambdaQueryWrapper = QueryGenerator.initQueryWrapper(TbUpkeepRule.class, tbUpkeepRule);
            List<TbUpkeepRule> list = upkeepRuleService.list(lambdaQueryWrapper);
            EasyExcel.write(output, TbUpkeepRule.class).sheet("保养规则").doWrite(list);

        } catch (IOException e) {
            return Result.error("导出错误！");
        }
        return Result.ok();
    }

}
