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.TunnelInformationManager;
import com.artfess.yhxt.basedata.model.Accessory;
import com.artfess.yhxt.basedata.model.TunnelInformation;
import com.artfess.yhxt.check.detail.dao.TunnelOftenCheckDetailDao;
import com.artfess.yhxt.check.detail.manager.TunnelOftenCheckDetailManager;
import com.artfess.yhxt.check.detail.model.TunnelOftenCheckDetail;
import com.artfess.yhxt.check.regular.model.TunnelOftenCheck;
import com.artfess.yhxt.check.regular.dao.TunnelOftenCheckDao;
import com.artfess.yhxt.check.regular.manager.TunnelOftenCheckManager;
import com.artfess.yhxt.check.regular.model.TunnelOftenCheck;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.yhxt.check.regular.vo.TunnelOftenCheckVo;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 隧道经常检查表 服务实现类
 *
 * @author xzh
 * @company 阿特菲斯信息技术有限公司
 * @since 2021-08-04
 */
@Service
public class TunnelOftenCheckManagerImpl extends BaseManagerImpl<TunnelOftenCheckDao, TunnelOftenCheck> implements TunnelOftenCheckManager {

    @Autowired
    private TunnelOftenCheckDetailManager tunnelOftenCheckDetailManager;

    @Resource
    private TunnelOftenCheckDetailDao tunnelOftenCheckDetailDao;
    @Resource
    private TunnelInformationManager tunnelInformationManager;
    @Resource
    private SiteStatisticDao siteStatisticDao;
    @Resource
    private AccessoryManager accessoryManager;


    @Override
    public PageList<TunnelOftenCheck> queryTunnelOftenCheck(QueryFilter<TunnelOftenCheck> 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<TunnelOftenCheck> result = baseMapper.queryTunnelOftenCheck(convert2IPage(queryFilter.getPageBean()), map, convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<>(result);
    }

    @Override
    public void saveTunnelOftenCheck(TunnelOftenCheckVo vo) {
        TunnelOftenCheck tunnelOftenCheck = vo.getTunnelOftenCheck();
        tunnelOftenCheck.setIsDele("0");
        this.saveOrUpdate(tunnelOftenCheck);
        vo.getTunnelOftenCheckDetails().forEach(s -> {
            s.setId(null);
            s.setTunnelOftenCheckId(tunnelOftenCheck.getId());
            this.tunnelOftenCheckDetailManager.saveOrUpdate(s);
        });
        //保存附件信息
        List<Accessory> accessoryList = vo.getAccessories();
        //资源ID
        String id = tunnelOftenCheck.getId();
        if (null !=accessoryList && accessoryList.size() > 0) {
            //获取附件信息
            accessoryList.forEach(s -> s.setSourceId(id));
            this.accessoryManager.saveBatch(accessoryList);
        }
    }

    @Override
    public void updateTunnelOftenCheck(TunnelOftenCheckVo vo) {
        TunnelOftenCheck tunnelOftenCheck = vo.getTunnelOftenCheck();
        this.update(tunnelOftenCheck);
        vo.getTunnelOftenCheckDetails().forEach(s -> {
            s.setTunnelOftenCheckId(tunnelOftenCheck.getId());
            this.tunnelOftenCheckDetailManager.saveOrUpdate(s);
        });
        //保存附件信息
        List<Accessory> accessoryList = vo.getAccessories();
        //资源ID
        String id = tunnelOftenCheck.getId();
        if (null !=accessoryList && accessoryList.size() > 0) {
            //删除原来的附件信息
            this.accessoryManager.delAccessoryBySourceId(id);
            //获取附件信息
            accessoryList.forEach(s -> s.setSourceId(id));
            this.accessoryManager.saveOrUpdateBatch(accessoryList);
        }
    }

    @Override
    public TunnelOftenCheckVo getTunnelOftenCheckById(String id) {
        TunnelOftenCheckVo checkVo = new TunnelOftenCheckVo();
        TunnelOftenCheck tunnelOftenCheck = this.getById(id);
        if (tunnelOftenCheck!=null) {
            checkVo.setTunnelOftenCheck(tunnelOftenCheck);
            QueryWrapper<TunnelOftenCheckDetail> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(tunnelOftenCheck.getId())) {
                queryWrapper.eq("TUNNEL_OFTEN_CHECK_ID_", tunnelOftenCheck.getId());
                List<TunnelOftenCheckDetail> bridgeOftenCheckDetails = this.tunnelOftenCheckDetailDao.selectList(queryWrapper);
                checkVo.setTunnelOftenCheckDetails(bridgeOftenCheckDetails);
            }
            List<Accessory> accessories = this.accessoryManager.getAccessoryBySourceId(id);
            checkVo.setAccessories(accessories);
        }
        return checkVo;
    }

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

        try (InputStream inputStream = file.getInputStream();) {
            // 获取数据
            List<TunnelOftenCheckDetail> data = ExcelImportUtil.importExcel(inputStream, TunnelOftenCheckDetail.class, new ImportParams());
            TunnelOftenCheckVo vo = new TunnelOftenCheckVo();
            vo.setTunnelOftenCheck(parseObject);
            vo.setTunnelOftenCheckDetails(data);
            saveTunnelOftenCheck(vo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveSiteStatistic(TunnelOftenCheck tunnelOftenCheck){
        SiteStatistic siteStatistic = new SiteStatistic();
        String tunnelId = tunnelOftenCheck.getTunnelId();
        TunnelInformation tunnel = tunnelInformationManager.getById(tunnelId);
        siteStatistic.setRoadSegmentId(tunnel.getRoadSegmentId());
        siteStatistic.setRoadSegmentName(tunnel.getRoadSegmentName());
        siteStatistic.setCompanyId(tunnelOftenCheck.getCompanyId());
        siteStatistic.setCompanyName(tunnelOftenCheck.getCompanyName());
        siteStatistic.setSiteCode(4);
        siteStatistic.setSiteName("隧道经常检查");
        Date checkDate = tunnelOftenCheck.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(tunnel.getRoadSegmentId()), "ROAD_SEGMENT_ID_", tunnel.getRoadSegmentId());
        queryWrapper.eq(StringUtils.isNotEmpty(tunnel.getCompanyId()), "COMPANY_ID_", tunnel.getCompanyId());
        queryWrapper.eq("SITE_CODE_", 4);
        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);
        }
    }
}
