package com.xxfc.platform.app.biz;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.constant.RestCode;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.app.vo.appVersionQuery;
import com.xxfc.platform.vehicle.common.RestResponse;
import com.xxfc.platform.vehicle.constant.RedisKey;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.xxfc.platform.app.entity.AppVersion;
import com.xxfc.platform.app.mapper.AppVersionMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.weekend.WeekendSqls;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 
 *
 * @author libin
 * @email 18178966185@163.com
 * @date 2019-06-24 10:34:00
 */
@Service
public class AppVersionBiz extends BaseBiz<AppVersionMapper,AppVersion> {

     @Value("${app.uploadPath}")
    private  String uploadPath;
     @Autowired
     private RedisTemplate redisTemplate;

    public static final DateTimeFormatter DEFAULT_DATE_TIME_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd");


    public ObjectRestResponse getVersion(String version,Integer type){
        if (StringUtils.isBlank(version)||type==null){
            return  ObjectRestResponse.createFailedResult(ResultCode.NULL_CODE,"参数不能为空");
        }
        version=version.trim();
        Example example =new Example(AppVersion.class);
        example.createCriteria().andEqualTo("isDel",0).andEqualTo("downloadSwitch",0).andEqualTo("sysType",type);
        example.setOrderByClause("version DESC");
        List<AppVersion> list=selectByExample(example);
        example.clear();
        example.createCriteria().andEqualTo("version",version).andEqualTo("sysType",type);
        List<AppVersion> list1=selectByExample(example);
        Integer weigh1=0;
        if(list1.size()>0){
            weigh1=list1.get(0).getWeigh();
        }
        if (list.size()>0){
            AppVersion appVersion=list.get(0);
            String lats_version=appVersion.getVersion();
            Integer weigh=appVersion.getWeigh();
            if(!version.equals(lats_version)&&weigh>weigh1){
                return new ObjectRestResponse().status(RestCode.SUCCESS.getStatus()).msg(RestCode.SUCCESS.getMsg()).data(appVersion).rel(false);
            }
        }
           return  ObjectRestResponse.succ();
    }

    public ObjectRestResponse getVersionH5(Integer type){
        Example example =new Example(AppVersion.class);
        example.createCriteria().andEqualTo("isDel",0).andEqualTo("downloadSwitch",0).andEqualTo("sysType",type);
        example.setOrderByClause("version DESC");
        List<AppVersion> list=selectByExample(example);
        if (list.size()>0){
            AppVersion appVersion=list.get(0);
            return new ObjectRestResponse().status(RestCode.SUCCESS.getStatus()).msg(RestCode.SUCCESS.getMsg()).data(appVersion).rel(false);
        }
        return  ObjectRestResponse.succ();
    }

    public RestResponse uploadDrivingLicense(MultipartFile file) throws IOException {
        DateTime now = DateTime.now();
        String dirPathToday =  File.separator + now.toString(DEFAULT_DATE_TIME_FORMATTER);
        String redisNoKey = RedisKey.UPLOAD_FILE_NO_PREFIX + now.toString(DEFAULT_DATE_TIME_FORMATTER);
//        Long no = redisTemplate.opsForValue().increment(redisNoKey);
//        if(no.equals(1L)){
//            redisTemplate.expire(redisNoKey,1, TimeUnit.DAYS);
//        }
        String fileName = file.getOriginalFilename();
        String realFileRelPath = dirPathToday + File.separator+fileName.substring(fileName.lastIndexOf("/"));

        String filePath = uploadPath + realFileRelPath;

        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(filePath));
        return RestResponse.suc(filePath);
    }


    /**
     * 下载行驶证图片
     * @param realFileRelPath
     * @return
     * @throws Exception
     */
    public ResponseEntity<byte[]> downloadInstallationPackage(String realFileRelPath) throws Exception{
        String filePath = uploadPath + realFileRelPath;
        File file = new File(filePath);//新建一个文件
        HttpHeaders headers = new HttpHeaders();//http头信息
        String downloadFileName = new String(file.getName());//设置编码
        headers.setContentDispositionFormData("attachment", downloadFileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
    }

    /**
     * 添加版本信息
     * @param appVersion
     */
    @Transactional
    public void insertAppVersion(AppVersion appVersion) {
        appVersion.setDownloadSwitch(0);
        insertSelective(appVersion);
    }
    public AppVersion get(Integer id) {
        if (id==null) {
            throw new IllegalArgumentException("Parameter is null");
        }
        return selectById(id);
    }

    /**
     * 修改一条信息
     * @param appVersion
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateAppVersionById(AppVersion appVersion) {
        updateSelectiveById(appVersion);
    }

    /**
     * 删除
     * @param id
     */
    public void remove(Integer id) {
        AppVersion appVersion = new AppVersion();
        appVersion.setIsDel(1);
        Example example = Example.builder(AppVersion.class)
                .where(WeekendSqls.<AppVersion>custom().andEqualTo(AppVersion::getId,id))
                .build();
        mapper.updateByExampleSelective(appVersion,example);
    }

    public PageInfo<AppVersion> getAll(appVersionQuery query) {
        PageHelper.startPage(query.getPage(),query.getLimit());
        List<AppVersion> appVersionList = mapper.getAllByquery(query);
       return  PageInfo.of(appVersionList);

    }
}