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

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.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.dto.FirefightersContractDto;
import com.yeejoin.amos.boot.module.common.api.entity.FirefightersContract;
import com.yeejoin.amos.boot.module.common.api.service.IFirefightersContractService;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FirefightersContractServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.SourceFileServiceImpl;

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


/**
* 消防员合同
*
* @author tb
* @date 2021-06-07
*/
@RestController
@Api(tags = "消防员合同Api")
@RequestMapping(value = "/firefighters-contract")
public class FirefightersContractController extends BaseController {

    @Autowired
    FirefightersContractServiceImpl iFirefightersContractService;
 
    @Autowired
    IFirefightersContractService firefightersContractService;
    
    @Autowired
  	SourceFileServiceImpl sourceFileService;
    @Autowired
    RedisUtils redisUtils;
    @Value("${redis.cache.failure.time:10800}")
    private long time;
    /**
    * 新增消防员合同
    * @return
    */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增消防员合同", notes = "新增消防员合同")
    public ResponseModel<FirefightersContractDto> saveFirefightersContract(HttpServletRequest request, @RequestBody FirefightersContractDto firefightersContract){
       	 return ResponseHelper.buildResponse(firefightersContractService.save(firefightersContract));
    }

    /**
    * 根据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) {
    	iFirefightersContractService.update(new UpdateWrapper<FirefightersContract>().eq("sequence_nbr", Long.valueOf(sequenceNbr)).set("is_delete", 1));
            //删除缓存
            redisUtils.del(RedisKey.CONTRACT_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<FirefightersContractDto> updateByIdFirefightersContract(HttpServletRequest request, @RequestBody FirefightersContractDto firefightersContract){
    	firefightersContractService.updateById(firefightersContract, getUserInfo());    
       //删除缓存
       redisUtils.del(RedisKey.CONTRACT_ID+firefightersContract.getSequenceNbr());
       return ResponseHelper.buildResponse(firefightersContract);  	          	      	
    }



    /**
    * 根据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.CONTRACT_ID+id)){
            Object obj= redisUtils.get(RedisKey.CONTRACT_ID+id);
            return ResponseHelper.buildResponse(obj);
        }else{
            FirefightersContract firefightersContract= iFirefightersContractService.getById(id);
            FirefightersContractDto dto = new  FirefightersContractDto();
            Bean.copyExistPropertis(firefightersContract, dto);
            dto.setAttachments(sourceFileService.getAttachments(id));
           redisUtils.set(RedisKey.CONTRACT_ID+id, JSON.toJSON(dto),time);
            return ResponseHelper.buildResponse(dto);
       }
    }



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

        Page<FirefightersContract> pageBean;
        QueryWrapper<FirefightersContract> firefightersContractQueryWrapper = new QueryWrapper<>();
        firefightersContractQueryWrapper.eq("is_delete", 0);
        Class<? extends FirefightersContract> aClass = firefightersContract.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            try {
                field.setAccessible(true);
                Object o = field.get(firefightersContract);
                if (o != null) {
                    Class<?> type = field.getType();
                    String name = NameUtils.camel2Underline(field.getName());
                    if (type.equals(Integer.class)) {
                        Integer fileValue = (Integer) field.get(firefightersContract);
                        firefightersContractQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(Long.class)) {
                        Long fileValue = (Long) field.get(firefightersContract);
                        firefightersContractQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(String.class)) {
                        String fileValue = (String) field.get(firefightersContract);
                        /* BUG 2193 合同名称模糊匹配 start*/
                        if ("NAME".equals(name)) {
                            firefightersContractQueryWrapper.like(name, fileValue);
                        } else {
                            firefightersContractQueryWrapper.eq(name, fileValue);
                        }
                        /* BUG 2193 合同名称模糊匹配 end*/
                    }else if (type.equals(Date.class)) {
                    	Date fileValue = (Date) field.get(firefightersContract);
                        firefightersContractQueryWrapper.eq(name, fileValue);
                    } else {
                    	if(!name.equals(NameUtils.camel2Underline("serialVersionUID"))) {
                        String fileValue = (String) field.get(firefightersContract);
                        firefightersContractQueryWrapper.eq(name, fileValue);
                    }
                    	}
                }
            } catch (Exception e) {
                throw  new RuntimeException("系统异常");
            }
        });
        IPage<FirefightersContract> page;
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<FirefightersContract>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<FirefightersContract>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        page = iFirefightersContractService.page(pageBean, firefightersContractQueryWrapper);
         page.getRecords().forEach(i->{
        	i.setAttachments(sourceFileService.getAttachments(i.getSequenceNbr()));
        });
        return ResponseHelper.buildResponse(page);  	 
        }
    }

