package com.bs.df.controller;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.bs.common.annotation.Anonymous;
import com.bs.common.core.domain.entity.SysUser;
import com.bs.common.core.domain.model.LoginUser;
import com.bs.common.utils.SecurityUtils;
import com.bs.df.domain.*;
import com.bs.df.service.*;
import com.bs.df.utils.HtmlUtils;
import com.bs.system.domain.DfArea;
import com.bs.system.mapper.SysUserMapper;
import com.bs.system.service.IDfAreaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.aspectj.weaver.patterns.IToken;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bs.common.annotation.Log;
import com.bs.common.core.controller.BaseController;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.core.page.TableDataInfo;
import com.bs.common.enums.BusinessType;
import com.bs.common.utils.poi.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.lang.Validator;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import static com.bs.common.utils.ServletUtils.getSession;

/**
 * 产品信息Controller
 *
 * @author bs
 * @date 2024-04-06
 */
@Api(tags = "产品信息")
@RestController
@RequestMapping("/product/info")
public class DfProductInfoController extends BaseController {
    @Resource
    private IDfProductInfoService dfProductInfoService;
    @Resource
    private IDfProductPosterService dfProductPosterService;
    @Resource
    private IDfAreaService dfAreaService;
    @Resource
    private IDfBrokerProductService dfBrokerProductService;
    @Resource
    private IDfBrokerService dfBrokerService;
    @Resource
    private IDfOrderService dfOrderService;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private IDfProductRecommendService dfProductRecommendService;



    /**
     * 分页查询产品信息列表
     */
    @ApiOperation("分页查询产品信息列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(DfProductInfo dfProductInfo) {
        SysUser sysUser = sysUserMapper.selectById(getUserId());
        List<DfProductInfo> list = selectInfo(dfProductInfo,sysUser,false);
        return getDataTable(list);
    }

    /**
     * 分页查询产品信息列表
     */
    @ApiOperation("分页查询产品信息列表")
    @GetMapping("/pageListVo")
    @Anonymous
    public TableDataInfo pageListVo(DfProductInfo dfProductInfo) {
        SysUser sysUser = sysUserMapper.selectById(dfProductInfo.getUserId());
        List<DfProductInfo> list = selectInfo(dfProductInfo,sysUser,true);
        return getDataTable(list);
    }

    private List<DfProductInfo> selectInfo(DfProductInfo dfProductInfo,SysUser sysUser,boolean isAnonymous) {
        String reviewStatus = sysUser.getReviewStatus();
        if ("1".equals(reviewStatus)) {
            return null;
        }
        LambdaQueryWrapper<DfProductInfo> queryWrapper = new LambdaQueryWrapper();
        if (Validator.isEmpty(dfProductInfo.getOrderByColumn())) {
            queryWrapper.last("ORDER BY CASE WHEN serial_number IS NULL THEN 1 ELSE 0 END, serial_number ASC");
        }
        condition(queryWrapper,dfProductInfo);
        String brokerIds = dfProductInfo.getBrokerIds();
        if ("1".equals(dfProductInfo.getSelectByBroker())) {
            if (Validator.isNotEmpty(dfProductInfo.getUserId())) {
                if ("1".equals(dfProductInfo.getIsSelectBroker())) {
                    String userId = dfProductInfo.getUserId();
                    List<Long> productIdsByBrokerIdByUserId = dfBrokerService.getProductIdsByBrokerIdByUserId(Long.valueOf(userId));
                    if (productIdsByBrokerIdByUserId == null || productIdsByBrokerIdByUserId.isEmpty()) {
                        productIdsByBrokerIdByUserId.add(0L);
                    }
                    queryWrapper.in(DfProductInfo::getId,productIdsByBrokerIdByUserId);
                } else {
                    String userId = dfProductInfo.getUserId();
                    List<Long> productIdsByBrokerIdByUserId = dfBrokerService.getProductIdsByBrokerIdByUserId(Long.valueOf(userId));
                    if (productIdsByBrokerIdByUserId == null || productIdsByBrokerIdByUserId.isEmpty()) {
                        productIdsByBrokerIdByUserId.add(0L);
                    }
                    if ("1".equals(dfProductInfo.getIsRecommend())) {
                        queryWrapper.and(wrapper ->
                                wrapper.in(DfProductInfo::getId, productIdsByBrokerIdByUserId)
                                        .or()
                                        .inSql(DfProductInfo::getId, "select product_id from df_broker_product where user_id in (" + dfProductInfo.getUserId() + ") and del_flag = '0' and staus = '1'")
                        );

                        queryWrapper.inSql(DfProductInfo::getId,"select product_id from df_product_recommend where user_id in (" + userId + ") and del_flag = '0'");
                    } else {
                        queryWrapper.inSql(DfProductInfo::getId,"select product_id from df_broker_product where user_id in (" + userId + ") and del_flag = '0' and staus = '1'");
                    }
                }
            } else {
                queryWrapper.inSql(DfProductInfo::getId,"select product_id from df_broker_product where broker_id in (" + brokerIds + ") and del_flag = '0' and staus = '1'");
            }
        }
        if (!SecurityUtils.isAdmin(sysUser.getUserId())) {
            if (!sysUser.getDeptId().equals(-1L)) {
                if (isAnonymous) {
                    List<Long> productIdsByBrokerId = dfBrokerService.getProductIdsByBrokerIdByUserId(sysUser.getUserId());
                    if (productIdsByBrokerId.size() == 0) {
                        productIdsByBrokerId.add(0L);
                    }
                    if (!"1".equals(dfProductInfo.getSelectByBroker())) {
                        queryWrapper.in(DfProductInfo::getId, productIdsByBrokerId)
                                .or()
                                .in(DfProductInfo::getCreateDept, SecurityUtils.getDeptId());
                    }
                } else {
                    List<Long> productIdsByBrokerId = dfBrokerService.getProductIdsByBrokerId();
                    if (productIdsByBrokerId.size() == 0) {
                        productIdsByBrokerId.add(0L);
                    }
                    if (!"1".equals(dfProductInfo.getSelectByBroker())) {
                        queryWrapper.in(DfProductInfo::getId, productIdsByBrokerId)
                                .or()
                                .in(DfProductInfo::getCreateDept, SecurityUtils.getDeptId());
                    }
                }
            }
        }
        startPage();
        List<DfProductInfo> list = dfProductInfoService.list(queryWrapper);
        List<DfOrder> dfOrders = dfOrderService.list();
        Map<Long, Integer> productOrderCounts = new HashMap<>();
        // 计算申请人数
        for (DfOrder order : dfOrders) {
            if (!productOrderCounts.containsKey(order.getProductId())) {
                productOrderCounts.put(order.getProductId(), 1000); // 从1000开始计数
            } else {
                productOrderCounts.put(order.getProductId(), productOrderCounts.get(order.getProductId()) + 1);
            }
        }
        for (DfProductInfo productInfo : list) {
            Long productId = productInfo.getId();
            if (productOrderCounts.containsKey(productId)) {
                productInfo.setApplicantNum(Long.valueOf(productOrderCounts.get(productId)));
            } else {
                productInfo.setApplicantNum(1000L);
            }
        }
        //城市名称
        Map<String, String> cityMap = new HashMap<>();
        List<DfArea> allCities = dfAreaService.list();
        for (DfArea city : allCities) {
            cityMap.put(city.getAreaId(), city.getName());
        }
        DfBroker byId = null;
        SysUser userInfo = null;
        if ("1".equals(dfProductInfo.getSelectByBroker())) {
            if (Validator.isNotEmpty(dfProductInfo.getUserId())) {
                userInfo = sysUserMapper.selectById(dfProductInfo.getUserId());
            } else {
                byId = dfBrokerService.getById(brokerIds);
            }
        }
        for (DfProductInfo productInfo : list) {
            productInfo.setInterestRate(productInfo.getInterestRateBegin() + "%-" + productInfo.getInterestRateEnd() + "%");
            productInfo.setProductIntro(HtmlUtils.stripHtmlTags(productInfo.getProductIntro()));
            productInfo.setProductDetail(HtmlUtils.stripHtmlTags(productInfo.getProductDetail()));
            String businessCity = productInfo.getBusinessCity();
            if (Validator.isNotEmpty(businessCity)) {
                String[] cityIds = businessCity.split(",");
                StringBuilder translatedCities = new StringBuilder();
                for (String cityId : cityIds) {
                    String cityName = cityMap.get(cityId);
                    if (cityName != null) {
                        translatedCities.append(cityName).append(",");
                    }
                }
                if (translatedCities.length() > 0) {
                    translatedCities.deleteCharAt(translatedCities.length() - 1);
                }
                productInfo.setBusinessCity(translatedCities.toString());
            }
            if ("1".equals(dfProductInfo.getSelectByBroker())) {
                if (Validator.isNotEmpty(dfProductInfo.getUserId())) {
                    if ("1".equals(dfProductInfo.getIsSelectBroker())) {
                        Long deptId = userInfo.getDeptId();
                        DfBroker byIdNew = dfBrokerService.getById(deptId);
                        productInfo.setBrokerName(byIdNew.getBrokerName());
                    } else {
                        productInfo.setBrokerName(userInfo.getUserName());
                    }
                } else {
                    productInfo.setBrokerName(byId.getBrokerName());
                }
            }
        }
        return list;

    }

    /**
     * 查询产品信息列表
     */
    @ApiOperation("查询产品信息列表")
    @GetMapping("/list")
    public AjaxResult list(DfProductInfo dfProductInfo) {
        LambdaQueryWrapper<DfProductInfo> queryWrapper = new LambdaQueryWrapper();
        if ("1".equals(dfProductInfo.getSelectByBroker())) {
            queryWrapper.notInSql(DfProductInfo::getId,"select product_id from df_broker_product where del_flag = '0'")
                    .or()
                    .eq(DfProductInfo::getId,dfProductInfo.getId());
        }
        condition(queryWrapper,dfProductInfo);
        List<DfProductInfo> list = dfProductInfoService.list(queryWrapper);
        return success(list);
    }

    /**
     * 根据userId查询产品信息列表
     */
    @ApiOperation("根据userId查询产品信息列表")
    @GetMapping("/listByUserId")
    public AjaxResult listByUserId(DfProductInfo dfProductInfo) {
        LambdaQueryWrapper<DfProductInfo> queryWrapper = new LambdaQueryWrapper();
        List<Long> productIdsByBrokerIdByUserId = dfBrokerService.getProductIdsByBrokerIdByUserId(Long.valueOf(dfProductInfo.getUserId()));
        queryWrapper.notInSql(DfProductInfo::getId,
                "select product_id from df_broker_product where del_flag = '0' and user_id = " + dfProductInfo.getUserId() + "")
                .eq(DfProductInfo::getStatus, "1")
                .or()
                .eq(DfProductInfo::getId,dfProductInfo.getId())
                .eq(DfProductInfo::getStatus, "1");
        condition(queryWrapper,dfProductInfo);
        List<DfProductInfo> list = dfProductInfoService.list(queryWrapper);
        Set<Long> idsToRemove = productIdsByBrokerIdByUserId.stream().collect(Collectors.toSet());
        List<DfProductInfo> filteredList = list.stream()
                .filter(product -> !idsToRemove.contains(product.getId()))
                .collect(Collectors.toList());
        return success(filteredList);
    }

    /**
     * 根据userId查询产品信息列表
     */
    @ApiOperation("根据userId查询产品信息列表")
    @GetMapping("/listByRecommend")
    public AjaxResult listByRecommend(DfProductInfo dfProductInfo) {
        List<DfProductRecommend> dfProductRecommends = dfProductRecommendService.list(new LambdaQueryWrapper<DfProductRecommend>().eq(DfProductRecommend::getUserId, dfProductInfo.getUserId()));
        List<Long> recommendProductIds = dfProductRecommends.stream()
                .map(DfProductRecommend::getProductId)  // 提取 String 类型的 productId
                .map(Long::parseLong)  // 将 String 转换为 Long
                .collect(Collectors.toList());  // 收集为 List<Long>
        recommendProductIds.add(0L);
        List<Long> brokerProductIds = dfBrokerService.getProductIdsByBrokerIdByUserId(Long.valueOf(dfProductInfo.getUserId()));
        List<Long> productIdsByBrokerIdByUserId = dfBrokerService.getProductIdsByBrokerIdByUserId(Long.valueOf(dfProductInfo.getUserId()));
        if (productIdsByBrokerIdByUserId.isEmpty()) {
            productIdsByBrokerIdByUserId.add(0L); // 添加默认值避免空集合错误
        }
        Set<Long> allProductIds = new HashSet<>();
        allProductIds.addAll(recommendProductIds);
        allProductIds.addAll(brokerProductIds);
        allProductIds.addAll(productIdsByBrokerIdByUserId);
        allProductIds.add(0L);
        LambdaQueryWrapper<DfProductInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.notIn(DfProductInfo::getId, recommendProductIds)  // 排除推荐的产品
                .in(DfProductInfo::getId, allProductIds)             // 包含经纪人产品和broker产品
                .or()
                .eq(DfProductInfo::getId, dfProductInfo.getId());     // 或者直接匹配当前产品ID

        condition(queryWrapper, dfProductInfo);
        List<DfProductInfo> list = dfProductInfoService.list(queryWrapper);
        return success(list);
    }


    /**
     * 根据代理商经纪id查询产品信息列表
     */
    @ApiOperation("根据代理商经纪id查询产品信息列表")
    @GetMapping("/listByBroker")
    public AjaxResult listByBroker(DfProductInfo dfProductInfo) {
//        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<DfProductInfo> queryWrapper = new LambdaQueryWrapper();
        DfBroker broker = dfBrokerService.getById(dfProductInfo.getBrokerId());
        if (Validator.isEmpty(broker.getParentId())) {
            List<DfBrokerProduct> listBrokerProduct = dfBrokerProductService.list(new LambdaQueryWrapper<DfBrokerProduct>()
                    .eq(DfBrokerProduct::getBrokerId, broker.getId())
                    .eq(DfBrokerProduct::getStaus, "1"));
            List<Long> productIds = listBrokerProduct.stream()
                    .map(DfBrokerProduct::getProductId)
                    .collect(Collectors.toList());
            productIds.removeIf(id -> Objects.equals(id, dfProductInfo.getId()));
//            productIds.removeIf(id -> id.equals(dfProductInfo.getId()));
            if (null != productIds && productIds.size() == 0) {
                productIds.add(0L);
            }
            queryWrapper.notIn(DfProductInfo::getId, productIds);
        } else {
            List<DfBrokerProduct> listBrokerProduct = dfBrokerProductService.list(new LambdaQueryWrapper<DfBrokerProduct>()
                    .eq(DfBrokerProduct::getBrokerId, broker.getParentId())
                    .eq(DfBrokerProduct::getStaus, "1"));
            List<Long> productIds = listBrokerProduct.stream()
                    .map(DfBrokerProduct::getProductId)
                    .collect(Collectors.toList());
            if (null != productIds && productIds.size() == 0) {
                productIds.add(0L);
            }
            queryWrapper.in(DfProductInfo::getId, productIds);
            List<DfBrokerProduct> listProduct = dfBrokerProductService.list(new LambdaQueryWrapper<DfBrokerProduct>()
                    .eq(DfBrokerProduct::getBrokerId, broker.getId())
                    .eq(DfBrokerProduct::getStaus, "1"));
            List<Long> productIdsNew = listProduct.stream()
                    .map(DfBrokerProduct::getProductId)
                    .collect(Collectors.toList());
            productIdsNew.removeIf(id -> id.equals(dfProductInfo.getId()));
            if (null != productIdsNew && productIdsNew.size() == 0) {
                productIdsNew.add(0L);
            }
            queryWrapper.notIn(DfProductInfo::getId, productIdsNew);
        }
        queryWrapper.eq(DfProductInfo::getStatus, "1");
        condition(queryWrapper,dfProductInfo);
        List<DfProductInfo> list = dfProductInfoService.list(queryWrapper);
        return success(list);
    }

    /**
     * 导出产品信息列表
     */
    @ApiOperation("导出产品信息列表")
    @Log(title = "产品信息导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DfProductInfo dfProductInfo) {
        Map<String, String> cityMap = new HashMap<>();
        List<DfArea> allCities = dfAreaService.list();
        for (DfArea city : allCities) {
            cityMap.put(city.getAreaId(), city.getName());
        }
        Map<Long, String> brokerProductMap = new HashMap<>();
        List<DfBroker> listBroker = dfBrokerService.list();
        Map<Long, String> brokerMap = new HashMap<>();
        for (DfBroker broker : listBroker) {
            brokerMap.put(broker.getId(), broker.getBrokerName());
        }
        List<DfBrokerProduct> listBrokerProduct = dfBrokerProductService.list();
        for (DfBrokerProduct brokerProduct : listBrokerProduct) {
            String brokerName = brokerMap.get(brokerProduct.getBrokerId());
            brokerProduct.setBrokerName(brokerName);
        }
        for (DfBrokerProduct brokerProduct : listBrokerProduct) {
            brokerProductMap.put(brokerProduct.getProductId(), brokerProduct.getBrokerName());
        }
        LambdaQueryWrapper<DfProductInfo> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,dfProductInfo);
        List<DfProductInfo> list = dfProductInfoService.list(queryWrapper);
        for (DfProductInfo productInfo : list) {
            productInfo.setInterestRate(productInfo.getInterestRateBegin() + "%-" + productInfo.getInterestRateEnd() + "%");
            productInfo.setProductIntro(HtmlUtils.stripHtmlTags(productInfo.getProductIntro()));
            productInfo.setProductDetail(HtmlUtils.stripHtmlTags(productInfo.getProductDetail()));
            String businessCity = productInfo.getBusinessCity(); // 获取原始的城市ID字符串
            if (Validator.isNotEmpty(businessCity)) {
                String[] cityIds = businessCity.split(","); // 按逗号分割城市ID
                StringBuilder translatedCities = new StringBuilder();
                for (String cityId : cityIds) {
                    String cityName = cityMap.get(cityId); // 从 Map 中获取城市名称
                    if (cityName != null) {
                        translatedCities.append(cityName).append(",");
                    }
                }
                if (translatedCities.length() > 0) {
                    translatedCities.deleteCharAt(translatedCities.length() - 1);
                }
                productInfo.setBusinessCity(translatedCities.toString());
                productInfo.setBrokerName(brokerProductMap.get(productInfo.getId()));
            }
        }
        ExcelUtil<DfProductInfo> util = new ExcelUtil<DfProductInfo>(DfProductInfo. class);
        util.exportExcel(response, list, "产品信息数据");
    }

    /**
     * 获取产品信息详细信息
     */
    @ApiOperation("获取产品信息详细信息")
    @GetMapping(value = "/{id}")
    @Anonymous
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        Boolean isUser = true;
        try {
            LoginUser loginUser = getLoginUser();
        } catch (Exception e) {
            isUser = false;
            // 捕获所有异常
            e.printStackTrace(); // 或者记录日志等处理方式
        }
        DfProductInfo byId = dfProductInfoService.getById(id);
        byId.setInterestRate(byId.getInterestRateBegin() + "%-" + byId.getInterestRateEnd() + "%");
        List<DfBrokerProduct> list = dfBrokerProductService.list(new LambdaQueryWrapper<DfBrokerProduct>().eq(DfBrokerProduct::getProductId, id));
        List<DfOrder> dfOrders = dfOrderService.list();
        Map<Long, Integer> productOrderCounts = new HashMap<>();
        // 计算申请人数
        for (DfOrder order : dfOrders) {
            if (!productOrderCounts.containsKey(order.getProductId())) {
                productOrderCounts.put(order.getProductId(), 1);
            } else {
                productOrderCounts.put(order.getProductId(), productOrderCounts.get(order.getProductId()) + 1);
            }
        }
        Long productId = byId.getId();
        if (productOrderCounts.containsKey(productId)) {
            byId.setApplicantNum(Long.valueOf(productOrderCounts.get(productId)));
        } else {
            byId.setApplicantNum(0L);
        }
        if (list.size() > 0 && list != null) {
            byId.setBrokerId(list.get(0).getBrokerId());
        }
        if (isUser == false) {
            byId.setProductDetail(null);
        } else {
            if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
                List<Long> productIdsByBrokerId = dfBrokerService.getProductIdsByBrokerId();
                if (!productIdsByBrokerId.contains(id)) {
                    byId.setProductDetail(null);
                }
                SysUser sysUser = sysUserMapper.selectById(getUserId());
                String reviewStatus = sysUser.getReviewStatus();
                if ("1".equals(reviewStatus)) {
                    byId.setProductDetail(null);
                }
            }
        }
        String businessCity = byId.getBusinessCity();
        if (Validator.isEmpty(businessCity)) {
            return success(byId);
        }
        List<String> businessCityList = Arrays.asList(businessCity.split(","));
        List<DfArea> douAreas = dfAreaService.listByIds(businessCityList);
        String concatenatedNames = douAreas.stream()
                .map(DfArea::getName)
                .collect(Collectors.joining(","));
        byId.setBusinessCityByName(concatenatedNames);


        return success(byId);
    }

    /**
     * 根据经纪人获取产品信息详细信息
     */
    @ApiOperation("根据经纪人获取产品信息详细信息")
    @GetMapping(value = "/getInfoByUserId/{id}")
    @Anonymous
    public AjaxResult getInfoByUserId(@PathVariable("id") Long id) {
        List<Long> productIdsByBrokerIdByUserId = dfBrokerService.getProductIdsByBrokerIdByUserId(id);
        if (productIdsByBrokerIdByUserId.size() == 0) {
            return success(null);
        }
        List<DfProductInfo> list = dfProductInfoService.list(new LambdaQueryWrapper<DfProductInfo>().in(DfProductInfo::getId, productIdsByBrokerIdByUserId));
        for (DfProductInfo productInfo : list) {
            productInfo.setProductDetail(null);
        }
        List<DfOrder> dfOrders = dfOrderService.list();
        Map<Long, Integer> productOrderCounts = new HashMap<>();
        // 计算申请人数
        for (DfOrder order : dfOrders) {
            if (!productOrderCounts.containsKey(order.getProductId())) {
                productOrderCounts.put(order.getProductId(), 1);
            } else {
                productOrderCounts.put(order.getProductId(), productOrderCounts.get(order.getProductId()) + 1);
            }
        }
        for (DfProductInfo productInfo : list) {
            productInfo.setInterestRate(productInfo.getInterestRateBegin() + "%-" + productInfo.getInterestRateEnd() + "%");
            Long productId = productInfo.getId();
            if (productOrderCounts.containsKey(productId)) {
                productInfo.setApplicantNum(Long.valueOf(productOrderCounts.get(productId)));
            } else {
                productInfo.setApplicantNum(0L);
            }
        }
        return success(list);
    }

    /**
     * 根据代理商获取产品信息详细信息
     */
    @ApiOperation("根据代理商获取产品信息详细信息")
    @PutMapping(value = "/getInfoByBroker")
    @Anonymous
    public AjaxResult getInfoByBroker(@RequestBody DfProductInfo dfProductInfo) {
        if(Validator.isNotEmpty(dfProductInfo.getBrokerId())) {
            DfProductInfo byId = dfProductInfoService.getById(dfProductInfo.getId());
            List<DfBrokerProduct> list = dfBrokerProductService.list(new LambdaQueryWrapper<DfBrokerProduct>()
                    .eq(DfBrokerProduct::getBrokerId, dfProductInfo.getBrokerId())
                    .eq(DfBrokerProduct::getProductId, dfProductInfo.getId()));
            if (list.size() > 0 && list != null) {
                byId.setBrokerId(list.get(0).getBrokerId());
            }
            String businessCity = byId.getBusinessCity();
            if (Validator.isEmpty(businessCity)) {
                return success(byId);
            }
            List<String> businessCityList = Arrays.asList(businessCity.split(","));
            List<DfArea> douAreas = dfAreaService.listByIds(businessCityList);
            String concatenatedNames = douAreas.stream()
                    .map(DfArea::getName)
                    .collect(Collectors.joining(","));
            byId.setBusinessCityByName(concatenatedNames);
            return success(byId);
        } else {
            DfProductInfo byId = dfProductInfoService.getById(dfProductInfo.getId());
            List<DfBrokerProduct> list = dfBrokerProductService.list(new LambdaQueryWrapper<DfBrokerProduct>()
                    .eq(DfBrokerProduct::getUserId, dfProductInfo.getUserId())
                    .eq(DfBrokerProduct::getProductId, dfProductInfo.getId()));
            if (list.size() > 0 && list != null) {
                byId.setUserId(list.get(0).getUserId());
            }
            String businessCity = byId.getBusinessCity();
            if (Validator.isEmpty(businessCity)) {
                return success(byId);
            }
            List<String> businessCityList = Arrays.asList(businessCity.split(","));
            List<DfArea> douAreas = dfAreaService.listByIds(businessCityList);
            String concatenatedNames = douAreas.stream()
                    .map(DfArea::getName)
                    .collect(Collectors.joining(","));
            byId.setBusinessCityByName(concatenatedNames);
            return success(byId);
        }

    }

    /**
     * 新增产品信息
     */
    @ApiOperation("新增产品信息")
    @Log(title = "产品信息新增", businessType = BusinessType.INSERT)
    @PostMapping
    @Anonymous
    public AjaxResult add(@RequestBody DfProductInfo dfProductInfo) {
        return toAjax(dfProductInfoService.save(dfProductInfo));
    }

    /**
     * 修改产品信息
     */
    @ApiOperation("修改产品信息")
    @Log(title = "产品信息修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DfProductInfo dfProductInfo) {
        return toAjax(dfProductInfoService.updateById(dfProductInfo));
    }



    /**
     * 删除产品信息
     */
    @ApiOperation("删除产品信息")
    @Log(title = "产品信息删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        List<DfProductPoster> list = dfProductPosterService.list(new LambdaQueryWrapper<DfProductPoster>().in(DfProductPoster::getProductId, ids));
        List<DfProductInfo> infos = dfProductInfoService.list(new LambdaQueryWrapper<DfProductInfo>().in(DfProductInfo::getId, ids));
        for (DfProductInfo dfProductInfo : infos) {
            if ("1".equals(dfProductInfo.getStatus())) {
                return AjaxResult.warn("该产品已经上架，请先下架再删除");
            }
        }
        if(list.size() > 0){
            return AjaxResult.warn("该产品下有海报，请先删除海报");
        }

        return toAjax(dfProductInfoService.removeBatchByIds(ids));
    }

    /**
     * 修改产品状态
     */
    @ApiOperation("修改产品状态")
    @Log(title = "修改产品状态", businessType = BusinessType.DELETE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody DfProductInfo dfProductInfo) {
        Long[] ids = dfProductInfo.getIds();
        String status = dfProductInfo.getStatus();
        List<DfProductInfo> dfProductInfos = new ArrayList<>();
        for (Long id : ids) {
            DfProductInfo dfProductInfoNew = new DfProductInfo();
            dfProductInfoNew.setId(id);
            dfProductInfoNew.setStatus(status);
            dfProductInfos.add(dfProductInfoNew);
        }
        if ("0".equals(status)) {
            List<DfBrokerProduct> list = dfBrokerProductService.list(new LambdaQueryWrapper<DfBrokerProduct>().in(DfBrokerProduct::getProductId, ids));
            for (DfBrokerProduct dfBrokerProduct : list) {
                dfBrokerProduct.setStaus("0");
            }
            dfBrokerProductService.updateBatchById(list);
        }
        if ("1".equals(dfProductInfo.getIsBroker())) {
            if ("1".equals(status)) {
                List<DfBrokerProduct> list = dfBrokerProductService.list(new LambdaQueryWrapper<DfBrokerProduct>().in(DfBrokerProduct::getProductId, ids));
                for (DfBrokerProduct dfBrokerProduct : list) {
                    dfBrokerProduct.setStaus("1");
                }
                dfBrokerProductService.updateBatchById(list);
            }
        }
        return toAjax(dfProductInfoService.updateBatchById(dfProductInfos));
    }

    /**
     * 获取产品相关代理商数量
     */
    @ApiOperation("获取产品相关代理商数量")
    @GetMapping(value = "/getBrokerNum/{ids}")
    public AjaxResult getBrokerNum(@PathVariable("ids") List<Long> ids) {
        List<DfBrokerProduct> list = dfBrokerProductService.list(new LambdaQueryWrapper<DfBrokerProduct>().in(DfBrokerProduct::getProductId, ids));
        list.size();
        return success(list.size());
    }


    /**
     * 修改代理产品权限
     */
    @ApiOperation("修改代理产品权限")
    @Log(title = "代理产品权限修改", businessType = BusinessType.UPDATE)
    @PutMapping("/editByBroker")
    public AjaxResult editByBroker(@RequestBody DfProductInfo dfProductInfo) {
        Long productInfoId = dfProductInfo.getId();
        Long brokerId = dfProductInfo.getBrokerId();
        List<DfBrokerProduct> list = dfBrokerProductService.list(new LambdaQueryWrapper<DfBrokerProduct>().eq(DfBrokerProduct::getProductId, productInfoId)
                                                                .eq(DfBrokerProduct::getBrokerId, brokerId));
        if (list != null && list.size() > 0) {
            DfBrokerProduct dfBrokerProduct = new DfBrokerProduct().setBrokerId(brokerId).setProductId(productInfoId).setId(list.get(0).getId());
            dfBrokerProduct.setStaus("1");
            return toAjax(dfBrokerProductService.updateById(dfBrokerProduct));
        } else {
            DfBrokerProduct dfBrokerProduct = new DfBrokerProduct().setBrokerId(brokerId).setProductId(productInfoId);
            dfBrokerProduct.setStaus("1");
            return toAjax(dfBrokerProductService.save(dfBrokerProduct));
        }
    }

    /**
     * 修改代理产品权限
     */
    @ApiOperation("修改代理产品权限")
    @Log(title = "代理产品权限修改", businessType = BusinessType.UPDATE)
    @PutMapping("/editByBrokers")
    public AjaxResult editByBrokers(@RequestBody DfProductInfo dfProductInfo) {
        for (Long id : dfProductInfo.getIds()) {
            if (Validator.isNotEmpty(dfProductInfo.getUserId())) {
                Long productInfoId = id;
                String userId = dfProductInfo.getUserId();
                List<DfBrokerProduct> list = dfBrokerProductService.list(new LambdaQueryWrapper<DfBrokerProduct>()
                        .eq(DfBrokerProduct::getProductId, productInfoId)
                        .eq(DfBrokerProduct::getBrokerId, userId));
                if (list != null && list.size() > 0) {
                    DfBrokerProduct dfBrokerProduct = new DfBrokerProduct().setUserId(userId).setProductId(productInfoId).setId(list.get(0).getId());
                    dfBrokerProduct.setStaus("1");
                    dfBrokerProductService.updateById(dfBrokerProduct);
                } else {
                    DfBrokerProduct dfBrokerProduct = new DfBrokerProduct().setUserId(userId).setProductId(productInfoId);
                    dfBrokerProduct.setStaus("1");
                    dfBrokerProductService.save(dfBrokerProduct);
                }
            } else {
                Long productInfoId = id;
                Long brokerId = dfProductInfo.getBrokerId();
                List<DfBrokerProduct> list = dfBrokerProductService.list(new LambdaQueryWrapper<DfBrokerProduct>()
                        .eq(DfBrokerProduct::getProductId, productInfoId)
                        .eq(DfBrokerProduct::getBrokerId, brokerId));
                if (list != null && list.size() > 0) {
                    DfBrokerProduct dfBrokerProduct = new DfBrokerProduct().setBrokerId(brokerId).setProductId(productInfoId).setId(list.get(0).getId());
                    dfBrokerProduct.setStaus("1");
                    dfBrokerProductService.updateById(dfBrokerProduct);
                } else {
                    DfBrokerProduct dfBrokerProduct = new DfBrokerProduct().setBrokerId(brokerId).setProductId(productInfoId);
                    dfBrokerProduct.setStaus("1");
                    dfBrokerProductService.save(dfBrokerProduct);
                }
            }
        }
        return toAjax(true);
    }

    /**
     * 移除代理产品权限
     */
    @ApiOperation("移除代理产品权限")
    @Log(title = "代理产品权限移除", businessType = BusinessType.DELETE)
    @PutMapping("/removeByBroker")
    public AjaxResult removeByBroker(@RequestBody DfProductInfo dfProductInfo) {
        Long[] ids = dfProductInfo.getIds();
        Long brokerId = dfProductInfo.getBrokerId();
        if (Validator.isNotEmpty(dfProductInfo.getUserId())) {
            boolean remove = dfBrokerProductService.remove(new LambdaQueryWrapper<DfBrokerProduct>()
                    .in(DfBrokerProduct::getProductId, ids)
                    .in(DfBrokerProduct::getUserId, dfProductInfo.getUserId()));
            return toAjax(remove);
        } else {
            List<DfBroker> allSubordinates = dfBrokerService.findAllSubordinates(brokerId);
            List<Long> brokerIds = allSubordinates.stream()
                    .map(DfBroker::getId)
                    .collect(Collectors.toList());
            brokerIds.add(brokerId);
            boolean remove = dfBrokerProductService.remove(new LambdaQueryWrapper<DfBrokerProduct>()
                    .in(DfBrokerProduct::getProductId, ids)
                    .in(DfBrokerProduct::getBrokerId, brokerIds));
            return toAjax(remove);
        }
    }


    /**
      * 条件设置
      */
    private void condition (LambdaQueryWrapper<DfProductInfo> queryWrapper,DfProductInfo dfProductInfo){


        //产品id
        if(Validator.isNotEmpty(dfProductInfo.getId())){
            queryWrapper.eq(DfProductInfo::getId,dfProductInfo.getId());
        }

        //产品名称
        if(Validator.isNotEmpty(dfProductInfo.getProductName())){
            queryWrapper.like(DfProductInfo::getProductName,dfProductInfo.getProductName());
        }

        //产品简称
        if(Validator.isNotEmpty(dfProductInfo.getSimpleName())){
            queryWrapper.like(DfProductInfo::getSimpleName,dfProductInfo.getSimpleName());
        }

        //产品类型
        if(Validator.isNotEmpty(dfProductInfo.getProductType())){
            queryWrapper.eq(DfProductInfo::getProductType,dfProductInfo.getProductType());
        }

        //产品细类
        if(Validator.isNotEmpty(dfProductInfo.getProductSubtype())){
            queryWrapper.eq(DfProductInfo::getProductSubtype,dfProductInfo.getProductSubtype());
        }

        //最高额度（元）
        if(Validator.isNotEmpty(dfProductInfo.getMaxAmount())){
            queryWrapper.eq(DfProductInfo::getMaxAmount,dfProductInfo.getMaxAmount());
        }

        if(Validator.isNotEmpty(dfProductInfo.getMaxAmountBegin())){
            queryWrapper.ge(DfProductInfo::getMaxAmount,dfProductInfo.getMaxAmountBegin());
        }

        if(Validator.isNotEmpty(dfProductInfo.getMaxAmountEnd())){
            queryWrapper.le(DfProductInfo::getMaxAmount,dfProductInfo.getMaxAmountEnd());
        }

        //年利率（单利）
        if(Validator.isNotEmpty(dfProductInfo.getInterestRateBegin())){
            queryWrapper.ge(DfProductInfo::getInterestRateBegin,dfProductInfo.getInterestRateBegin());
        }

        if(Validator.isNotEmpty(dfProductInfo.getInterestRateEnd())){
            queryWrapper.le(DfProductInfo::getInterestRateEnd,dfProductInfo.getInterestRateEnd());
        }

        //产品简介
        if(Validator.isNotEmpty(dfProductInfo.getProductIntro())){
            queryWrapper.eq(DfProductInfo::getProductIntro,dfProductInfo.getProductIntro());
        }

        //产品详情（富文本）
        if(Validator.isNotEmpty(dfProductInfo.getProductDetail())){
            queryWrapper.eq(DfProductInfo::getProductDetail,dfProductInfo.getProductDetail());
        }

        //上架时间起
        if(Validator.isNotEmpty(dfProductInfo.getListBegin())){
            queryWrapper.ge(DfProductInfo::getListBegin,dfProductInfo.getListBegin());
        }

        //上架时间止
        if(Validator.isNotEmpty(dfProductInfo.getListEnd())){
            queryWrapper.le(DfProductInfo::getListEnd,dfProductInfo.getListEnd());
        }

        if(Validator.isNotEmpty(dfProductInfo.getParams().get("beginTime"))){
            queryWrapper.ge(DfProductInfo::getListBegin,dfProductInfo.getParams().get("beginTime"));
        }

        if(Validator.isNotEmpty(dfProductInfo.getParams().get("endTime"))){
            queryWrapper.le(DfProductInfo::getListEnd,dfProductInfo.getParams().get("endTime"));
        }

        //还款周期
        if(Validator.isNotEmpty(dfProductInfo.getRepaymentCycle())){
            queryWrapper.eq(DfProductInfo::getRepaymentCycle,dfProductInfo.getRepaymentCycle());
        }

        //还款方式
        if(Validator.isNotEmpty(dfProductInfo.getRepaymentMethod())){
            queryWrapper.eq(DfProductInfo::getRepaymentMethod,dfProductInfo.getRepaymentMethod());
        }

        //展业城市
        if(Validator.isNotEmpty(dfProductInfo.getBusinessCity())){
            queryWrapper.eq(DfProductInfo::getBusinessCity,dfProductInfo.getBusinessCity());
        }

        //综合费率
        if(Validator.isNotEmpty(dfProductInfo.getCombinedRates())){
            queryWrapper.eq(DfProductInfo::getCombinedRates,dfProductInfo.getCombinedRates());
        }

        //状态0草稿1上架
        if(Validator.isNotEmpty(dfProductInfo.getStatus())){
            queryWrapper.eq(DfProductInfo::getStatus,dfProductInfo.getStatus());
        }

        //备注
        if(Validator.isNotEmpty(dfProductInfo.getRemark())){
            queryWrapper.eq(DfProductInfo::getRemark,dfProductInfo.getRemark());
        }

        //创建部门
        if(Validator.isNotEmpty(dfProductInfo.getCreateDept())){
            queryWrapper.eq(DfProductInfo::getCreateDept,dfProductInfo.getCreateDept());
        }

        //创建人员
        if(Validator.isNotEmpty(dfProductInfo.getCreateBy())){
            queryWrapper.eq(DfProductInfo::getCreateBy,dfProductInfo.getCreateBy());
        }

        //创建时间
        if(Validator.isNotEmpty(dfProductInfo.getCreateTime())){
            queryWrapper.eq(DfProductInfo::getCreateTime,dfProductInfo.getCreateTime());
        }

        //修改人员
        if(Validator.isNotEmpty(dfProductInfo.getUpdateBy())){
            queryWrapper.eq(DfProductInfo::getUpdateBy,dfProductInfo.getUpdateBy());
        }

        //修改时间
        if(Validator.isNotEmpty(dfProductInfo.getUpdateTime())){
            queryWrapper.eq(DfProductInfo::getUpdateTime,dfProductInfo.getUpdateTime());
        }

        //删除标志（0代表存在 2代表删除）
        if(Validator.isNotEmpty(dfProductInfo.getDelFlag())){
            queryWrapper.eq(DfProductInfo::getDelFlag,dfProductInfo.getDelFlag());
        }

        //租户id
        if(Validator.isNotEmpty(dfProductInfo.getTenantId())){
            queryWrapper.eq(DfProductInfo::getTenantId,dfProductInfo.getTenantId());
        }

        }

}
