package com.ningdatech.carapi.industry.manage;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Component;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ningdatech.basic.model.PageVo;
import com.ningdatech.carapi.common.aop.BuildChildrenRegionWrapper;
import com.ningdatech.carapi.common.constant.CommonConstant;
import com.ningdatech.carapi.common.contants.DefValConstants;
import com.ningdatech.carapi.common.util.CodeUtil;
import com.ningdatech.carapi.common.util.ExcelDownUtil;
import com.ningdatech.carapi.common.util.ExcelExportStyle;
import com.ningdatech.carapi.datascope.aop.LambdaDataScope;
import com.ningdatech.carapi.datascope.contants.LambdaDataScopeTypeEnum;
import com.ningdatech.carapi.industry.entity.ReadyMixedMortarIndustryManage;
import com.ningdatech.carapi.industry.model.dto.ReadyMixedMortarIndustryManageSaveDTO;
import com.ningdatech.carapi.industry.model.dto.ReadyMixedMortarIndustryManageUpdateDTO;
import com.ningdatech.carapi.industry.model.dto.ReadyMixedPageParamDTO;
import com.ningdatech.carapi.industry.model.vo.ReadyMixedMortarIndustryManageVO;
import com.ningdatech.carapi.industry.service.IReadyMixedMortarIndustryManageService;
import com.ningdatech.carapi.sys.helper.RegionsCacheHelper;
import com.ningdatech.carapi.user.security.auth.model.UserInfoDetails;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @Classname ReadyMixedMortarManage
 * @Description
 * @Date 2022/11/17 17:57
 * @Created by PoffyZhang
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class ReadyMixedMortarManage {

    private final IReadyMixedMortarIndustryManageService readyMixedMortarIndustryManageService;
    private final RegionsCacheHelper regionsCacheHelper;

    public PageVo<ReadyMixedMortarIndustryManageVO> list(ReadyMixedPageParamDTO param) {

        //Page<ReadyMixedMortarIndustryManage> page = param.page();

        Integer pageNumber = param.getPageNumber();
        Integer pageSize = param.getPageSize();
        LambdaQueryWrapper<ReadyMixedMortarIndustryManage> wrapper = Wrappers.lambdaQuery(ReadyMixedMortarIndustryManage.class);
        //ReadyMixedMortarManage context = (ReadyMixedMortarManage) AopContext.currentProxy();
        //context.buildWrapper(wrapper,param);

        wrapper.like(StringUtils.isNotBlank(param.getTitle()), ReadyMixedMortarIndustryManage::getTitle, param.getTitle())
                .isNotNull(ReadyMixedMortarIndustryManage::getRegionId)
                .orderBy(Boolean.TRUE, Boolean.FALSE, ReadyMixedMortarIndustryManage::getUpdateOn);
        List<ReadyMixedMortarIndustryManage> resultList = readyMixedMortarIndustryManageService.dataScopeList(wrapper,param);
        //List<ReadyMixedMortarIndustryManage> resultList = readyMixedMortarIndustryManageService.list(wrapper);

        // 省级部门上传的文件(所属区域为省级)，下级账号也要能看到
        List<ReadyMixedMortarIndustryManage> list = readyMixedMortarIndustryManageService
                .list(Wrappers.lambdaQuery(ReadyMixedMortarIndustryManage.class)
                .eq(ReadyMixedMortarIndustryManage::getRegionId, DefValConstants.ZJREGION_ID));
        resultList.addAll(list);

        if (CollUtil.isEmpty(resultList)) {
            return PageVo.empty();
        }

        List<ReadyMixedMortarIndustryManage> records = resultList.stream()
                .skip((long) (pageNumber - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());
        List<ReadyMixedMortarIndustryManageVO> data = records.stream().map(this::convert).collect(Collectors.toList());
        return PageVo.of(data, resultList.size());

        //context.search(page, wrapper, param);
        //if (CollUtil.isEmpty(page.getRecords())) {
        //    return PageVo.empty();
        //}
        //List<ReadyMixedMortarIndustryManageVO> data = page.getRecords().stream().map(w -> convert(w)).collect(Collectors.toList());
        //return PageVo.of(data, page.getTotal());
    }

    @LambdaDataScope
    @BuildChildrenRegionWrapper
    private void buildWrapper(LambdaQueryWrapper<ReadyMixedMortarIndustryManage> wrapper, ReadyMixedPageParamDTO param) {
        wrapper.like(StringUtils.isNotBlank(param.getTitle()), ReadyMixedMortarIndustryManage::getTitle, param.getTitle())
                .isNotNull(ReadyMixedMortarIndustryManage::getRegionId)
                .orderBy(Boolean.TRUE, Boolean.FALSE, ReadyMixedMortarIndustryManage::getUpdateOn);
    }

    public ReadyMixedMortarIndustryManageVO details(Long id) {
        LambdaQueryWrapper<ReadyMixedMortarIndustryManage> wrapper = Wrappers.lambdaQuery(ReadyMixedMortarIndustryManage.class);
        ReadyMixedMortarManage context = (ReadyMixedMortarManage) AopContext.currentProxy();
        context.buildStandardFileQuery(wrapper, id);
        ReadyMixedMortarIndustryManage record = readyMixedMortarIndustryManageService.getOne(wrapper);
        if (Objects.isNull(record)){
            return null;
        }
        // ReadyMixedMortarIndustryManage record = readyMixedMortarIndustryManageService.getById(id);
        return convert(record);
    }

    @LambdaDataScope(type = LambdaDataScopeTypeEnum.ALL)
    public void buildStandardFileQuery(LambdaQueryWrapper<ReadyMixedMortarIndustryManage> wrapper, Long id) {
        wrapper.eq(ReadyMixedMortarIndustryManage::getId,id);
    }

    /**
     * 查询
     *
     * @param page
     * @param param
     */
    @LambdaDataScope(wrapperIndex = 1)
    @BuildChildrenRegionWrapper(wrapperIndex = 1, entityIndex = 2)
    public void search(Page<ReadyMixedMortarIndustryManage> page, LambdaQueryWrapper<ReadyMixedMortarIndustryManage> wrapper, ReadyMixedPageParamDTO param) {
        wrapper.like(StringUtils.isNotBlank(param.getTitle()), ReadyMixedMortarIndustryManage::getTitle, param.getTitle())
                .orderBy(Boolean.TRUE, Boolean.FALSE, ReadyMixedMortarIndustryManage::getUpdateOn);
        readyMixedMortarIndustryManageService.page(page, wrapper);
    }

    private ReadyMixedMortarIndustryManageVO convert(ReadyMixedMortarIndustryManage data) {
        if (Objects.isNull(data)) {
            return null;
        }
        ReadyMixedMortarIndustryManageVO vo = BeanUtil.copyProperties(data, ReadyMixedMortarIndustryManageVO.class);
        CodeUtil.searchCompanyNameAndRegionName(vo);
        return vo;
    }


    public ReadyMixedMortarIndustryManageVO save(ReadyMixedMortarIndustryManageSaveDTO data, UserInfoDetails user) {
        ReadyMixedMortarIndustryManage record = BeanUtil.copyProperties(data, ReadyMixedMortarIndustryManage.class);
        Long regionId = user.getRegionId();
        Long companyId = user.getCompanyId();
        record.setRegionId(regionId);
        record.setCompanyId(companyId);
        CodeUtil.searchCompanyNameAndRegionName(record);
        record.setCreateBy(user.getUserId());
        record.setUpdateBy(user.getUserId());
        readyMixedMortarIndustryManageService.save(record);
        return BeanUtil.copyProperties(record, ReadyMixedMortarIndustryManageVO.class);
    }

    public ReadyMixedMortarIndustryManageVO modify(ReadyMixedMortarIndustryManageUpdateDTO data, UserInfoDetails user) {
        ReadyMixedMortarIndustryManage record = BeanUtil.copyProperties(data, ReadyMixedMortarIndustryManage.class);
        CodeUtil.searchCompanyNameAndRegionName(record);
        record.setUpdateBy(user.getUserId());
        readyMixedMortarIndustryManageService.updateById(record);
        return BeanUtil.copyProperties(record, ReadyMixedMortarIndustryManageVO.class);
    }

    public Boolean remove(Long id, UserInfoDetails user) {
        readyMixedMortarIndustryManageService.removeById(id);
        return Boolean.TRUE;
    }

    public void export(HttpServletResponse response, ReadyMixedPageParamDTO param) {
        param.page(CommonConstant.EXPORT_PAGE_NUMBER, CommonConstant.EXPORT_PAGE_SIZE);
        PageVo<ReadyMixedMortarIndustryManageVO> page = list(param);
        Collection<ReadyMixedMortarIndustryManageVO> collect = page.getRecords();
        String fileName = "预拌砂浆行业管理信息";
        ExcelDownUtil.setFileName(fileName, response);
        // 数据导出处理函数
        try {
            EasyExcel.write(response.getOutputStream(), ReadyMixedMortarIndustryManageVO.class)
                    .autoCloseStream(false)
                    .registerWriteHandler(ExcelExportStyle.formalStyle())
                    .sheet(fileName)
                    .doWrite(collect);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
