package com.xxfc.platform.vehicle.biz;

import com.ace.cache.annotation.Cache;
import com.ace.cache.annotation.CacheClear;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxiaoqi.security.admin.feign.dto.UserDTO;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.google.common.collect.Lists;
import com.xxfc.platform.vehicle.common.RestResponse;
import com.xxfc.platform.vehicle.constant.RedisKey;
import com.xxfc.platform.vehicle.entity.Campsite;
import com.xxfc.platform.vehicle.mapper.CampsiteMapper;
import com.xxfc.platform.vehicle.mapper.ConstantMapper;
import com.xxfc.platform.vehicle.mapper.SysRegionMapper;
import com.xxfc.platform.vehicle.util.excel.ExcelImport;
import com.xxfc.platform.vehicle.pojo.CampsiteVo;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.github.wxiaoqi.security.auth.common.constatns.CommonConstants.DATA_ALL_FALSE;
import static com.xxfc.platform.vehicle.constant.DbColumnConstant.COMPANY_ZONE_ID;
import static com.xxfc.platform.vehicle.constant.DbColumnConstant.ID;
import static com.xxfc.platform.vehicle.constant.RedisKey.CAMPSITE_CACHE_DATAZONE;

@Service
@Slf4j
public class CampsiteBiz extends BaseBiz<CampsiteMapper, Campsite> {

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

    @Autowired
    private RedisTemplate customRedisTemplate;

    @Value("${campsitePic.baseUploadPath}")
    private String baseUploadPath ;

    @Autowired
    private SysRegionMapper sysRegionMapper;

    @Autowired
    private ConstantMapper constantMapper;

    /**
     * 按主键获取公司
     * @param id
     * @return
     */
    public Campsite getById(Integer id){
        return mapper.selectByPrimaryKey(id);
    }

    public Boolean exits(Integer id){
        Campsite param = new Campsite();
        param.setId(id);
        return mapper.selectCount(param)>0;
    }

    /**
     * 转换为vo类
     * @param campsites
     * @returns
     */
    private List<CampsiteVo> branchCompany2VO(List<Campsite> campsites){
        List<CampsiteVo> campsiteVoList = Lists.newArrayList();
        if(CollectionUtils.isNotEmpty(campsites)){
            for(Campsite campsite:campsites){
                CampsiteVo campsiteVo = new CampsiteVo();
                BeanUtils.copyProperties(campsite,campsiteVo);
                campsiteVoList.add(campsiteVo);
            }
        }
        return  campsiteVoList;
    }

    public PageDataVO<Campsite> getAll(Integer page, Integer limit, Integer addrProvince, Integer addrCity,
                                       Integer addrTown, UserDTO userDTO){
        Example example = new Example(Campsite.class);
        Example.Criteria criteria = example.createCriteria();
        if(addrProvince!=null) {
            criteria.andCondition(" addr_province = '" + addrProvince + "'");
        }
        if(addrCity!=null) {
            criteria.andCondition(" addr_city = '" + addrCity + "'");
        }
        if(addrTown!=null) {
            criteria.andCondition(" addr_town = '" + addrTown + "'");
        }
        if(userDTO != null && DATA_ALL_FALSE.equals(userDTO.getDataAll())) {
            if(StringUtils.isNotBlank(userDTO.getDataZone())) {
                criteria.andIn(COMPANY_ZONE_ID, userDTO.dataZone2List());
            }
            if(StringUtils.isNotBlank(userDTO.getDataCompany())) {
                criteria.andIn(ID, userDTO.dataCompany2List());
            }
        }
        example.setOrderByClause("`id` asc");
        PageHelper.startPage(page,limit);
        PageInfo<Campsite> campsitePageInfo = new PageInfo<>(mapper.selectByExample(example));
        return PageDataVO.pageInfo(campsitePageInfo);
    }

    @Cache(key= RedisKey.CAMPSITE_CACHE_ALL)
    public List<Campsite> getAll(){
        return mapper.selectAll();
    }

    /**
     * 增加公司，返回id
     * @param campsiteVo
     * @return
     */
    @CacheClear(key= RedisKey.CAMPSITE_CACHE)
    public Integer add(CampsiteVo campsiteVo){
        Campsite campsite = new Campsite();
        BeanUtils.copyProperties(campsiteVo,campsite);
        mapper.insertSelective(campsite);
        return campsite.getId();
    }

    @CacheClear(key= RedisKey.CAMPSITE_CACHE)
    public void del(Integer id){
        mapper.deleteByPrimaryKey(id);
    }

    /**
     * 更新公司信息
     * @param campsite
     * @return
     */
    @CacheClear(key= RedisKey.CAMPSITE_CACHE)
    public Integer update(Campsite campsite){
        return mapper.updateByPrimaryKeySelective(campsite);
    }

    /**
     * 写入上传文件，返回相对路径
     * @param file
     * @return
     */
    public RestResponse<String> uploadCompanyPic(MultipartFile file) throws Exception{
        //创建本日存放目录
        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 = customRedisTemplate.opsForValue().increment(redisNoKey);
        if(no.equals(1l)){
            customRedisTemplate.expire(redisNoKey,1, TimeUnit.DAYS);
        }
        String fileName = file.getOriginalFilename();
        String realFileRelPath = dirPathToday + File.separator + no + fileName.substring(fileName.lastIndexOf("."));
        //文件存放路径
        String filePath = baseUploadPath + realFileRelPath;
        //将文件写入指定位置
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(filePath));
        return RestResponse.suc(realFileRelPath);
    }

    @Cache(key=CAMPSITE_CACHE_DATAZONE)
    public List<Campsite> dataCompany(String dataZone) {
        if(StringUtils.isBlank(dataZone)) {
            return new ArrayList<Campsite>();
        }
        List<Integer> zoneIds = Arrays.asList(dataZone.split(",")).parallelStream().map(s -> Integer.valueOf(s)).collect(Collectors.toList());
        Example example = new Example(Campsite.class);
        example.createCriteria().andIn("zoneId", zoneIds);
        List<Campsite> zoneCompanys = selectByExample(example);
        return zoneCompanys;
    }

    public RestResponse<String> importExcel(MultipartFile multipartfile, HttpServletRequest request){
        try {
            List<String[]> readExcel = ExcelImport.getExcelData(multipartfile);
            if(readExcel.size()<1){
                return RestResponse.codeAndMessage(1001,"导入不能没数据！！！");
            }
           Date date=new Date();
            List<Campsite> list=new ArrayList<>();
            for (int i = 1; i < readExcel.size(); i++) {
                String[] str = readExcel.get(i);
                Campsite campsite=new Campsite();
                String name=str[0];
                String status=str[1];
                String zone=str[2];
                String province = str[3];
                String city = str[4];
                String town = str[5];
                String addr_detail=str[6];
                BigDecimal latitude=new BigDecimal(str[7]);
                BigDecimal longitude=new BigDecimal(str[8]);
                if(str.length>9){
                    String leader=str[9];
                    campsite.setLeader(leader);
                }
                if(str.length>10){
                    String leader_contact_info=str[10];
                    campsite.setLeaderContactInfo(leader_contact_info);
                }

                Integer branch_type=1;
                Integer zone_id=constantMapper.getTypebyname(zone,4);
                if(zone_id==null){
                    zone_id=1;
                }
                Integer addr_province=sysRegionMapper.getNumberV2(province,1);
                Integer addr_city=sysRegionMapper.getNumberV2(city,2);
                Integer addr_town=sysRegionMapper.getNumberV2(town,3);
                campsite.setAddrProvince(addr_province);
                campsite.setAddrCity(addr_city);
                campsite.setAddrTown(addr_town);
                campsite.setAddrDetail(addr_detail);
                campsite.setStatus(4);
                campsite.setName(name);
                campsite.setLatitude(latitude);
                campsite.setLongitude(longitude);
                campsite.setCreateTime(date);
                campsite.setUpdateTime(date);
                campsite.setZoneId(zone_id);
                campsite.setBranchType(branch_type);
                //list.add(campsite);
                mapper.insertSelective(campsite);
                }
           /* if(list.size()>0){

            }*/

        }catch (Exception e){
            log.error(e.getMessage(), e);
            return RestResponse.codeAndMessage(10001,"网络异常！");
        }
        return RestResponse.suc();
    }

}
