package com.fdage.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.fdage.constant.ConfigConstant;
import com.fdage.dao.base.TbCollectionMapper;
import com.fdage.dao.base.TbCollectionTimeMapper;
import com.fdage.dao.base.TbCollectionTypeMapper;
import com.fdage.dao.cust.TbCollectionMapperCust;
import com.fdage.dao.cust.TbCollectionTimeMapperCust;
import com.fdage.dao.cust.TbCollectionTypeMapperCust;
import com.fdage.dao.cust.TbExhibitionCollectionMapperCust;
import com.fdage.pojo.TbCollection;
import com.fdage.pojo.TbCollectionTime;
import com.fdage.pojo.TbCollectionType;
import com.fdage.request.RequestCollection;
import com.fdage.respon.ResponCollection;
import com.fdage.respon.ResponStatistics;
import com.fdage.service.ICollectionService;
import com.fdage.util.AjaxJson;
import com.fdage.util.DateUtil;
import com.fdage.util.ImportExeclUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created by Hb_zzZ on 2019/9/11.
 */
@Slf4j
@Service
public class CollectionServiceImpl implements ICollectionService {

    @Autowired
    private TbCollectionMapper mapper;

    @Autowired
    private TbCollectionMapperCust mapperCust;

    @Autowired
    private TbCollectionTypeMapper typeMapper;

    @Autowired
    private TbCollectionTypeMapperCust typeMapperCust;

    @Autowired
    private TbCollectionTimeMapper timeMapper;

    @Autowired
    private TbCollectionTimeMapperCust timeMapperCust;

    @Autowired
    private TbExhibitionCollectionMapperCust exhibitionCollectionMapperCust;

    @Autowired
    ConfigConstant configConstant;

    @Override
    public List<TbCollectionType> typeList(RequestCollection bo) {
        return mapperCust.typeList(bo);
    }

    @Override
    public List<TbCollectionTime> timeList() {
        return mapperCust.timeList();
    }

    @Override
    public int insert(TbCollection bo) {
        return mapper.insertSelective(bo);
    }

    @Override
    public int update(TbCollection bo) {
        return mapper.updateByPrimaryKeySelective(bo);
    }

    @Override
    public ResponCollection findById(Long id) {
        TbCollection collection = mapper.selectByPrimaryKey(id);
        if(collection == null){
            return null;
        }
        ResponCollection result = new ResponCollection();
        BeanUtils.copyProperties(collection, result);
//        String typeImages = collection.getTypeImages();
//        if (StringUtils.isNotBlank(typeImages)){
//            List<String> images = Arrays.asList(StrUtil.split(typeImages, ","));
//            result.setTypeImages(images);
//        }
        TbCollectionType type = typeMapper.selectByPrimaryKey(collection.getTypeId());
        if(type != null){
            result.setTypeName(type.getName());
        }

        TbCollectionTime time = timeMapper.selectByPrimaryKey(collection.getTimeId());
        if(time != null){
            result.setTimeName(time.getName());
        }

        if(collection.getDiscoveryTime() != null){
            result.setDiscoveryTime(String.valueOf(collection.getDiscoveryTime().getTime()));
        }
        if(collection.getRepairTime() != null){
            result.setRepairTime(String.valueOf(collection.getRepairTime().getTime()));
        }

        mapperCust.addOpenNumById(id);

        return result;
    }



    @Override
    public List<ResponCollection> findList(RequestCollection bo) {
        if(bo == null){
            bo = new RequestCollection();
            bo.setState(0);
            return mapperCust.findList(bo);
        }
        int pageNum = bo.getPageNum() == 0? 1: bo.getPageNum();
        int pageSize = bo.getPageSize() == 0? 10: bo.getPageSize();
        PageHelper.startPage(pageNum, pageSize);

        return mapperCust.findList(bo);
    }

    @Override
    public int addLikeNumById(Long id) {
        return mapperCust.addLikeNumById(id);
    }

    @Override
    public AjaxJson importCollection(String fileUrl) {
        TbCollection collection = null;
        TbCollectionType collectionType = null;
        TbCollectionTime collectionTime = null;
        StringBuilder error = new StringBuilder();
        StringBuilder errorNum = new StringBuilder("");

        ImportExeclUtil poi = new ImportExeclUtil();
        List<List<String>> list = poi.read(fileUrl);
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                List<String> cellList = list.get(i);
                if(i == 0){
                    continue;
                }
//                if(cellList.size() < 7){
                if(cellList.size() < 6){
                    return AjaxJson.failure("导入数据根式不正常");
                }
                if(StringUtil.isEmpty(cellList.get(0).toString().trim()) ||
                        StringUtil.isEmpty(cellList.get(1).toString().trim()) ||
                        StringUtil.isEmpty(cellList.get(2).toString().trim()) ||
                        StringUtil.isEmpty(cellList.get(3).toString().trim()) ||
                        StringUtil.isEmpty(cellList.get(4).toString().trim())){
                    errorNum.append(cellList.get(0).toString().trim()).append(";");
                    continue;
                }

                collection = mapperCust.findByName(cellList.get(1).toString().trim());
                collectionType = typeMapperCust.findByName(cellList.get(2).toString().trim());
                collectionTime = timeMapperCust.findByName(cellList.get(3).toString().trim());
                if(collectionType == null || collectionTime == null){
                    errorNum.append(cellList.get(0).toString().trim()).append(";");
                    continue;
                }
                if(collection == null){
                    collection = new TbCollection();
                    collection.setName(cellList.get(1).toString().trim());
                    collection.setTypeId(collectionType.getId());
                    collection.setTimeId(collectionTime.getId());
                    collection.setNum(cellList.get(4).toString().trim());
                    collection.setDescription(cellList.get(5).toString().trim());
                    collection.setCreateTime(new Date());
                    mapper.insertSelective(collection);
                    continue;
                }
                collection.setName(cellList.get(1).toString().trim());
                collection.setTypeId(collectionType.getId());
                collection.setTimeId(collectionTime.getId());
                collection.setNum(cellList.get(4).toString().trim());
                collection.setDescription(cellList.get(5).toString().trim());
                mapper.updateByPrimaryKeySelective(collection);
            }

        }
        if(StringUtil.isNotEmpty(errorNum.toString())){
            error.append("序号").append(errorNum.toString()).append("内容导入失败");
            return AjaxJson.failure(error.toString());
        }
        return AjaxJson.success();
    }

    @Override
    public List<ResponCollection> searchCollection(RequestCollection bo) {
        return mapperCust.searchListByName(bo);
    }

    @Override
    public int addSearchNum(Long id) {
        return mapperCust.addSearchNumById(id);
    }

    @Override
    public int addDownloadNum(Long id) {
        return mapperCust.addDownloadNumById(id);
    }

    @Override
    public ResponStatistics collectionTotal() {
        return mapperCust.collectionTotal();
    }

    @Override
    public List<ResponCollection> findListOrderBy(Map<String, String> map) {
        return mapperCust.findListOrderBy(map);
    }

    @Override
    public List<Map<String, Object>> typeTotal() {
        return mapperCust.typeTotal();
    }

    @Override
    public int deleteById(Long id) {
        exhibitionCollectionMapperCust.deleteByCollectionId(id);
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    public AjaxJson uploadCode(MultipartFile file, String code) {

        if(file == null){
            return AjaxJson.failure("参数不能为空");
        }

        // 拦截非法文件
        List<String> legalSuffix = Arrays.asList("obj","png","ab");
        String originalFilename = file.getOriginalFilename();
        String suffix = StringUtils.substringAfterLast(originalFilename, ".");
        suffix = StringUtils.lowerCase(suffix);

        if (!legalSuffix.contains(suffix)){
            return AjaxJson.failure(3001, "非法文件");
        }

        String filePath = "/collection/unity/" + code +"/" +  originalFilename;
        String savePath = configConstant.serverBasePath + filePath;
        try {
            FileUtil.writeFromStream(file.getInputStream(), savePath);
            log.info("图片地址：" + savePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxJson.success((Object)filePath);
    }

    @Override
    public AjaxJson addVisit(Long id) {
        mapper.addVisit(id);
        return AjaxJson.success();
    }

    @Override
    public Long countVisit() {
        return mapper.countVisit();
    }

    public static void main(String[] args) {
        CollectionServiceImpl service = new CollectionServiceImpl();

        service.importCollection("F:\\文档\\下载\\高淳文物导入模板.xlsx");
    }
}
