package cn.com.ty.lift.ud.sensitivewords.controller;

import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.IService;

// gitlab.udreamtech.com/xuesong.chen/lift-server.git
import cn.com.ty.lift.ud.common.BaseController;
import cn.com.ty.lift.ud.common.DelReq;
import cn.com.ty.lift.ud.utils.ExcelUtil;
import cn.com.ty.lift.ud.sensitivewords.controller.query.SensitiveWordsQuery;
import cn.com.ty.lift.ud.sensitivewords.mapper.entity.SensitiveWords;
import cn.com.ty.lift.ud.sensitivewords.service.ISensitiveWordsService;
import cn.com.ty.lift.ud.userInfo.mapper.entity.UserInfoEntity;
import cn.com.ty.lift.ud.userInfo.service.IUserInfoService;
import cn.com.ty.lift.ud.utils.CurrentUserInfo;
import cn.com.xwy.boot.web.dto.RestResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 敏感词汇 API
 * 
 * @author Xson
 * @date 2020-04-24
 */
@Api(tags = "敏感词汇 API- 魏瑞锋")
@RestController
@RequestMapping("/api/sensitiveWordss")
public class SensitiveWordsController extends BaseController<SensitiveWords, SensitiveWordsQuery> {

    private final Logger log = LoggerFactory.getLogger(SensitiveWordsController.class);

    private @Autowired ISensitiveWordsService sensitiveWordsService;

    private @Autowired IUserInfoService iUserInfoService;

    @Override
    protected IService<SensitiveWords> getService() {
        return sensitiveWordsService;
    }

    @ApiOperation(value = "批量启用")
    @PostMapping("useBath")
    public RestResponse useBath(@RequestBody DelReq ids) {
        sensitiveWordsService.updateStatuzByIds(ids.getIds(), 1);
        return RestResponse.success("启用成功");
    }

    @ApiOperation(value = "批量关闭")
    @PostMapping("nouseBath")
    public RestResponse nouseBath(@RequestBody DelReq ids) {
        sensitiveWordsService.updateStatuzByIds(ids.getIds(), 0);
        return RestResponse.success("关闭成功");
    }

  //修改
    @PutMapping("/update")
    @ApiOperation(value = "修改")
    public RestResponse update(@RequestBody SensitiveWords request) {
        List<SensitiveWords> byKeyword = sensitiveWordsService.getByKeyword(request.getKeyword());
        if(!byKeyword.isEmpty()) {
            return RestResponse.fail("敏感词汇重复："+request.getKeyword());
        }
        boolean updateFlag = getService().updateById(request);

        if (updateFlag)
            return RestResponse.success(null, "Updated successfully");
        else
            return RestResponse.fail("Updated unsuccessfully");
    }
    
    /**
     * 判断是否有敏感词汇
     * 
     * @param text
     *            文字
     * @return 敏感词汇
     */
    @ApiOperation(value = "判断是否有敏感词汇")
    @GetMapping("/changText")
    public Set<String> changText(String text) {
        Set<String> changText = sensitiveWordsService.changText(text);
        // SensitivewordFilter filter = new SensitivewordFilter();// 加载敏感词库
        // Set<String> changText = filter.getSensitiveWord(text, 2);// 比对敏感词
        return changText;

    }

    // 新建
    @PostMapping("/insert")
    @ApiOperation(value = "文本域批量新增")
    public RestResponse<SensitiveWords> create(@RequestBody SensitiveWords entity) {
        if (StringUtils.isNotBlank(entity.getKeyword())) {
            String userMobile = CurrentUserInfo.userMobile();
            UserInfoEntity userByMobile = iUserInfoService.getUserByMobile(userMobile);
            if(userByMobile == null) {
                return RestResponse.fail("您的登录信息已失效，请重新登录后进行添加");
            }
            String[] splitWord = entity.getKeyword().split(",");
            for (int i = 0; i < splitWord.length; i++) {
                String keyw = splitWord[i];
                List<SensitiveWords> byKeyword = sensitiveWordsService.getByKeyword(keyw);
                if(!byKeyword.isEmpty()) {
                    return RestResponse.fail("敏感词汇重复："+keyw);
                }
                SensitiveWords sensitiveWords = new SensitiveWords();
                if (userByMobile != null) {
                    sensitiveWords.setCreateBy(userByMobile.getName());
                }
                sensitiveWords.setKeyword(keyw);
                if (entity.getStatus() == null) {
                    sensitiveWords.setStatus(1);
                } else {
                    sensitiveWords.setStatus(entity.getStatus());
                }
                getService().save(sensitiveWords);
            }
            return RestResponse.success(null, "Created successfully");
        } else {
            return RestResponse.fail("敏感词汇不能为空");
        }

    }

    /**
     * excel导入
     * 
     * @param file
     * @param request
     * @return
     */
    @ApiOperation(value = "excel导入")
    @RequestMapping("/inputExcel")
    public RestResponse InputExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String userMobile = CurrentUserInfo.userMobile();
        UserInfoEntity userByMobile = iUserInfoService.getUserByMobile(userMobile);
        if(userByMobile == null) {
            return RestResponse.fail("您的登录信息已失效，请重新登录后进行添加");
        }
        try {
            ExcelUtil excelReader = new ExcelUtil();

            // 对读取Excel表格内容测试
            Map<String, String> map = new HashMap<String, String>();
            map.put("敏感词汇", "keyword");

            List<Map<String, Object>> data =
                excelReader.readExcelContent(file.getInputStream(), file.getOriginalFilename(), map);
            List<SensitiveWords> partsList = JSONObject.parseArray(JSON.toJSONString(data), SensitiveWords.class);
            for(SensitiveWords sensitiveWords : partsList) {
                if(sensitiveWords.getKeyword() == null || sensitiveWords.getKeyword().equals("")) {
                    return RestResponse.fail("导入模板格式不正确");
                }
                List<SensitiveWords> byKeyword = sensitiveWordsService.getByKeyword(sensitiveWords.getKeyword());
                if(!byKeyword.isEmpty()) {
                    return RestResponse.fail("敏感词汇重复："+sensitiveWords.getKeyword());
                }
                if (userByMobile != null) {
                    sensitiveWords.setCreateBy(userByMobile.getName());
                }
            }
            sensitiveWordsService.saveBatch(partsList);
            return RestResponse.success("上传成功");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return RestResponse.fail("未找到指定路径的文件!");
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail("上传异常!");
        }
    }
}