package com.hchyun.web.controller.system;

import java.io.Serializable;
import java.util.List;
import java.util.regex.Pattern;

import com.hchyun.common.constant.ReturnConstants;
import com.hchyun.common.utils.ServerResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hchyun.common.annotation.Log;
import com.hchyun.common.core.controller.HcyBaseController;
import com.hchyun.common.core.entity.AjaxResult;
import com.hchyun.common.enums.BusinessType;
import com.hchyun.system.entity.Regular;
import com.hchyun.system.service.RegularService;
import com.hchyun.common.utils.poi.ExcelUtil;

/**
 * 校验规则Controller
 *
 * @author hchyun
 * @date 2021-01-18
 */
@RestController
@RequestMapping("/system/regular")
public class RegularController extends HcyBaseController {
    protected final Logger logger = LoggerFactory.getLogger(RegularController.class);

    @Autowired
    private RegularService regularService;

    /**
     * 查询校验规则列表
     *
     * @param regular
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:regular:list')")
    @GetMapping("/list")
    public Serializable list(Regular regular) {
        try {
            startPage();
            ServerResult<List<Regular>> serverResult = regularService.selectRegularList(regular);
            if (serverResult.isStart()) {
                return getDataTable(serverResult.getData());
            } else {
                return AjaxResult.info(serverResult.getMsg());
            }
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }

    /**
     * 导出校验规则列表
     *
     * @param regular
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:regular:export')")
    @Log(title = "校验规则", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Regular regular) {
        try {
            ServerResult<List<Regular>> serverResult = regularService.selectRegularList(regular);
            ExcelUtil<Regular> util = new ExcelUtil<Regular>(Regular.class);
            if (serverResult.isStart()) {
                return util.exportExcel(serverResult.getData(), "regular");
            } else {
                return AjaxResult.error(serverResult.getMsg());
            }
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }

    /**
     * 获取校验规则详细信息
     *
     * @param id
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:regular:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        try {
            ServerResult<Regular> serverResult = regularService.selectRegularById(id);
            if (serverResult.isStart()) {
                return AjaxResult.success(serverResult.getData());
            } else {
                return AjaxResult.info(serverResult.getMsg());
            }
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }

    /**
     * 新增校验规则
     *
     * @param regular
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:regular:add')")
    @Log(title = "校验规则", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Regular regular) {
        try {
            if (regular.getName() == null || regular.getName().equals("")) {
                return AjaxResult.error("正则名称不能为空!");
            }
            if (regular.getRegular() == null || regular.getRegular().equals("")) {
                return AjaxResult.error("正则内容不能为空!");
            }
            if (regular.getEnable() == null || regular.getEnable() < 0) {
                return AjaxResult.error("是否启用不能为空!");
            }
            if (!verifyRegular(regular)){
                return AjaxResult.error("正则表达式校验不通过!");
            }
            ServerResult<Integer> serverResult = regularService.insertRegular(regular);
            if (serverResult.isStart()) {
                return toAjax(serverResult.getData());
            } else {
                return AjaxResult.error(serverResult.getMsg());
            }
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }

    /**
     * 修改校验规则
     *
     * @param regular
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:regular:edit')")
    @Log(title = "校验规则", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Regular regular) {
        try {
            if (regular.getName() == null || regular.getName().equals("")) {
                return AjaxResult.error("正则名称不能为空!");
            }
            if (regular.getRegular() == null || regular.getRegular().equals("")) {
                return AjaxResult.error("正则内容不能为空!");
            }
            if (regular.getEnable() == null || regular.getEnable() < 0) {
                return AjaxResult.error("是否启用不能为空!");
            }
            if (!verifyRegular(regular)){
                return AjaxResult.error("正则表达式校验不通过!");
            }
            ServerResult<Integer> serverResult = regularService.updateRegular(regular);
            if (serverResult.isStart()) {
                return toAjax(serverResult.getData());
            } else {
                return AjaxResult.error(serverResult.getMsg());
            }
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }

    /**
     * 删除校验规则
     *
     * @param ids
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:regular:remove')")
    @Log(title = "校验规则", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        try {
            if (ids.length == 0) {
                return AjaxResult.error("需要删除id数不能为空!");
            }
            ServerResult<Integer> serverResult = regularService.deleteRegularByIds(ids);
            if (serverResult.isStart()) {
                return toAjax(serverResult.getData());
            } else {
                return AjaxResult.error(serverResult.getMsg());
            }
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }

    public boolean verifyRegular(Regular regular){
        return Pattern.matches(regular.getRegular(),regular.getValidation());
    }
}
