package com.gree.mall.manager.logic.charging;

import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.ExcelData;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.charging.ChargingStandardBean;
import com.gree.mall.manager.bean.listvo.ChargingStandard2VO;
import com.gree.mall.manager.bean.listvo.ChargingStandardTypeVO;
import com.gree.mall.manager.bean.listvo.ChargingStandardVO;
import com.gree.mall.manager.commonmapper.CommonMapper;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.Brand;
import com.gree.mall.manager.plus.entity.ChargingStandard;
import com.gree.mall.manager.plus.entity.ChargingStandardType;
import com.gree.mall.manager.plus.entity.GoodsCategory;
import com.gree.mall.manager.plus.service.BrandService;
import com.gree.mall.manager.plus.service.ChargingStandardService;
import com.gree.mall.manager.plus.service.ChargingStandardTypeService;
import com.gree.mall.manager.plus.service.GoodsCategoryService;
import com.gree.mall.manager.utils.DateUtils;
import com.gree.mall.manager.utils.excel.ExcelUtils;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ChargingStandardLogic {

    @Autowired
    CommonLogic commonLogic;
    @Autowired
    ChargingStandardService chargingStandardService;
    @Autowired
    ChargingStandardTypeService chargingStandardTypeService;
    @Autowired
    CommonMapper commonMapper;
    @Autowired
    BrandService brandService;
    @Autowired
    GoodsCategoryService goodsCategoryService;

    /**
     * 收费标准业务类型-新版V2
     * @param zfireParamBean
     * @return
     */
    public IPage<ChargingStandardTypeVO> listType2(ZfireParamBean zfireParamBean){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        zfireParamBean.setCompanyWechatId(adminUser.getCompanyWechatId());

        zfireParamBean = FieldUtils.supplyParam(zfireParamBean,ChargingStandardTypeVO.class);
        IPage<ChargingStandardTypeVO> page = commonMapper.chargingStandardTypeList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        return page;
    }


    /**
     * 收费标准业务类型-列表
     * @return
     */
    public List<ChargingStandardType> listType(){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        return chargingStandardTypeService.lambdaQuery()
                .eq(StringUtils.isNotBlank(adminUser.getCompanyWechatId()),ChargingStandardType::getCompanyWechatId,adminUser.getCompanyWechatId())
                .eq(ChargingStandardType::getStatus,true)
                .orderByAsc(ChargingStandardType::getSortNum)
                //.orderByDesc(ChargingStandardType::getCreateTime)
                .list();
    }

    /**
     * 收费标准业务类型-保存
     * @param chargingStandardType
     * @param request
     */
    public void saveType(ChargingStandardType chargingStandardType,HttpServletRequest request){
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        if(StringUtils.isBlank(chargingStandardType.getId())){
            chargingStandardType.setCreateTime(new Date());
            chargingStandardType.setCreateBy(adminUser.getNickName());
            chargingStandardType.setUpdateBy(adminUser.getNickName());
            chargingStandardType.setUpdateTime(new Date());
        }else{
            chargingStandardType.setUpdateBy(adminUser.getNickName());
            chargingStandardType.setUpdateTime(new Date());
        }
        chargingStandardType.setCompanyWechatId(adminUser.getCompanyWechatId());
        chargingStandardType.setCompanyWechatName(adminUser.getCompanyName());
        chargingStandardType.insertOrUpdate();
    }

    /**
     * 收费标准业务类型-详情
     * @return
     */
    public ChargingStandardType detailType(String id){
        ChargingStandardType chargingStandardType = chargingStandardTypeService.getById(id);
        return chargingStandardType;
    }

    /**
     * 收费标准业务类型-删除
     * @param id
     */
    public void deleteType(String id){
        chargingStandardTypeService.removeById(id);
    }


    /**
     * 收费标准-列表v2
     */
    public IPage<ChargingStandardVO> list2(ZfireParamBean zfireParamBean){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        zfireParamBean.setCompanyWechatId(adminUser.getCompanyWechatId());

        zfireParamBean = FieldUtils.supplyParam(zfireParamBean,ChargingStandardVO.class);

        IPage<ChargingStandardVO> chargingStandardBeanIPage = commonMapper
                .chargingStandardList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()),zfireParamBean);
        return chargingStandardBeanIPage;
    }

    /**
     * 故障现象 列表
     */
    public IPage<ChargingStandard2VO> list3(ZfireParamBean zfireParamBean){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        zfireParamBean.setCompanyWechatId(adminUser.getCompanyWechatId());

        zfireParamBean = FieldUtils.supplyParam(zfireParamBean,ChargingStandard2VO.class);

        IPage<ChargingStandard2VO> chargingStandardBeanIPage = commonMapper
                .chargingStandardList2(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()),zfireParamBean);
        return chargingStandardBeanIPage;
    }



    /**
     * 收费标准/故障排查-列表
     */
    public IPage<ChargingStandardBean> list(Integer type,Boolean status,String brandId,String oneCategoryId,String twoCategoryId,String content1,
                                            Integer pageNum,Integer pageSize){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        IPage<ChargingStandardBean> chargingStandardBeanIPage = commonMapper.queryChargingStandrdList(new Page(pageNum, pageSize),
                type,status,brandId,oneCategoryId,twoCategoryId,content1,null,adminUser.getCompanyWechatId());
        return chargingStandardBeanIPage;
    }

    /**
     * 收费标准/故障排查-详情
     */
    public ChargingStandardBean detail(String id){
        IPage<ChargingStandardBean> chargingStandardBeanIPage = commonMapper.queryChargingStandrdList(new Page(1, -1),
                null,null,null,null,null,null,id,null);
        return chargingStandardBeanIPage.getRecords().get(0);
    }

    /**
     * 收费标准/故障排查-保存
     */
    public void save(ChargingStandard chargingStandard,HttpServletRequest request){
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        if(StringUtils.isBlank(chargingStandard.getId())){
            chargingStandard.setCreateTime(new Date());
            chargingStandard.setCreateBy(adminUser.getNickName());
            chargingStandard.setUpdateBy(adminUser.getNickName());
            chargingStandard.setUpdateTime(new Date());
        }else{
            chargingStandard.setUpdateBy(adminUser.getNickName());
            chargingStandard.setUpdateTime(new Date());
        }
        chargingStandard.setCompanyWechatId(adminUser.getCompanyWechatId());
        chargingStandard.setCompanyWechatName(adminUser.getCompanyName());
        chargingStandard.insertOrUpdate();
    }

    /**
     * 收费标准/故障排查-删除
     */
    public void delete(String id){
        chargingStandardService.removeById(id);
    }


    /**
     * 故障排查-导入
     */
    public void importData(MultipartFile file) throws IOException {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        List<Object> rows = ExcelUtils.importExcel(file);
        if(CollectionUtils.isEmpty(rows)){
            throw new RemoteServiceException("导入内容为空");
        }
        List<GoodsCategory> goodsCategoryList = goodsCategoryService.lambdaQuery()
                .eq(GoodsCategory::getCompanyWechatId,adminUser.getCompanyWechatId())
                .eq(GoodsCategory::getType, 2).list();
        Map<String, GoodsCategory> categoryMap1 = goodsCategoryList.stream().filter(v -> v.getLevel() == 1)
                .collect(Collectors.toMap(GoodsCategory::getName, v -> v));
        Map<String, GoodsCategory> categoryMap2 = goodsCategoryList.stream().filter(v -> v.getLevel() == 2)
                .collect(Collectors.toMap(GoodsCategory::getName, v -> v));
        Map<String, Brand> brandMap = brandService.lambdaQuery()
                .eq(Brand::getCompanyWechatId,adminUser.getCompanyWechatId())
                .list().stream().collect(Collectors.toMap(Brand::getBrandName, v -> v));

        List<ChargingStandard> list = new ArrayList<>();
        for(Object o : rows){
            List<Object> row = (List<Object>)o;
            String brandName = (String)row.get(0);
            String oneCategoryName = (String)row.get(1);
            String twoCategoryName = (String)row.get(2);
            String content1 = (String)row.get(3);
            String content2 = (String)row.get(4);

            Brand brand = brandMap.get(brandName);
            GoodsCategory goodsCategory1 = categoryMap1.get(oneCategoryName);
            GoodsCategory goodsCategory2 = categoryMap2.get(twoCategoryName);

            if(brand == null){
                throw new RemoteServiceException(brand+"品牌不存在于本系统");
            }
            if(goodsCategory1 == null){
                throw new RemoteServiceException(oneCategoryName+"一级分类不存在于本系统");
            }
            if(goodsCategory2 == null){
                throw new RemoteServiceException(twoCategoryName+"二级分类不存在于本系统");
            }
            if(!goodsCategory2.getParentId().equals(goodsCategory1.getCategoryId())){
                throw new RemoteServiceException(oneCategoryName+"与"+twoCategoryName+"非级联关系");
            }
            ChargingStandard chargingStandard = new ChargingStandard();
            chargingStandard.setBrandId(brand.getId());
            chargingStandard.setOneCategoryId(goodsCategory1.getCategoryId());
            chargingStandard.setTwoCategoryId(goodsCategory2.getCategoryId());
            chargingStandard.setType(2);
            chargingStandard.setContent1(content1);
            chargingStandard.setContent2(content2);
            chargingStandard.setCreateTime(new Date());
            chargingStandard.setUpdateTime(new Date());
            chargingStandard.setCreateBy(adminUser.getNickName());
            chargingStandard.setUpdateBy(adminUser.getNickName());
            chargingStandard.setCompanyWechatId(adminUser.getCompanyWechatId());
            chargingStandard.setCompanyWechatName(adminUser.getCompanyName());
            list.add(chargingStandard);
        }
        chargingStandardService.saveBatch(list);
    }


    /**
     * 导出
     */
    public ExcelData exportData(List<ChargingStandardBean> list){
        String[] titles = new String[]{"品牌","一级分类","二级分类","故障内容","故障排除指引","创建人","创建时间","修改人","修改时间","商户名称"};
        List<List<Object>> rows = new ArrayList<>();
        for(ChargingStandardBean bean : list){
            List<Object> row = new ArrayList<>();
            row.add(bean.getBrandName());
            row.add(bean.getOneCategoryName());
            row.add(bean.getTwoCategoryName());
            row.add(bean.getContent1());
            row.add(bean.getContent2());
            row.add(bean.getCreateBy());
            row.add(DateUtils.formatDate(bean.getCreateTime()));
            row.add(bean.getUpdateBy());
            row.add(DateUtils.formatDate(bean.getUpdateTime()));
            row.add(bean.getCompanyWechatName());
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }

}
