package com.testor.module.partner.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.testor.biz.rule.service.SysRuleService;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.common.util.FileUtil;
import com.testor.module.partner.model.domain.TPartnerOrg;
import com.testor.module.partner.model.dto.TPartnerOrgDTO;
import com.testor.module.partner.model.dto.TPartnerOrgParam;
import com.testor.module.partner.model.vo.PartnerOrgBlacklistVO;
import com.testor.module.partner.model.vo.PartnerOrgDetailVO;
import com.testor.module.partner.model.vo.PartnerOrgVO;
import com.testor.module.partner.service.TPartnerOrgService;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.constants.enumeration.BaseStatusEnum;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 相关方组织机构Controller
 *
 * @author testor-framework
 * @date 2022-06-01 14:16:53
 */
@RestController
@RequestMapping("/partner/partnerOrg")
@Api(value = "TPartnerOrg", tags = "相关方组织机构")
@Slf4j
public class TPartnerOrgController extends SuperController {
    @Autowired
    private TPartnerOrgService tPartnerOrgService;

    @Autowired
    private SysOrgService sysOrgService;

    @Resource
    private HttpServletResponse response;

    @Resource
    private HttpServletRequest request;
    @Resource
    private SysRuleService sysRuleService;
    @Value("${ureport.path}")
    private String path;

    @ApiOperation(value = "新增 相关方组织机构", notes = "Add TPartnerOrg")
    @PostMapping(value = "/add")
    public BaseResponse<TPartnerOrg> addEntity(@RequestBody TPartnerOrgDTO addRequest) {
        return tPartnerOrgService.editPartnerOrg(addRequest);

    }

    @ApiOperation(value = "获取 所有相关方组织机构 (可以根据name/orgId进行筛选)")
    @GetMapping(value = "/getAll")
    public BaseResponse<BaseResponseList<TPartnerOrg>> getAll(@RequestParam(required = false) String name, @RequestParam(required = false) String orgId, @RequestParam(required = false) String flag) {
        BaseResponse<BaseResponseList<TPartnerOrg>> responseListBaseResponse = new BaseResponse<>();
        BaseResponseList<TPartnerOrg> baseResponseList = new BaseResponseList<>();
        List<TPartnerOrg> list = null;

        if ("1".equals(flag)) {
            TPartnerOrgDTO tPartnerOrgDTO = new TPartnerOrgDTO();
            tPartnerOrgDTO.setName(name);
            tPartnerOrgDTO.setId(orgId);
            list = tPartnerOrgService.getOrgId(tPartnerOrgDTO);
        } else {
            TPartnerOrgDTO tPartnerOrgDTO = new TPartnerOrgDTO();
            tPartnerOrgDTO.setName(name);
            tPartnerOrgDTO.setId(orgId);
            list = tPartnerOrgService.getResid(tPartnerOrgDTO);
        }


        baseResponseList.setData(list);
        responseListBaseResponse.setData(baseResponseList);
        return responseListBaseResponse;
    }


    @ApiOperation(value = "获取 相关方组织机构-根据id", notes = "Get TPartnerOrg By Id")
    @GetMapping(value = "/get")
    public BaseResponse<TPartnerOrg> getById(@RequestParam("id") String id) {
        BaseResponse<TPartnerOrg> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            TPartnerOrg data = tPartnerOrgService.getById(id);
            baseResponse.setData(data);
        }
        return baseResponse;
    }

    @ApiOperation(value = "获取 相关方详情-根据id", notes = "Get TPartnerOrg By Id")
    @GetMapping(value = "/details")
    public BaseResponse<PartnerOrgDetailVO> details(@ApiParam(name = "resId", value = "相关方id") @RequestParam("resId") String resId) {
        BaseResponse<PartnerOrgDetailVO> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(resId)) {
            PartnerOrgDetailVO detail = tPartnerOrgService.getDetail(resId);
            baseResponse.setData(detail);
        }
        return baseResponse;
    }


    @ApiOperation(value = "获取 相关方组织机构 分页列表", notes = "List TPartnerOrg with page")
    @PostMapping(value = "/list")
    public BaseResponse<BaseResponseList<PartnerOrgVO>> listEntity(@RequestBody TPartnerOrgParam param) {
        BaseResponse<BaseResponseList<PartnerOrgVO>> baseResponse = new BaseResponse<>();
        IPage<PartnerOrgVO> resultList = tPartnerOrgService.listByPage(param);
        BaseResponseList<PartnerOrgVO> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList.getRecords());
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    @ApiOperation(value = "修改 相关方组织机构", notes = "Update TPartnerOrg By Id")
    @PutMapping(value = "/update")
    public BaseResponse<TPartnerOrg> updateEntity(@RequestBody TPartnerOrgDTO updateRequest) {
        return tPartnerOrgService.editPartnerOrg(updateRequest);
    }

   /* @ApiOperation(value = "删除 相关方组织机构 ", notes = "delete TPartnerOrg By Id")
    @PutMapping(value = "/delete")
    public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TPartnerOrgDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && StringHelper.isNotEmpty(deleteRequest.getId())) {
            boolean result = false;
            if (tPartnerOrgService.checkDeleteAuthority(deleteRequest.getType())) {
                TPartnerOrg data = new TPartnerOrg();
                data.setId(deleteRequest.getId());
                data.setStatus(BizConstants.STATUS_DELETE);
                result = tPartnerOrgService.updateById(data);
            }
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }

        return baseResponse;
    }*/

    /*@ApiOperation(value = "批量删除相关方组织机构", notes = "delete TPartnerOrg by batch Id")
    @PutMapping(value = "/batch_delete")
    public BaseResponse<BizGeneralResponse> deleteEntityBatch(
            @RequestBody TPartnerOrgDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {

            boolean result = false;
            if (tPartnerOrgService.checkDeleteAuthority(deleteRequest.getType())) {
                List<TPartnerOrg> tPartnerOrgList = new ArrayList<>();
                for (String id : deleteRequest.getIds()) {
                    TPartnerOrg data = new TPartnerOrg();
                    data.setId(id);
                    data.setStatus(BizConstants.STATUS_DELETE);
                    tPartnerOrgList.add(data);
                }
                *//* 批量删除 *//*
                result = tPartnerOrgService.updateBatchById(tPartnerOrgList);
            }
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }*/


    @ApiOperation(value = "加入黑名单")
    @GetMapping(value = "/addBlacklist")
    public BaseResponse<BizGeneralResponse> addBlacklist(String id, String reason) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (StrUtil.isBlank(id) || StrUtil.isBlank(reason)) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("参数缺失");
            return baseResponse;
        }

        UserInfo curUser = ContextUtils.getLoginUser();
        if (StrUtil.isBlank(curUser.getOrgId())) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("用户信息错误");
            return baseResponse;
        }
        // 组织机构id
        String curUserOrgId = curUser.getOrgId();

        TPartnerOrg data = new TPartnerOrg();
        data.setId(id);
        data.setIsBlacklist("1");
        data.setBlacklistReason(reason);
        data.setIsBlacklistBy(curUserOrgId);
        data.setUpdateBy(getUserId());
        data.setUpdateDate(new Date());
        boolean result = tPartnerOrgService.updateById(data);
        baseResponse.setData(
                BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        return baseResponse;
    }

    private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object,Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }


    @ApiOperation(value = "获取 相关方黑名单组织机构 分页列表")
    @PostMapping(value = "/blacklist")
    public BaseResponse<BaseResponseList<PartnerOrgBlacklistVO>> blacklist(@RequestBody TPartnerOrgParam param) {
        BaseResponse<BaseResponseList<PartnerOrgBlacklistVO>> baseResponse = new BaseResponse<>();
        IPage<PartnerOrgBlacklistVO> blacklist = tPartnerOrgService.blacklist(param);
        BaseResponseList<PartnerOrgBlacklistVO> baseResponseList = new BaseResponseList<>();
        List<PartnerOrgBlacklistVO> collect = blacklist.getRecords().stream().filter(distinctByKey(PartnerOrgBlacklistVO::getPartnerId))
                .collect(Collectors.toList());

        baseResponseList.setData(collect);
        baseResponseList.setTotal(blacklist.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    @ApiOperation(value = "修改 恢复黑名单")
    @GetMapping(value = "/recoverBlacklist")
    public BaseResponse<Boolean> recoverBlacklist(String id) {
        BaseResponse<Boolean> baseResponse = new BaseResponse<>();
        UserInfo curUser = ContextUtils.getLoginUser();
        if (StrUtil.isBlank(curUser.getOrgId())) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("用户信息错误");
            return baseResponse;
        }
        // 组织机构id
        String curUserOrgId = curUser.getOrgId();

        SysOrg sysOrg = sysOrgService.getById(curUserOrgId);
        BigDecimal treeLevel = sysOrg.getTreeLevel();
        if (treeLevel.compareTo(new BigDecimal(1)) != 0) {
            throw new RuntimeException("只有顶级人员才能恢复黑名单中的相关方");
        }
        TPartnerOrg tPartnerOrg = new TPartnerOrg();
        tPartnerOrg.setId(id);
        tPartnerOrg.setIsBlacklist("0");
        tPartnerOrg.setBlacklistReason(null);
        tPartnerOrg.setIsBlacklistBy(null);
        tPartnerOrg.setUpdateBy(getUserId());
        tPartnerOrg.setUpdateDate(new Date());
        boolean b = tPartnerOrgService.updateById(tPartnerOrg);
        baseResponse.setData(b);
        return baseResponse;
    }


    @ApiOperation(value = "导出相关方组织机构", notes = "")
    @PostMapping("/exportPartnerOrg")
    public void exportPartnerOrg(@RequestBody List<String> ids) throws Exception {
        String url = this.path + "/ureport/excel?_u=file:partnerOrg.ureport.xml";

        if (null != ids && ids.size() > 0) {
            url = url + "&ids=" + ids;
        }

        String fileName = "相关方组织机构.xlsx";
        FileUtil.downloadHttpFile(url, request, response, fileName);
    }


    @ApiOperation(value = "批量导入相关方机构", notes = "")
    @GetMapping("/importPartnerOrg")
    public BaseResponse<String> importPartnerOrg(@RequestParam("file") MultipartFile file) throws Exception {
        return tPartnerOrgService.importPartnerOrg(file);
    }

//    @ApiOperation(value = "首页 - 危险作业 - 本日计划进行", notes = "")
//    @GetMapping("/importPartnerOrg")
//    public BaseResponse<String> importPartnerOrg(@RequestParam("file") MultipartFile file) throws Exception {
//        return tPartnerOrgService.importPartnerOrg(file);
//    }
}
