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.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.TunnelRegularCheckDetailDao;
import com.artfess.yhxt.check.detail.manager.TunnelRegularCheckDetailManager;
import com.artfess.yhxt.check.detail.model.TunnelRegularCheckDetail;
import com.artfess.yhxt.check.regular.model.BridgeRegularCheck;
import com.artfess.yhxt.check.regular.model.TunnelRegularCheck;
import com.artfess.yhxt.check.regular.dao.TunnelRegularCheckDao;
import com.artfess.yhxt.check.regular.manager.TunnelRegularCheckManager;
import com.artfess.yhxt.check.regular.model.TunnelRegularCheck;
import com.artfess.yhxt.check.regular.vo.TunnelRegularCheckVo;
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.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 隧道定期检查表 服务实现类
 *
 * @author xzh
 * @company 阿特菲斯信息技术有限公司
 * @since 2021-08-17
 */
@Service
public class TunnelRegularCheckManagerImpl extends BaseManagerImpl<TunnelRegularCheckDao, TunnelRegularCheck> implements TunnelRegularCheckManager {
    @Resource
    private TunnelRegularCheckDetailDao tunnelRegularCheckDetailDao;

    @Resource
    private TunnelRegularCheckDetailManager tunnelRegularCheckDetailManager;

    @Resource
    private TunnelInformationManager tunnelInformationManager;
    @Resource
    private SiteStatisticDao siteStatisticDao;
    @Resource
    private AccessoryManager accessoryManager;
    @Override
    public PageList<TunnelRegularCheck> queryTunnelRegularCheck(QueryFilter<TunnelRegularCheck> queryFilter) {


        HashMap<String, Object> map = new HashMap<>();
        Map<String, Object> params = queryFilter.getParams();
        if (params != null) {
            map.putAll(params);
        }
        IPage<TunnelRegularCheck> result = baseMapper.queryTunnelRegularCheck(convert2IPage(queryFilter.getPageBean()), map, convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<>(result);
    }

    @Override
    public void saveTunnelRegularCheck(TunnelRegularCheckVo vo) {
        TunnelRegularCheck tunnelRegularCheck = vo.getTunnelRegularCheck();
        tunnelRegularCheck.setIsDele("0");
        this.saveOrUpdate(tunnelRegularCheck);
        List<TunnelRegularCheckDetail> list = vo.getTunnelRegularCheckDetails();
        if (list.size()>0){
            for (TunnelRegularCheckDetail tunnelRegularCheckDetail : list) {
                tunnelRegularCheckDetail.setTunnelRegularCheckId(tunnelRegularCheck.getId());
                tunnelRegularCheckDetail.setId(null);
                this.tunnelRegularCheckDetailManager.create(tunnelRegularCheckDetail);
            }
        }
        //保存附件信息
        List<Accessory> accessoryList = vo.getAccessories();
        //资源ID
        String id = tunnelRegularCheck.getId();
        if (null !=accessoryList && accessoryList.size() > 0) {
            //获取附件信息
            accessoryList.forEach(s -> s.setSourceId(id));
            this.accessoryManager.saveBatch(accessoryList);
        }
    }

    @Override
    public void updateTunnelRegularCheck(TunnelRegularCheckVo vo) {
        TunnelRegularCheck tunnelRegularCheck = vo.getTunnelRegularCheck();
        this.update(tunnelRegularCheck);
        List<TunnelRegularCheckDetail> tunnelRegularCheckDetails = vo.getTunnelRegularCheckDetails();
        if (tunnelRegularCheckDetails.size()>0){
            for (TunnelRegularCheckDetail tunnelRegularCheckDetail : tunnelRegularCheckDetails) {
                tunnelRegularCheckDetail.setTunnelRegularCheckId(tunnelRegularCheck.getId());
                this.tunnelRegularCheckDetailManager.saveOrUpdate(tunnelRegularCheckDetail);
            }
        }
        //保存附件信息
        List<Accessory> accessoryList = vo.getAccessories();
        //资源ID
        String id = tunnelRegularCheck.getId();
        if (null !=accessoryList && accessoryList.size() > 0) {
            //删除原来的附件信息
            this.accessoryManager.delAccessoryBySourceId(id);
            //获取附件信息
            accessoryList.forEach(s -> s.setSourceId(id));
            this.accessoryManager.saveOrUpdateBatch(accessoryList);
        }
    }

    @Override
    public TunnelRegularCheckVo getTunnelRegularCheckById(String id) {
        TunnelRegularCheckVo tunnelRegularCheckVo = new TunnelRegularCheckVo();
        TunnelRegularCheck tunnelRegularCheck = this.getById(id);
        tunnelRegularCheckVo.setTunnelRegularCheck(tunnelRegularCheck);
        QueryWrapper<TunnelRegularCheckDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(tunnelRegularCheck.getId()),"TUNNEL_REGULAR_CHECK_ID_",id);
        List<TunnelRegularCheckDetail> tunnelRegularCheckDetails = this.tunnelRegularCheckDetailDao.selectList(queryWrapper);
        tunnelRegularCheckVo.setTunnelRegularCheckDetails(tunnelRegularCheckDetails);

        List<Accessory> accessories = this.accessoryManager.getAccessoryBySourceId(id);

        tunnelRegularCheckVo.setAccessories(accessories);

        return tunnelRegularCheckVo;
    }

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

        try (InputStream inputStream = file.getInputStream();) {
            // 获取数据
            List<TunnelRegularCheckDetail> data = ExcelImportUtil.importExcel(inputStream, TunnelRegularCheckDetail.class, new ImportParams());
            TunnelRegularCheckVo vo = new TunnelRegularCheckVo();
            vo.setTunnelRegularCheck(parseObject);
            vo.setTunnelRegularCheckDetails(data);
            saveTunnelRegularCheck(vo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveSiteStatistic(TunnelRegularCheck tunnelRegularCheck){
        SiteStatistic siteStatistic = new SiteStatistic();
        String tunnelId = tunnelRegularCheck.getTunnelId();
        TunnelInformation tunnel = tunnelInformationManager.getById(tunnelId);
        siteStatistic.setRoadSegmentId(tunnel.getRoadSegmentId());
        siteStatistic.setRoadSegmentName(tunnel.getRoadSegmentName());
        siteStatistic.setCompanyId(tunnelRegularCheck.getCompanyId());
        siteStatistic.setCompanyName(tunnelRegularCheck.getCompanyName());
        siteStatistic.setSiteCode(8);
        siteStatistic.setSiteName("隧道定期检查");
        LocalDate checkDate = tunnelRegularCheck.getCheckDate();
        String month = checkDate.format(DateTimeFormatter.ofPattern("yyyy-MM"));
        siteStatistic.setAccDateMonth(month);
        String year = checkDate.format(DateTimeFormatter.ofPattern("yyyy"));
        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);
        }
    }
}
