package com.zfire.mall.manager.logic.saletype;

import cn.hutool.core.date.DateUtil;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.ExcelData;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.listV2.SaleTypeVO;
import com.zfire.mall.manager.commonmapper.listV2.CommonCMapper;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.plus.entity.ProductPrice;
import com.zfire.mall.manager.plus.entity.SaleType;
import com.zfire.mall.manager.plus.entity.WalletRebateSaleType;
import com.zfire.mall.manager.plus.service.ProductPriceService;
import com.zfire.mall.manager.plus.service.SaleTypeService;
import com.zfire.mall.manager.plus.service.WalletRebateSaleTypeService;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.mall.manager.zfire.util.FieldUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 销售类型维护
 */
@Slf4j
@Service
public class SaleTypeLogic {

    @Autowired
    SaleTypeService saleTypeService;
    @Autowired
    ProductPriceService productPriceService;
    @Autowired
    CommonCMapper commonCMapper;
    @Autowired
    WalletRebateSaleTypeService walletRebateSaleTypeService;
    @Autowired
    CommonLogic commonLogic;


    public IPage<SaleTypeVO> listV2(ZfireParamBean zfireParamBean){
        zfireParamBean = FieldUtils.supplyParam(zfireParamBean);
        IPage<SaleTypeVO> page = commonCMapper.querySaleType(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        return page;
    }




    public List<SaleType> listAll(){
        return saleTypeService.list();
    }

    public IPage<SaleType> list(String saleCode,String saleName,Boolean status,Integer pageNum,Integer pageSize){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        IPage<SaleType> page = saleTypeService.lambdaQuery()
                .in(CollectionUtils.isNotEmpty(adminUser.getAdminCompanyIds()),SaleType::getAdminCompanyId,adminUser.getAdminCompanyIds())
                .like(StringUtils.isNotEmpty(saleCode), SaleType::getSaleCode, saleCode)
                .like(StringUtils.isNotEmpty(saleName), SaleType::getSaleName, saleName)
                .eq(status != null, SaleType::getStatus, status)
                .orderByDesc(SaleType::getCreateTime)
                .page(new Page<>(pageNum, pageSize));
        return page;
    }

    public ExcelData export(List<SaleType> list){
        String[] titles = new String[]{"销售类型编码","销售类型名称","状态","创建人","创建时间","更新人","更新时间"};
        List<List<Object>> rows = new ArrayList<>();
        for(SaleType bean : list){
            List<Object> row = new ArrayList<>();
            row.add(bean.getSaleCode());
            row.add(bean.getSaleName());
            row.add(bean.getStatus()?"已启用":"未启用");
            row.add(bean.getCreateBy());
            row.add(DateUtil.formatDateTime(bean.getCreateTime()));
            row.add(bean.getUpdateBy());
            row.add(DateUtil.formatDateTime(bean.getUpdateTime()));
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }


    public void add(SaleType saleType){
        AdminUserCom adminUser = commonLogic.getAdminUser();

        Integer count = saleTypeService.lambdaQuery().eq(SaleType::getSaleCode, saleType.getSaleCode()).count();
        if(count > 0){
            throw new RemoteServiceException("销售类型编码已存在");
        }
        saleType.setId(null);
        saleType.setAdminCompanyId(adminUser.getAdminCompanyId());
        saleType.insert();
    }


    public void update(SaleType saleType){

        Integer count = saleTypeService.lambdaQuery()
                .eq(SaleType::getSaleCode, saleType.getSaleCode())
                .ne(SaleType::getId,saleType.getId())
                .count();
        if(count > 0){
            throw new RemoteServiceException("销售类型编码已存在");
        }
        saleType.updateById();
    }

    public void delete(String id){
        saleTypeService.removeById(id);
    }

    public SaleType detail(String id){
        SaleType saleType = saleTypeService.getById(id);
        return saleType;
    }


    /**
     * 获取返利钱包销售类型对应关系
     * @param walletRebateId
     * @param saleTypeId
     * @return
     */
    public WalletRebateSaleType getBySaleTypeRebateWallet(String walletRebateId,String saleTypeId){
        if(StringUtils.isEmpty(walletRebateId) || StringUtils.isEmpty(saleTypeId)){
            return null;
        }
        return walletRebateSaleTypeService.lambdaQuery()
                .eq(WalletRebateSaleType::getWalletRebateId,walletRebateId)
                .eq(WalletRebateSaleType::getSaleTypeId,saleTypeId).last("limit 1").one();
    }

    /**
     * 家用工程专用销售类型
     * @return
     */
    public List<SaleType> homeList(){
        List<ProductPrice> productPrices = productPriceService.query()
                .select("DISTINCT sale_type_id")
                .eq("bill_type","HOME")
                .list();
        List<String> saleTypeIds = productPrices.stream().map(ProductPrice::getSaleTypeId).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(saleTypeIds)){
            return new ArrayList<>();
        }
        return saleTypeService.lambdaQuery().eq(SaleType::getStatus,true).in(SaleType::getId,saleTypeIds).list();
    }

}
