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.BridgeInformationManager;
import com.artfess.yhxt.basedata.model.Accessory;
import com.artfess.yhxt.basedata.model.BridgeInformation;
import com.artfess.yhxt.check.detail.dao.BridgeRegularCheckDetailDao;
import com.artfess.yhxt.check.detail.manager.BridgeRegularCheckDetailManager;
import com.artfess.yhxt.check.detail.model.BridgeRegularCheckDetail;
import com.artfess.yhxt.check.regular.dao.BridgeRegularCheckDao;
import com.artfess.yhxt.check.regular.manager.BridgeRegularCheckManager;
import com.artfess.yhxt.check.regular.model.BridgeRegularCheck;
import com.artfess.yhxt.check.regular.vo.BridgeRegularCheckFjVo;
import com.artfess.yhxt.check.regular.vo.BridgeRegularCheckVo;
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 javax.servlet.http.HttpServletResponse;
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-16
 */
@Service
public class BridgeRegularCheckManagerImpl extends BaseManagerImpl<BridgeRegularCheckDao, BridgeRegularCheck> implements BridgeRegularCheckManager {
    @Resource
    private BridgeRegularCheckDetailManager bridgeRegularCheckDetailManager;
    @Resource
    private BridgeRegularCheckDetailDao bridgeRegularCheckDetailDao;
    @Resource
    private AccessoryManager accessoryManager;

    @Resource
    private BridgeInformationManager bridgeInformationManager;
    @Resource
    private SiteStatisticDao siteStatisticDao;

    @Override
    public PageList<BridgeRegularCheck> queryBridgeRegularCheck(QueryFilter<BridgeRegularCheck> queryFilter) {

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

    @Override
    public void saveBridgeRegularCheck(BridgeRegularCheckVo vo) {
        BridgeRegularCheck bridgeRegularCheck = vo.getBridgeRegularCheck();
        bridgeRegularCheck.setIsDele("0");
        this.saveOrUpdate(bridgeRegularCheck);
        List<BridgeRegularCheckDetail> bridgeRegularChecks = vo.getBridgeRegularChecks();
        if (bridgeRegularChecks.size() > 0) {
            for (BridgeRegularCheckDetail regularCheck : bridgeRegularChecks) {
                regularCheck.setBridgeRegularCheckId(bridgeRegularCheck.getId());
                this.bridgeRegularCheckDetailManager.save(regularCheck);
            }
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBridgeRegularFjCheck(BridgeRegularCheckFjVo vo) {
        BridgeRegularCheck bridgeRegularCheck = vo.getBridgeRegularCheck();
        bridgeRegularCheck.setIsDele("0");
        this.saveOrUpdate(bridgeRegularCheck);
        List<BridgeRegularCheckDetail> bridgeRegularChecks = vo.getBridgeRegularChecks();
        if (bridgeRegularChecks.size() > 0) {
            for (BridgeRegularCheckDetail regularCheck : bridgeRegularChecks) {
                regularCheck.setId(null);
                regularCheck.setBridgeRegularCheckId(bridgeRegularCheck.getId());
                this.bridgeRegularCheckDetailManager.save(regularCheck);
            }
        }
        //保存附件信息
        List<Accessory> accessoryList = vo.getAccessories();
        //资源ID
        String id = bridgeRegularCheck.getId();
        if (null !=accessoryList && accessoryList.size() > 0) {
            accessoryList.forEach(s -> s.setSourceId(id));
            this.accessoryManager.saveBatch(accessoryList);
        }
    }

    @Override
    public void updateBridgeRegularCheck(BridgeRegularCheckFjVo vo) {
        BridgeRegularCheck bridgeRegularCheck = vo.getBridgeRegularCheck();
        this.update(bridgeRegularCheck);
        List<BridgeRegularCheckDetail> checks = vo.getBridgeRegularChecks();
        if (checks.size() > 0) {
            for (BridgeRegularCheckDetail check : checks) {
                check.setBridgeRegularCheckId(bridgeRegularCheck.getId());
                this.bridgeRegularCheckDetailManager.update(check);
            }
        }
        //保存附件信息
        List<Accessory> accessoryList = vo.getAccessories();
        //资源ID
        String id = bridgeRegularCheck.getId();
        if (null !=accessoryList && accessoryList.size() > 0) {
            //删除原来的附件信息
            this.accessoryManager.delAccessoryBySourceId(id);
            //获取附件信息
            accessoryList.forEach(s -> s.setSourceId(id));
            this.accessoryManager.saveOrUpdateBatch(accessoryList);
        }
    }

    @Override
    public BridgeRegularCheckVo getBridgeRegularCheckById(String id) {
        BridgeRegularCheckVo bridgeRegularCheckVo = new BridgeRegularCheckVo();
        BridgeRegularCheck bridgeRegularCheck = this.getById(id);
        bridgeRegularCheckVo.setBridgeRegularCheck(bridgeRegularCheck);

        QueryWrapper<BridgeRegularCheckDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(bridgeRegularCheck.getId()), "BRIDGE_REGULAR_CHECK_ID_", id);
        List<BridgeRegularCheckDetail> bridgeRegularCheckDetails = this.bridgeRegularCheckDetailDao.selectList(queryWrapper);
        bridgeRegularCheckVo.setBridgeRegularChecks(bridgeRegularCheckDetails);

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

        bridgeRegularCheckVo.setAccessories(accessories);



        return bridgeRegularCheckVo;
    }

    @Override
    public Accessory minioRegularCheckUpload(MultipartFile file, String sourceId) {
        return this.accessoryManager.minIoUpload(file, "regular", "", "yhxt", sourceId);
    }

    @Override
    public void minioRegularCheck(List<String> asList) {
        asList.forEach(s -> {

            this.accessoryManager.minIoRemoveFile(s, "regular", "yhxt");
        });
    }

    @Override
    public void downloadRegularCheckUpload(String ids, HttpServletResponse response) throws Exception {
        this.accessoryManager.minIoDownFile(ids, "regular", "download/regular", "yhxt", response);
    }


    @Override
    public void importExcelData(MultipartFile file, BridgeRegularCheck parseObject) {
        Assert.notNull(parseObject, "主数据不能为空");
        try (InputStream inputStream = file.getInputStream();) {
            // 获取数据
            List<BridgeRegularCheckDetail> data = ExcelImportUtil.importExcel(inputStream, BridgeRegularCheckDetail.class, new ImportParams());
            BridgeRegularCheckVo vo = new BridgeRegularCheckVo();
            vo.setBridgeRegularCheck(parseObject);
            vo.setBridgeRegularChecks(data);
            saveBridgeRegularCheck(vo);
        } catch (Exception e) {
            e.printStackTrace();
        }}
    private void saveSiteStatistic(BridgeRegularCheck bridgeRegularCheck) {
        SiteStatistic siteStatistic = new SiteStatistic();
        String brigeId = bridgeRegularCheck.getBrigeId();
        BridgeInformation bridge = bridgeInformationManager.getById(brigeId);
        siteStatistic.setRoadSegmentId(bridge.getRoadSegmentId());
        siteStatistic.setRoadSegmentName(bridge.getRoadSegmentName());
        siteStatistic.setCompanyId(bridgeRegularCheck.getCompanyId());
        siteStatistic.setCompanyName(bridgeRegularCheck.getCompanyName());
        siteStatistic.setSiteCode(7);
        siteStatistic.setSiteName("桥梁定期检查");
        LocalDate checkDate = bridgeRegularCheck.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(bridge.getRoadSegmentId()), "ROAD_SEGMENT_ID_", bridge.getRoadSegmentId());
        queryWrapper.eq(StringUtils.isNotEmpty(bridge.getCompanyId()), "COMPANY_ID_", bridge.getCompanyId());
        queryWrapper.eq("SITE_CODE_", 7);
        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);
        }
    }

}
