package com.artfess.yhxt.check.regular.manager.impl;


import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.query.Direction;
import com.artfess.base.query.FieldSort;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.yhxt.basedata.manager.AccessoryManager;
import com.artfess.yhxt.basedata.manager.BizCulvertInformationManager;
import com.artfess.yhxt.basedata.model.Accessory;
import com.artfess.yhxt.basedata.model.BizCulvertInformation;
import com.artfess.yhxt.basedata.model.TunnelInformation;
import com.artfess.yhxt.check.detail.dao.CulvertOftenCheckDetailDao;
import com.artfess.yhxt.check.detail.manager.CulvertOftenCheckDetailManager;
import com.artfess.yhxt.check.detail.model.CulvertOftenCheckDetail;
import com.artfess.yhxt.check.regular.dao.CulvertOftenCheckDao;
import com.artfess.yhxt.check.regular.manager.CulvertOftenCheckManager;
import com.artfess.yhxt.check.regular.model.CulvertOftenCheck;
import com.artfess.yhxt.check.regular.model.SideSlopeOftenCheck;
import com.artfess.yhxt.check.regular.model.TunnelOftenCheck;
import com.artfess.yhxt.check.regular.vo.CulvertOftenCheckVo;
import com.artfess.yhxt.check.regular.vo.SideSlopeOftenCheckVo;
import com.artfess.yhxt.statistics.dao.SiteStatisticDao;
import com.artfess.yhxt.statistics.model.SiteStatistic;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 涵洞经常检查表 服务实现类
 *
 * @company 阿特菲斯信息技术有限公司
 * @author xzh
 * @since 2021-08-05
 */
@Service
public class CulvertOftenCheckManagerImpl extends BaseManagerImpl<CulvertOftenCheckDao, CulvertOftenCheck> implements CulvertOftenCheckManager {

    @Resource
    private CulvertOftenCheckDetailManager culvertOftenCheckDetailManager;

    @Resource
    private CulvertOftenCheckDetailDao culvertOftenCheckDetailDao;
    @Resource
    private BizCulvertInformationManager culvertInformationManager;
    @Resource
    private SiteStatisticDao siteStatisticDao;
    @Resource
    private AccessoryManager accessoryManager;

    @Override
    public PageList<CulvertOftenCheck> queryCulvertOftenCheck(QueryFilter<CulvertOftenCheck> queryFilter) {
        HashMap<String, Object> map = new HashMap<>();
        Map<String, Object> params = queryFilter.getParams();
        if (params != null) {
            map.putAll(params);
        }

        List<FieldSort> sorter = queryFilter.getSorter();
        //设置默认排序 安装巡检日期倒序排序
        if(null == sorter || sorter.isEmpty()){
            sorter.add(new FieldSort("CHECK_DATE_", Direction.DESC));
            queryFilter.setSorter(sorter);
        }


        IPage<CulvertOftenCheck> result = baseMapper.queryCulvertOftenCheck(convert2IPage(queryFilter.getPageBean()), map, convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<>(result);

    }

    @Override
    public void saveCulvertOftenCheck(CulvertOftenCheckVo vo) {
        CulvertOftenCheck culvertOftenCheck = vo.getCulvertOftenCheck();
        culvertOftenCheck.setIsDele("0");
        this.create(culvertOftenCheck);
        vo.getCulvertOftenCheckDetails().forEach(s -> {
            s.setId(null);
            s.setCulvertOftenCheckId(culvertOftenCheck.getId());
            this.culvertOftenCheckDetailManager.saveOrUpdate(s);
        });

        //保存附件信息
        List<Accessory> accessoryList = vo.getAccessories();
        //资源ID
        String id = culvertOftenCheck.getId();
        if (null !=accessoryList && accessoryList.size() > 0) {

            //获取附件信息
            accessoryList.forEach(s -> s.setSourceId(id));
            this.accessoryManager.saveBatch(accessoryList);
        }
    }

    @Override
    public void updateCulvertOftenCheck(CulvertOftenCheckVo vo) {
        CulvertOftenCheck culvertOftenCheck = vo.getCulvertOftenCheck();

        this.update(culvertOftenCheck);
        vo.getCulvertOftenCheckDetails().forEach(s -> {
            s.setCulvertOftenCheckId(culvertOftenCheck.getId());
            this.culvertOftenCheckDetailManager.saveOrUpdate(s);
        });
        //保存附件信息
        List<Accessory> accessoryList = vo.getAccessories();
        //资源ID
        String id = culvertOftenCheck.getId();
        if (null !=accessoryList && accessoryList.size() > 0) {
            //删除原来的附件信息
            this.accessoryManager.delAccessoryBySourceId(id);
            //获取附件信息
            accessoryList.forEach(s -> s.setSourceId(id));
            this.accessoryManager.saveOrUpdateBatch(accessoryList);
        }
    }

    @Override
    public CulvertOftenCheckVo getCulvertOftenCheckById(String id) {
        CulvertOftenCheckVo checkVo = new CulvertOftenCheckVo();
        CulvertOftenCheck culvertOftenCheck = this.getById(id);
        if (culvertOftenCheck!=null) {
            checkVo.setCulvertOftenCheck(culvertOftenCheck);
            QueryWrapper<CulvertOftenCheckDetail> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(culvertOftenCheck.getId())) {
                queryWrapper.eq("CULVERT_OFTEN_CHECK_ID_", culvertOftenCheck.getId());
                List<CulvertOftenCheckDetail> sideSlopeOftenCheckDetailList = this.culvertOftenCheckDetailDao.selectList(queryWrapper);
                checkVo.setCulvertOftenCheckDetails(sideSlopeOftenCheckDetailList);
            }
            List<Accessory> accessories = this.accessoryManager.getAccessoryBySourceId(id);
            checkVo.setAccessories(accessories);
        }
        return checkVo;
    }

    @Override
    public void importExcelData(MultipartFile file, CulvertOftenCheck parseObject) {
        Assert.notNull(parseObject, "主数据不能为空");

        try (InputStream inputStream = file.getInputStream();) {
            // 获取数据
            List<CulvertOftenCheckDetail> data = ExcelImportUtil.importExcel(inputStream, CulvertOftenCheckDetail.class, new ImportParams());
            CulvertOftenCheckVo vo = new CulvertOftenCheckVo();
            vo.setCulvertOftenCheck(parseObject);
            vo.setCulvertOftenCheckDetails(data);
            saveCulvertOftenCheck(vo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveSiteStatistic(CulvertOftenCheck culvertOftenCheck){
        SiteStatistic siteStatistic = new SiteStatistic();
        String checkId = culvertOftenCheck.getCulvertId();
        BizCulvertInformation culvertInformation = culvertInformationManager.getById(checkId);
        siteStatistic.setRoadSegmentId(culvertInformation.getRoadSegmentId());
        siteStatistic.setRoadSegmentName(culvertInformation.getRoadSegmentName());
        siteStatistic.setCompanyId(culvertOftenCheck.getCompanyId());
        siteStatistic.setCompanyName(culvertOftenCheck.getCompanyName());
        siteStatistic.setSiteCode(5);
        siteStatistic.setSiteName("涵洞经常检查");
        Date checkDate = culvertOftenCheck.getCheckDate();
        String month = new SimpleDateFormat("yyyy-MM").format(checkDate);
        siteStatistic.setAccDateMonth(month);
        String year = new SimpleDateFormat("yyyy").format(checkDate);
        siteStatistic.setAccDateYear(year);
        siteStatistic.setComplete("1");
        siteStatistic.setCompleteNo("0");
        QueryWrapper<SiteStatistic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(month), "ACC_DATE_MONTH_", month);
        queryWrapper.eq(StringUtils.isNotEmpty(year), "ACC_DATE_YEAR_", year);
        queryWrapper.eq(StringUtils.isNotEmpty(culvertInformation.getRoadSegmentId()), "ROAD_SEGMENT_ID_", culvertInformation.getRoadSegmentId());
        queryWrapper.eq(StringUtils.isNotEmpty(culvertInformation.getCompanyId()), "COMPANY_ID_", culvertInformation.getCompanyId());
        queryWrapper.eq("SITE_CODE_", 5);
        queryWrapper.eq("SITE_NAME_", "涵洞经常检查");
        List<SiteStatistic> siteStatistics = siteStatisticDao.selectList(queryWrapper);
        if (siteStatistics.size() > 0) {
            SiteStatistic statistic = siteStatistics.get(0);
            statistic.setComplete(String.valueOf(Integer.parseInt(statistic.getCompleteNo()) + 1));
            this.siteStatisticDao.update(siteStatistic, queryWrapper);
        } else {
            siteStatisticDao.insert(siteStatistic);
        }
    }
}
