package com.yeejoin.amos.boot.module.common.biz.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.yeejoin.amos.boot.module.common.api.entity.SourceFile;
import com.yeejoin.amos.boot.module.common.biz.service.impl.SourceFileServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ReflectionUtils;
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.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.NameUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.entity.FirefightersThought;
import com.yeejoin.amos.boot.module.common.api.service.IFailureAuditService;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FirefightersThoughtServiceImpl;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;


/**
* 消防员思想谈话记录
*
* @author tb
* @date 2021-06-07
*/
@RestController
@Api(tags = "消防员思想谈话记录Api")
@RequestMapping(value = "/firefighters-thought")
public class FirefightersThoughtController extends BaseController {

    @Autowired
    FirefightersThoughtServiceImpl iFirefightersThoughtService;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    SourceFileServiceImpl sourceFileService;
    @Value("${redis.cache.failure.time}")
    private long time;
    /**
    * 新增消防员思想谈话记录
    * @return
    */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增消防员思想谈话记录", notes = "新增消防员思想谈话记录")
    public ResponseModel<FirefightersThought> saveFirefightersThought(HttpServletRequest request, @RequestBody FirefightersThought firefightersThought){
    	iFirefightersThoughtService.save(firefightersThought);
        /*bug 2883 消防人员，新增思想状态保存报错 2021-09-15 陈召 开始*/
        if (firefightersThought.getAttachments() != null && !firefightersThought.getAttachments().isEmpty()){
            /*bug 2883 消防人员，新增思想状态保存报错 2021-09-15 陈召 开始*/
            sourceFileService.saveAttachments(firefightersThought.getSequenceNbr(),firefightersThought.getAttachments());
        }
    	return ResponseHelper.buildResponse(firefightersThought);
    }


    /**
    * 根据id删除
    * @param id
    * @return
    */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public ResponseModel<Object> deleteById(HttpServletRequest request, @PathVariable String id){
    	String str[] = id.split(",");
   	    List<String> ids= Arrays.asList(str);
     	for (String sequenceNbr : ids) {
        iFirefightersThoughtService.update(new UpdateWrapper<FirefightersThought>().eq("sequence_nbr", Long.valueOf(sequenceNbr)).set("is_delete", 1));
            //删除缓存
            redisUtils.del(RedisKey.THOUGHT_ID+sequenceNbr);
     	}
    	return ResponseHelper.buildResponse(null);

    }




    /** 修改消防员思想谈话记录
    * @return
    */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/updateById", method = RequestMethod.PUT)
    @ApiOperation(httpMethod = "PUT", value = "修改消防员思想谈话记录", notes = "修改消防员思想谈话记录")
    public ResponseModel<FirefightersThought>  updateByIdFirefightersThought(HttpServletRequest request, @RequestBody FirefightersThought firefightersThought){

        if (firefightersThought.getAttachments() != null && !firefightersThought.getAttachments().isEmpty()){
            sourceFileService.saveAttachments(firefightersThought.getSequenceNbr(),firefightersThought.getAttachments());
        }
    	iFirefightersThoughtService.updateById(firefightersThought);

        //删除缓存
        redisUtils.del(RedisKey.THOUGHT_ID+firefightersThought.getSequenceNbr());
        return ResponseHelper.buildResponse(firefightersThought);

    }



    /**
    * 根据id查询
    * @param id
    * @return
    */
	@TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据消防员id查询", notes = "根据消防员id查询")
    public ResponseModel<Object> selectById(HttpServletRequest request, @PathVariable Long id){


        if(redisUtils.hasKey(RedisKey.THOUGHT_ID+id)){
            Object obj= redisUtils.get(RedisKey.THOUGHT_ID+id);
            ((Map<String,Object>) obj).put("attachments", sourceFileService.getAttachments(id));
            /*Map<String, Object> mainMap = Bean.BeantoMap(obj);
            mainMap.put("attachments", sourceFileService.getAttachments(id));
            return ResponseHelper.buildResponse(mainMap);*/
            return ResponseHelper.buildResponse((Map<String,Object>) obj );
        }else{ FirefightersThought firefightersThought= iFirefightersThoughtService.getById(id);
            redisUtils.set(RedisKey.THOUGHT_ID+id, JSON.toJSON(firefightersThought),time);
            Map<String, Object> mainMap = Bean.BeantoMap(firefightersThought);
            mainMap.put("attachments", sourceFileService.getAttachments(id));
            return ResponseHelper.buildResponse(mainMap);
        }



    }



    /**
    * 列表分页查询
    * @return
    */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public ResponseModel<IPage<FirefightersThought>> listPage(String pageNum,String pageSize, FirefightersThought firefightersThought){

        Page<FirefightersThought> pageBean;
        QueryWrapper<FirefightersThought> firefightersThoughtQueryWrapper = new QueryWrapper<>();
        firefightersThoughtQueryWrapper.eq("is_delete", 0);
        Class<? extends FirefightersThought> aClass = firefightersThought.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            try {
                ReflectionUtils.makeAccessible(field);
                Object o = field.get(firefightersThought);
                if (o != null) {
                    Class<?> type = field.getType();
                    String name = NameUtils.camel2Underline(field.getName());
                    if (type.equals(Integer.class)) {
                        Integer fileValue = (Integer) field.get(firefightersThought);
                        firefightersThoughtQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(Long.class)) {
                        Long fileValue = (Long) field.get(firefightersThought);
                        firefightersThoughtQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(String.class)) {
                        String fileValue = (String) field.get(firefightersThought);
                        if("SPEAKER".equals(name)) {
                        	 firefightersThoughtQueryWrapper.like(name,fileValue);
                        }else {
                        	firefightersThoughtQueryWrapper.eq(name, fileValue);
                        }
                    }else if (type.equals(Date.class)) {
                    	Date fileValue = (Date) field.get(firefightersThought);
                    	firefightersThoughtQueryWrapper.likeRight(name,DateUtils.dateFormat(fileValue,null));
                    } else {
                    	if(!name.equals(NameUtils.camel2Underline("serialVersionUID"))) {
                        String fileValue = (String) field.get(firefightersThought);
                        firefightersThoughtQueryWrapper.eq(name, fileValue);
                    }}
                }
            } catch (Exception e) {
                throw  new RuntimeException("系统异常");
            }
        });
        IPage<FirefightersThought> page;
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        page = iFirefightersThoughtService.page(pageBean, firefightersThoughtQueryWrapper);

        return ResponseHelper.buildResponse(page); }
    }

