package com.wgb.system.service.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wgb.system.service.component.ExcelUtils;
import com.wgb.system.service.domain.mapper.BusinessCategoryMapper;
import com.wgb.system.service.domain.model.BusinessCategory;
import com.wgb.system.service.domain.request.BusinessCategoryRequest;
import com.wgb.system.service.domain.response.LayuiTableResponse;
import com.wgb.system.service.exception.InternalSystemUnHandlerException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class BusinessCategoryService {


    @Value("${sys.business.category.price}")
    private BigDecimal price;

    private final BusinessCategoryMapper businessCategoryMapper;

    public BusinessCategoryService(BusinessCategoryMapper businessCategoryMapper) {
        this.businessCategoryMapper = businessCategoryMapper;
    }

    public LayuiTableResponse getBusinessCategoryList(BusinessCategoryRequest request){
        QueryWrapper<BusinessCategory> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(BusinessCategory::getParentId,request.getParentId())
                .orderByDesc(BusinessCategory::getCreateTime);
        IPage<BusinessCategory> iPage=new Page<>(request.getPage(),request.getLimit());
        IPage<BusinessCategory> pageList= businessCategoryMapper.selectPage(iPage,queryWrapper);
        return new LayuiTableResponse(0,"",pageList.getTotal(),pageList.getRecords());
    }

   public BusinessCategory getBusinessCategoryById(Long id,Integer state){
       QueryWrapper<BusinessCategory> queryWrapper=new QueryWrapper();
       queryWrapper.lambda().eq(BusinessCategory::getId,id);
       if (state!=null){
           queryWrapper.lambda().eq(BusinessCategory::getState,state);
       }
        return businessCategoryMapper.selectOne(queryWrapper);
    }

   public List<BusinessCategory> getBusinessCategoryByParentId(Long parentId,Integer state){
        QueryWrapper<BusinessCategory> queryWrapper=new QueryWrapper();
        queryWrapper.lambda().eq(BusinessCategory::getParentId,parentId);
        if (state!=null){
           queryWrapper.lambda().eq(BusinessCategory::getState,state);
        }
        return businessCategoryMapper.selectList(queryWrapper);
   }

    public void deleteById(Long id){
        businessCategoryMapper.deleteById(id);
    }

    public void saveOrUpdate(BusinessCategory businessCategory){
      if (businessCategory.getId()==null){
            BusinessCategory businessCategoryOne= businessCategoryMapper.selectOne(new QueryWrapper<BusinessCategory>().lambda().eq(BusinessCategory::getParentId,businessCategory.getParentId()).eq(BusinessCategory::getLevel,businessCategory.getLevel()));
            if (businessCategoryOne!=null){
              businessCategoryMapper.deleteById(businessCategoryOne.getId());
            }
            businessCategory.setCreateTime(LocalDateTime.now());
            businessCategory.setUserInstallationPrice(calculateThePrice(businessCategory.getInstallationPrice()));
            businessCategory.setUserModifyPrice(calculateThePrice(businessCategory.getModifyPrice()));
            businessCategory.setUserNewOpeningPrice(calculateThePrice(businessCategory.getNewOpeningPrice()));
            businessCategory.setUserOpeningPrice(calculateThePrice(businessCategory.getOpeningPrice()));
            businessCategoryMapper.insert(businessCategory);
        }else{
            businessCategoryMapper.updateById(businessCategory);
        }
    }

    public void updateByState(Long id ,Integer state){
        QueryWrapper<BusinessCategory> queryWrapper=new QueryWrapper();
        queryWrapper.lambda().eq(BusinessCategory::getId,id);
        BusinessCategory Category= businessCategoryMapper.selectOne(queryWrapper);
        if (Category==null){
            throw new InternalSystemUnHandlerException("05");
        }
        Category.setState(state);
        businessCategoryMapper.update(Category,queryWrapper);
    }

    public void uploadExcelFile(MultipartFile file)throws Exception{
        List<Map<String, Object>> excel = ExcelUtils.read(file.getInputStream());
        List<List<String>> data = excel.get(0) == null ? null : (List<List<String>>) excel.get(0).get("data");
        data.remove(0);
        data.stream().filter(i->{
            for (int j = 0; j <data.size() ; j++) {
                if (i.get(0)==null||i.get(1)==null||i.get(2)==null||i.get(3)==null){
                    return false;
                }
            }
            return i==null?false:true;
        });
        Long id = null;
        /*for (int i = 0; i <data.size() ; i++) {
            if (StringUtils.isNoneEmpty(data.get(i).get(0))){
                BusinessCategory businessCategory=businessCategoryMapper.selectOne(new QueryWrapper<BusinessCategory>().lambda().eq(BusinessCategory::getName,data.get(i).get(0)));
                if (businessCategory==null){
                    businessCategory= new BusinessCategory(data.get(i).get(0),1,0l,LocalDateTime.now().toString());
                    businessCategoryMapper.insertMapper(businessCategory);
                }
                id=businessCategory.getId();
            }
            businessCategoryMapper.insert(new BusinessCategory(
                    data.get(i).get(1),
                    id,
                    Integer.valueOf(data.get(i).get(2)),
                    Integer.valueOf(data.get(i).get(3)),
                    StringUtils.isNoneEmpty(data.get(i).get(4))?Integer.valueOf(data.get(i).get(4)):0,
                    StringUtils.isNoneEmpty(data.get(i).get(5))?Integer.valueOf(data.get(i).get(5)):0,
                    StringUtils.isNoneEmpty(data.get(i).get(6))?Integer.valueOf(data.get(i).get(6)):0,
                    StringUtils.isNoneEmpty(data.get(i).get(7))?Integer.valueOf(data.get(i).get(7)):0,
                    LocalDateTime.now().toString()
            ));
            continue;
        }*/
    }

    private BigDecimal calculateThePrice(BigDecimal driginalPrice){
      if (driginalPrice!=null){
        return driginalPrice.multiply(price).setScale(2,BigDecimal.ROUND_DOWN);
      }else{
        return new BigDecimal(0);
      }

    }

}
