package com.ruoyi.ibs.grid.controller;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.ibs.enumertion.CustIdTypeEnum;
import com.ruoyi.ibs.grid.domain.dto.DeleteDTO;
import com.ruoyi.ibs.grid.domain.dto.GridUserSelectDTO;
import com.ruoyi.ibs.grid.domain.dto.virtual.VirtualGridDTO;
import com.ruoyi.ibs.grid.domain.dto.virtual.VirtualGridUpdateDTO;
import com.ruoyi.ibs.grid.domain.excel.VirtualCustImportDTO;
import com.ruoyi.ibs.grid.domain.excel.VirtualCustUserImportDTO;
import com.ruoyi.ibs.grid.domain.vo.GridUserVO;
import com.ruoyi.ibs.grid.domain.vo.VirtualGridVO;
import com.ruoyi.ibs.grid.service.VirtualGridService;
import com.ruoyi.ibs.task.domain.dto.MarketTaskDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author 吴凯程
 * @Date 2024/9/20
 **/
@Api(tags = "虚拟网格接口")
@RestController
@RequestMapping("/grid/virtual")
public class VirtualGridController extends BaseController {

    @Resource
    private VirtualGridService virtualGridService;

    @ApiOperation("新增网格")
    @Log(title = "虚拟网格-新增虚拟网格", businessType = BusinessType.INSERT)
    @PostMapping("/create")
    public R<String> createVirtualGrid(@RequestBody @Valid VirtualGridDTO virtualGridDTO){
        if (virtualGridDTO.getCreateMode().equals("1")) {
            return R.ok(virtualGridService.createVirtualGrid(virtualGridDTO));
        } else {
            return R.ok(virtualGridService.createVirtualGridByRelate(virtualGridDTO));
        }
    }

    /**
     * 创建网格————异步
     */
    @ApiOperation("异步新增网格")
    @Log(title = "虚拟网格-异步新增虚拟网格", businessType = BusinessType.INSERT)
    @PostMapping("/createAsync")
    public R<String> createVirtualGridAsync(@RequestPart("dto") @Valid String dtoJson,
                                            @RequestPart("file") MultipartFile file) {
        VirtualGridDTO virtualGridDTO = JSON.parseObject(dtoJson, VirtualGridDTO.class);
        if (virtualGridDTO.getCreateMode().equals("1")) {
            return R.ok(virtualGridService.createVirtualGridAsync(virtualGridDTO, file));
        } else {
            return R.ok(virtualGridService.createVirtualGridByRelateAsync(virtualGridDTO, file));
        }
    }

    @ApiOperation("修改网格")
    @Log(title = "虚拟网格-修改虚拟网格", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public R<String> updateVirtualGrid(@RequestBody @Valid VirtualGridUpdateDTO virtualGridUpdateDTO){
        return R.ok(virtualGridService.updateVirtualGrid(virtualGridUpdateDTO));
    }

    @ApiOperation("获取虚拟网格")
    @Log(title = "虚拟网格-获取虚拟网格")
    @GetMapping("/{gridId}")
    public R<VirtualGridVO> getVirtualGrid(@PathVariable Long gridId){
        return R.ok(virtualGridService.getVirtualGrid(gridId));
    }

    @ApiOperation("删除网格")
    @Log(title = "虚拟网格-删除虚拟网格", businessType = BusinessType.DELETE)
    @PostMapping("/delete")
    public R<String> deleteVirtualGrids(@RequestBody @Valid DeleteDTO deleteDTO){
        return R.ok(virtualGridService.deleteVirtualGrids(deleteDTO));
    }

    @ApiOperation("客户信息模板")
    @Log(title = "虚拟网格-客户信息模板", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response)
    {
        ExcelUtil<VirtualCustImportDTO> util = new ExcelUtil<>(VirtualCustImportDTO.class);
        util.exportExcel(response, null, "客户信息模板");
    }

    @ApiOperation("客户信息模板")
    @Log(title = "虚拟网格-客户信息模板", businessType = BusinessType.EXPORT)
    @PostMapping("/export/relate")
    public void exportRelate(HttpServletResponse response) {
        ExcelUtil<VirtualCustUserImportDTO> util = new ExcelUtil<>(VirtualCustUserImportDTO.class);
        util.exportExcel(response, null, "客户管护关系信息模板");
    }

    @ApiOperation("客户信息导入")
    @Log(title = "虚拟网格-客户信息管理", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public R<List<VirtualCustImportDTO>> importData(MultipartFile file) throws Exception {
        ExcelUtil<VirtualCustImportDTO> util = new ExcelUtil<>(VirtualCustImportDTO.class);
        List<VirtualCustImportDTO> virtualCustImportDTOS = util.importExcel(file.getInputStream());
        List<String> custIds = virtualCustImportDTOS.stream().map(virtualCustImportDTO -> {
            virtualCustImportDTO.checkValid();
            return virtualCustImportDTO.getCustId();
        }).distinct().collect(Collectors.toList());
        if (custIds.size() != virtualCustImportDTOS.size()) {
            throw new ServiceException("客户列表存在重复客户！");
        }
        if(virtualCustImportDTOS.size() > 0){
            virtualCustImportDTOS.forEach(virtualCustImportDTO -> {
                if (!StringUtils.isNotEmpty(virtualCustImportDTO.getCustIdType())) {
                    virtualCustImportDTO.setCustIdType(CustIdTypeEnum.getByCode(virtualCustImportDTO.getCustId().substring(0, 3)).getName());
                }
                if (!StringUtils.isNotEmpty(virtualCustImportDTO.getCustIdn())) {
                    virtualCustImportDTO.setCustIdn(virtualCustImportDTO.getCustId().substring(3));
                }
            });
        }
        return R.ok(virtualCustImportDTOS);
    }

    @ApiOperation("客户信息编辑导入")
    @Log(title = "虚拟网格-客户信息管理", businessType = BusinessType.IMPORT)
    @PostMapping("/import/update")
    public R<List<VirtualCustImportDTO>> importData(MultipartFile file, Long gridId) throws Exception {
        ExcelUtil<VirtualCustImportDTO> util = new ExcelUtil<>(VirtualCustImportDTO.class);
        List<VirtualCustImportDTO> virtualCustImportDTOS = util.importExcel(file.getInputStream());
        virtualCustImportDTOS.forEach(virtualCustImportDTO -> {
            virtualCustImportDTO.checkValid();
            if (virtualGridService.checkVirtualCustInGrid(gridId, virtualCustImportDTO)) {
                throw new ServiceException("网格内存在重复客户：" + virtualCustImportDTO.getCustId());
            }
        });
        Set<String> filter = new HashSet<>();
        List<VirtualCustImportDTO> collect = virtualCustImportDTOS.stream()
                .filter(virtualCustUserImportDTO -> filter.add(virtualCustUserImportDTO.getCustId()))
                .collect(Collectors.toList());
        if (collect.size() > 0) {
            collect.forEach(virtualCustImportDTO -> {
                if (!StringUtils.isNotEmpty(virtualCustImportDTO.getCustIdType())) {
                    virtualCustImportDTO.setCustIdType(CustIdTypeEnum.getByCode(virtualCustImportDTO.getCustId().substring(0, 3)).getName());
                }
                if (!StringUtils.isNotEmpty(virtualCustImportDTO.getCustIdn())) {
                    virtualCustImportDTO.setCustIdn(virtualCustImportDTO.getCustId().substring(3));
                }
            });
        }
        return R.ok(collect);
    }

    @ApiOperation("管护信息导入")
    @Log(title = "虚拟网格-管护信息导入", businessType = BusinessType.IMPORT)
    @PostMapping("/import/relate")
    public R<List<VirtualCustUserImportDTO>> importRelateData(MultipartFile file) throws Exception {
        ExcelUtil<VirtualCustUserImportDTO> util = new ExcelUtil<>(VirtualCustUserImportDTO.class);
        List<VirtualCustUserImportDTO> virtualCustImportDTOS = util.importExcel(file.getInputStream());
        Set<String> filter = new HashSet<>();
        List<VirtualCustUserImportDTO> collect = virtualCustImportDTOS.stream().filter(virtualCustUserImportDTO -> filter.add(virtualCustUserImportDTO.getCustId() + '-' + virtualCustUserImportDTO.getUserName()))
                .collect(Collectors.toList());
        if (!collect.isEmpty()) {
            collect.forEach(virtualCustImportDTO -> {
                virtualCustImportDTO.checkValid();
                if (!StringUtils.isNotEmpty(virtualCustImportDTO.getCustIdType())) {
                    virtualCustImportDTO.setCustIdType(CustIdTypeEnum.getByCode(virtualCustImportDTO.getCustId().substring(0, 3)).getName());
                }
                if (!StringUtils.isNotEmpty(virtualCustImportDTO.getCustIdn())) {
                    virtualCustImportDTO.setCustIdn(virtualCustImportDTO.getCustId().substring(3));
                }
            });
        }
        return R.ok(collect);
    }

    @ApiOperation("管护信息编辑导入")
    @Log(title = "虚拟网格-管护信息编辑导入", businessType = BusinessType.IMPORT)
    @PostMapping("/import/relate/update")
    public R<List<VirtualCustUserImportDTO>> importRelateData(MultipartFile file, Long gridId) throws Exception {
        ExcelUtil<VirtualCustUserImportDTO> util = new ExcelUtil<>(VirtualCustUserImportDTO.class);
        List<VirtualCustUserImportDTO> virtualCustImportDTOS = util.importExcel(file.getInputStream());
        virtualCustImportDTOS.forEach(virtualCustUserImportDTO -> {
            if (virtualGridService.checkVirtualCustRelateInGrid(gridId, virtualCustUserImportDTO)) {
                throw new ServiceException("网格内存在重复管护关系：" + virtualCustUserImportDTO.getUserName() + "-" + virtualCustUserImportDTO.getCustId());
            }
        });
        Set<String> filter = new HashSet<>();
        List<VirtualCustUserImportDTO> collect = virtualCustImportDTOS.stream().filter(virtualCustUserImportDTO -> filter.add(virtualCustUserImportDTO.getCustId() + '-' + virtualCustUserImportDTO.getUserName()))
                .collect(Collectors.toList());
        if (!collect.isEmpty()) {
            collect.forEach(virtualCustImportDTO -> {
                virtualCustImportDTO.checkValid();
                if (!StringUtils.isNotEmpty(virtualCustImportDTO.getCustIdType())) {
                    String idType = virtualCustImportDTO.getCustId().substring(0, 3);
                    if (!idType.equals("101") && !idType.equals("202")){
                        throw new ServiceException("存在客户号前缀错误！");
                    }
                    virtualCustImportDTO.setCustIdType(CustIdTypeEnum.getByCode(virtualCustImportDTO.getCustId().substring(0, 3)).getName());
                }
                if (!StringUtils.isNotEmpty(virtualCustImportDTO.getCustIdn())) {
                    virtualCustImportDTO.setCustIdn(virtualCustImportDTO.getCustId().substring(3));
                }
            });
        }
        return R.ok(collect);
    }

    @ApiOperation("获取网格关联机构用户")
    @Log(title = "虚拟网格-获取网格关联机构用户")
    @GetMapping("/user/list")
    public R<List<GridUserVO>> getUserListByGridId(@Valid GridUserSelectDTO gridUserSelectDTO) {
        return R.ok(virtualGridService.getUserListByDeptId(gridUserSelectDTO));
    }

    @ApiOperation("检查虚拟网格名称是否重复")
    @Log(title = "虚拟网格-检查虚拟网格名称是否重复")
    @GetMapping("/check/name")
    public R<Boolean> checkGridNameExist(String gridName) {
        return R.ok(virtualGridService.checkGridNameExist(gridName));
    }
}
