package com.bs.df.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.bs.common.core.domain.entity.SysUser;
import com.bs.common.utils.SecurityUtils;
import com.bs.df.domain.DfProductPoster;
import com.bs.df.mapper.DfBrokerMapper;
import com.bs.df.utils.HtmlUtils;
import com.bs.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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 com.bs.df.domain.DfBroker;
import com.bs.df.service.IDfBrokerService;
import javax.annotation.Resource;

/**
 * 代理商经纪Controller
 *
 * @author bs
 * @date 2024-04-06
 */
@Api(tags = "代理商经纪")
@RestController
@RequestMapping("/broker/broker")
public class DfBrokerController extends BaseController {
    @Resource
    private IDfBrokerService dfBrokerService;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private DfBrokerMapper dfBrokerMapper;

    /**
     * 分页查询代理商经纪列表
     */
    @ApiOperation("分页查询代理商经纪列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(DfBroker dfBroker) {
        // startPage();
        LambdaQueryWrapper<DfBroker> queryWrapper = new LambdaQueryWrapper();
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            List<Long> longs = dfBrokerService.filterByUser();
            queryWrapper.in(DfBroker::getId, longs);
        }
        queryWrapper.orderByAsc(DfBroker::getOrderNum);
        condition(queryWrapper,dfBroker);
        List<DfBroker> list = dfBrokerService.list(queryWrapper);
        for (DfBroker broker : list) {
            broker.setBrokerDesc(HtmlUtils.stripHtmlTags(broker.getBrokerDesc()));
        }
//        List<DfBroker> treeList = buildTree(list);
        return getDataTable(list);
    }

    public List<DfBroker> buildTree(List<DfBroker> list) {
        List<DfBroker> treeList = new ArrayList<>();
        Map<Long, DfBroker> brokerMap = new HashMap<>();
        // 遍历列表，将每个节点添加到 Map 中
        for (DfBroker broker : list) {
            brokerMap.put(broker.getId(), broker);
        }
        // 构建树形结构
        for (DfBroker broker : list) {
            if (broker.getParentId() == null) {
                treeList.add(findChildren(broker, brokerMap));
            }
        }
        return treeList;
    }

    private DfBroker findChildren(DfBroker parent, Map<Long, DfBroker> brokerMap) {
        for (DfBroker broker : brokerMap.values()) {
            if (parent.getId().equals(broker.getParentId())) {
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(findChildren(broker, brokerMap));
            }
        }
        return parent;
    }




    /**
     * 查询代理商经纪列表
     */
    @ApiOperation("查询代理商经纪列表")
    @GetMapping("/list")
    public AjaxResult list(DfBroker dfBroker) {
        LambdaQueryWrapper<DfBroker> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,dfBroker);
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            List<Long> longs = dfBrokerService.filterByUser();
            queryWrapper.in(DfBroker::getId, longs);
        }
        List<DfBroker> list = dfBrokerService.list(queryWrapper);
        return success(list);
    }

    /**
     * 查询代理商经纪树
     */
    @ApiOperation("查询代理商经纪列表")
    @GetMapping("/listByTree")
    public AjaxResult listByTree(DfBroker dfBroker) {
        LambdaQueryWrapper<DfBroker> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,dfBroker);
        List<DfBroker> list = dfBrokerService.list(queryWrapper);
        List<DfBroker> treeList = buildTree(list);
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            List<Long> longs = dfBrokerService.filterByUser();
            treeList = filterTree(treeList, longs);
//            queryWrapper.in(DfBroker::getId, longs);
        }
        return success(treeList);
    }

    private List<DfBroker> filterTree(List<DfBroker> treeList, List<Long> idList) {
        List<DfBroker> filteredList = new ArrayList<>();
        for (DfBroker broker : treeList) {
            // 如果当前节点的 ID 在列表中，则将其加入到结果列表中
            if (idList.contains(broker.getId())) {
                filteredList.add(broker);
            }
            // 如果当前节点有子节点，则递归调用该方法对其子节点进行过滤
            if (broker.getChildren() != null && !broker.getChildren().isEmpty()) {
                List<DfBroker> children = filterTree(broker.getChildren(), idList);
                // 如果子节点也被过滤掉了，则不加入到结果列表中
                if (!children.isEmpty()) {
                    broker.setChildren(children);
                    filteredList.add(broker);
                }
            }
        }
        return filteredList;
    }


    /**
     * 导出代理商经纪列表
     */
    @ApiOperation("导出代理商经纪列表")
    @Log(title = "代理商经纪导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DfBroker dfBroker) {
        LambdaQueryWrapper<DfBroker> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,dfBroker);
        List<DfBroker> list = dfBrokerService.list(queryWrapper);
        List<DfBroker> listAll = dfBrokerService.list();
        Map<Long, DfBroker> brokerMap = new HashMap<>();
        for (DfBroker broker : listAll) {
            brokerMap.put(broker.getId(), broker);
        }
        for (DfBroker broker : list) {
            broker.setBrokerDesc(HtmlUtils.stripHtmlTags(broker.getBrokerDesc()));
            DfBroker parentBroker = brokerMap.get(broker.getParentId());
            if (parentBroker != null) {
                broker.setParentName(parentBroker.getBrokerName());
            }
        }
        ExcelUtil<DfBroker> util = new ExcelUtil<DfBroker>(DfBroker. class);
        util.exportExcel(response, list, "代理商经纪数据");
    }

    /**
     * 代理商经纪状态修改
     */
    @Log(title = "代理商经纪状态修改", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody DfBroker dfBroker) {
        dfBrokerService.updateById(dfBroker);
        return toAjax(true);
    }


    /**
     * 获取代理商经纪详细信息
     */
    @ApiOperation("获取代理商经纪详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(dfBrokerService.getById(id));
    }

    /**
     * 新增代理商经纪
     */
    @ApiOperation("新增代理商经纪")
    @Log(title = "代理商经纪新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DfBroker dfBroker) {
        return toAjax(dfBrokerService.save(dfBroker));
    }

    /**
     * 修改代理商经纪
     */
    @ApiOperation("修改代理商经纪")
    @Log(title = "代理商经纪修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DfBroker dfBroker) {
        if (null == dfBroker.getParentId()) {
            dfBrokerMapper.updateByNull(dfBroker);
        }
        return toAjax(dfBrokerService.updateById(dfBroker));
    }

    /**
     * 删除代理商经纪
     */
    @ApiOperation("删除代理商经纪")
    @Log(title = "代理商经纪删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        LambdaQueryWrapper<DfBroker> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.in(DfBroker::getParentId,ids);
        if(dfBrokerService.list(queryWrapper).size()>0){
            return AjaxResult.warn("请先删除子节点");
        }
        LambdaQueryWrapper<SysUser> queryWrapperByUser = new LambdaQueryWrapper();
        queryWrapperByUser.in(SysUser::getDeptId,ids);
        queryWrapperByUser.eq(SysUser::getDelFlag,0);
        queryWrapperByUser.eq(SysUser::getUserType,"jj");
        if(sysUserService.list(queryWrapperByUser).size()>0){
            return AjaxResult.warn("请先删除用户");
        }
        return toAjax(dfBrokerService.removeBatchByIds(ids));
    }

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


        //id
        if(Validator.isNotEmpty(dfBroker.getId())){
            queryWrapper.eq(DfBroker::getId,dfBroker.getId());
        }

        //父级id
        if(Validator.isNotEmpty(dfBroker.getParentId())){
            queryWrapper.eq(DfBroker::getParentId,dfBroker.getParentId());
        }

        //代理商名称
        if(Validator.isNotEmpty(dfBroker.getBrokerName())){
            queryWrapper.like(DfBroker::getBrokerName,dfBroker.getBrokerName());
        }

        //地址
        if(Validator.isNotEmpty(dfBroker.getBrokerAddress())){
            queryWrapper.eq(DfBroker::getBrokerAddress,dfBroker.getBrokerAddress());
        }

        //简介
        if(Validator.isNotEmpty(dfBroker.getBrokerDesc())){
            queryWrapper.eq(DfBroker::getBrokerDesc,dfBroker.getBrokerDesc());
        }

        //显示顺序
        if(Validator.isNotEmpty(dfBroker.getOrderNum())){
            queryWrapper.eq(DfBroker::getOrderNum,dfBroker.getOrderNum());
        }

        //负责人
        if(Validator.isNotEmpty(dfBroker.getChargePerson())){
            queryWrapper.like(DfBroker::getChargePerson,dfBroker.getChargePerson());
        }

        //联系电话
        if(Validator.isNotEmpty(dfBroker.getContactPhone())){
            queryWrapper.like(DfBroker::getContactPhone,dfBroker.getContactPhone());
        }

        //邮箱
        if(Validator.isNotEmpty(dfBroker.getEmail())){
            queryWrapper.eq(DfBroker::getEmail,dfBroker.getEmail());
        }

        //是否机构
        if(Validator.isNotEmpty(dfBroker.getIsInstitution())){
            queryWrapper.eq(DfBroker::getIsInstitution,dfBroker.getIsInstitution());
        }

        //状态
        if(Validator.isNotEmpty(dfBroker.getStaus())){
            queryWrapper.eq(DfBroker::getStaus,dfBroker.getStaus());
        }

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

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

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

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

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

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

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

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

        }

}
