package com.ruoyi.system.service.grid.impl;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.grid.*;
import com.ruoyi.system.domain.grid.ext.GridCompanyExt;
import com.ruoyi.system.domain.grid.ext.GridCompanyLawArchivesExt;
import com.ruoyi.system.domain.grid.vo.GridCompanyLawArchivesParam;
import com.ruoyi.system.listener.MyBaseService;
import com.ruoyi.system.mapper.grid.GridCompanyExtMapper;
import com.ruoyi.system.mapper.grid.GridCompanyLawArchivesExtMapper;
import com.ruoyi.system.mapper.grid.GridCompanyLawArchivesMapper;
import com.ruoyi.system.service.BaseServiceImpl;
import com.ruoyi.system.service.grid.GridCompanyLawArchivesAttachmentService;
import com.ruoyi.system.service.grid.GridCompanyLawArchivesService;
import com.ruoyi.system.service.grid.GridCompanyService;
import com.ruoyi.system.service.grid.GridRegionService;
import com.ruoyi.system.service.other.BsCommonService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@MyBaseService
public class GridCompanyLawArchivesServiceImpl extends BaseServiceImpl<GridCompanyLawArchivesMapper, GridCompanyLawArchives, GridCompanyLawArchivesExample> implements GridCompanyLawArchivesService {

    private static final Logger LOGGER = LoggerFactory.getLogger(GridCompanyLawArchivesServiceImpl.class);

    @Autowired
    GridCompanyLawArchivesMapper wsCompanyLawArchivesMapper;
    @Autowired
    GridCompanyLawArchivesExtMapper wsCompanyLawArchivesExtMapper;
    @Autowired
    GridCompanyLawArchivesAttachmentService wsCompanyLawArchivesAttachmentService;
    @Autowired
    GridCompanyService wsCompanyService;
    @Autowired
    GridRegionService bsWgxxbService;
    @Autowired
    TransactionTemplate transactionTemplate;
    @Autowired
    BsCommonService bsCommonService;
    @Autowired
    GridCompanyExtMapper wsCompanyExtMapper;

    @Override
    public PageInfo pageInfos(GridCompanyLawArchivesParam check, Integer pageNo, Integer pageSize) {
        PageInfo<GridCompanyLawArchivesExt> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(pageNo);
        pageInfo.setPageSize(pageSize);
        if (StringUtils.isBlank(check.getIsValid())) {
            check.setIsValid("1");
        }
        int currIndex = (pageNo - 1) * pageSize;
        if (StringUtils.isNotBlank(check.getWgCode())) {
            GridRegionExample ex = new GridRegionExample();
            GridRegionExample.Criteria ca = ex.createCriteria();
            ca.andWgCodeEqualTo(check.getWgCode());
            ca.andIsValidEqualTo("1");
            GridRegion bsWgxxb = bsWgxxbService.selectFirstByExample(ex);
            if (bsWgxxb == null) {
                throw new RuntimeException("查询失败：找不到对应的网格");
            }
            if (!"1".equals(bsWgxxb.getLevel())) {
                List<String> companyIds = getWgChildIds(bsWgxxb);
                if (CollectionUtils.isEmpty(companyIds)) {
                    return pageInfo;
                }
                check.setCompanyIds(companyIds);
            }
        }
        int totalIndex = (int) wsCompanyLawArchivesExtMapper.countByExample(check);
        check.setCurrIndex(currIndex);
        check.setPageSize(pageSize);
        pageInfo.setTotal(totalIndex);
        if (totalIndex == 0) {
            pageInfo.setList(new ArrayList<>());
            return pageInfo;
        }
        List<GridCompanyLawArchivesExt> archivesExts = wsCompanyLawArchivesExtMapper.selectByExample(check);
        if (!CollectionUtils.isEmpty(archivesExts)) {
            for (GridCompanyLawArchivesExt ext : archivesExts) {
                List<GridCompanyLawArchivesAttachment> attachments = wsCompanyLawArchivesAttachmentService.list(ext.getId());
                ext.setAttachmentList(attachments);
            }
        }
        pageInfo.setList(archivesExts);
        return pageInfo;
    }

    @Override
    public GridCompanyLawArchivesExt detail(String id) {
        GridCompanyLawArchives wsCompanyLawArchives = wsCompanyLawArchivesMapper.selectByPrimaryKey(id);
        if (wsCompanyLawArchives == null) {
            throw new RuntimeException("查询失败：未找到对应数据");
        }
        GridCompanyLawArchivesExt archivesExt = new GridCompanyLawArchivesExt();
        BeanUtils.copyProperties(wsCompanyLawArchives, archivesExt);
        GridCompany company = wsCompanyService.selectByPrimaryKey(archivesExt.getCompanyId());
        if (company != null) {
            archivesExt.setCompanyName(company.getCompanyName());
            archivesExt.setCompanyType(company.getQylxCode());
            archivesExt.setCompanyTypeName(bsCommonService.getName(company.getQylxCode()));
            archivesExt.setWgCode(company.getWgCode());
            GridRegionExample ex = new GridRegionExample();
            GridRegionExample.Criteria ca = ex.createCriteria();
            ca.andWgCodeEqualTo(company.getWgCode());
            ca.andIsValidEqualTo("1");
            GridRegion bsWgxxb = bsWgxxbService.selectFirstByExample(ex);
            archivesExt.setWgName(bsWgxxb == null ? "" : bsWgxxb.getWgName());
        }
        archivesExt.setArchivesTypeName(bsCommonService.getName(archivesExt.getArchivesType()));
        List<GridCompanyLawArchivesAttachment> attachments = wsCompanyLawArchivesAttachmentService.list(id);
        archivesExt.setAttachmentList(attachments);
        return archivesExt;
    }

    @Override
    public void save(GridCompanyLawArchivesExt archivesExt) {
        if (StringUtils.isBlank(archivesExt.getCompanyId())
                || StringUtils.isBlank(archivesExt.getCreateUserId())
                || StringUtils.isBlank(archivesExt.getCreateUsername())
                || StringUtils.isBlank(archivesExt.getName())
                || StringUtils.isBlank(archivesExt.getCreateTime())
                || StringUtils.isBlank(archivesExt.getArchivesType())
                || StringUtils.isBlank(archivesExt.getArchivesNo())
                || CollectionUtils.isEmpty(archivesExt.getAttachmentList())) {
            throw new RuntimeException("保存失败：缺少必要参数");
        }
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                GridCompanyLawArchives wsCompanyLawArchives = new GridCompanyLawArchives();
                BeanUtils.copyProperties(archivesExt, wsCompanyLawArchives);
                wsCompanyLawArchives.setIsValid("1");
                wsCompanyLawArchives.setId(UUID.randomUUID().toString());
                wsCompanyLawArchivesMapper.insert(wsCompanyLawArchives);
                wsCompanyLawArchivesAttachmentService.save(archivesExt.getAttachmentList(), wsCompanyLawArchives.getId());
            }
        });
    }

    @Override
    public void update(GridCompanyLawArchivesExt archivesExt) {
        if (StringUtils.isBlank(archivesExt.getId())
                || StringUtils.isBlank(archivesExt.getCreateUserId())
                || StringUtils.isBlank(archivesExt.getCreateUsername())
                || StringUtils.isBlank(archivesExt.getName())
                || StringUtils.isBlank(archivesExt.getCreateTime())
                || StringUtils.isBlank(archivesExt.getArchivesType())
                || StringUtils.isBlank(archivesExt.getArchivesNo())
                || CollectionUtils.isEmpty(archivesExt.getAttachmentList())) {
            throw new RuntimeException("复查失败：缺少必要参数");
        }
        GridCompanyLawArchives wsCompanyLawArchives = wsCompanyLawArchivesMapper.selectByPrimaryKey(archivesExt.getId());
        if (wsCompanyLawArchives == null) {
            throw new RuntimeException("复查失败：未找到对应的执法档案");
        }
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                wsCompanyLawArchives.setCreateUserId(archivesExt.getCreateUserId());
                wsCompanyLawArchives.setCreateUsername(archivesExt.getCreateUsername());
                wsCompanyLawArchives.setCompanyId(archivesExt.getCompanyId());
                wsCompanyLawArchives.setName(archivesExt.getName());
                wsCompanyLawArchives.setCreateTime(archivesExt.getCreateTime());
                wsCompanyLawArchives.setArchivesType(archivesExt.getArchivesType());
                wsCompanyLawArchivesMapper.updateByPrimaryKey(wsCompanyLawArchives);
                wsCompanyLawArchivesAttachmentService.save(archivesExt.getAttachmentList(), archivesExt.getId());
            }
        });
    }

    @Override
    public void delete(String id) {
        GridCompanyLawArchives archives = wsCompanyLawArchivesMapper.selectByPrimaryKey(id);
        if (archives == null) {
            throw new RuntimeException("删除失败：未找到对应的执法档案");
        }
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                archives.setIsValid("0");
                wsCompanyLawArchivesMapper.updateByPrimaryKey(archives);
                wsCompanyLawArchivesAttachmentService.save(null, id);
            }
        });
    }

    // 根据网格获取网格下的所有关联企业
    private List<String> getWgChildIds(GridRegion rootWg) {
        List<GridCompany> wsCompanies = new ArrayList<>();
        List<String> companyIds = new ArrayList<>();
        GridCompanyExt extParam = new GridCompanyExt();
        extParam.setWgCode(rootWg.getWgCode());
        extParam.setWgValue(rootWg.getWgType());
        extParam.setIsValid((byte) 1);
        if ("2".equals(rootWg.getLevel())) {
            wsCompanies = wsCompanyExtMapper.selectCompanyBySecondLevel(extParam);
        } else if ("3".equals(rootWg.getLevel())) {
            wsCompanies = wsCompanyExtMapper.selectCompanyByThirdLevel(extParam);
        } else if ("4".equals(rootWg.getLevel())) {
            wsCompanies = wsCompanyExtMapper.selectCompanyByForthLevel(extParam);
        }
        if (CollectionUtils.isEmpty(wsCompanies)) {
            return null;
        }
        for (GridCompany wsCompany : wsCompanies) {
            companyIds.add(wsCompany.getId());
        }
        return companyIds;
    }
}
