package com.crm.manager.controller;

import com.crm.login.rely.backend.controller.BaseLoginController;
import com.crm.manager.dto.export.CustomListExportDto;
import com.crm.manager.service.CustomInfoService;
import com.crm.manager.service.custom.CustomInfoFeignService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.CustomWalletSourceEnum;
import com.crm.rely.backend.core.constant.PrefixEnum;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.dto.base.BaseResultWithPagerDto;
import com.crm.rely.backend.core.dto.custom.CustomInfoDto;
import com.crm.rely.backend.core.dto.custom.potential.CustomListDto;
import com.crm.rely.backend.core.entity.base.LongEntitys;
import com.crm.rely.backend.core.entity.base.SingleLongEntity;
import com.crm.rely.backend.core.entity.custom.info.*;
import com.crm.rely.backend.core.entity.custom.login.CustomLoginDayWithdrawLimitUpdateEntity;
import com.crm.rely.backend.exception.ControllerException;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.service.BlackListLoginService;
import com.crm.rely.backend.service.RedisService;
import com.crm.rely.backend.util.ExportUtil;
import com.crm.rely.backend.util.MD5Util;
import com.crm.rely.backend.util.StringUtil;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @description: 客户控制器
 * @author: houn
 * @create: 2020-06-13 17:52
 **/
@RestController
@RequestMapping("/custom")
public class CustomInfoController extends BaseLoginController {

    @Autowired
    private CustomInfoService customInfoService;

    @Autowired
    private CustomInfoFeignService customInfoFeignService;

    @Autowired
    private BlackListLoginService blackListLoginService;
    @Autowired
    private RedisService redisService;

//    @PostMapping("/{method}/add")
//    public BaseResultDto add(@PathVariable("method") String method, @RequestBody CustomInfoUpdateEntity entity,
//    InfoEntity infoEntity) {
//        if (!"potential".equals(method) && !"real".equals(method) && !"approve".equals(method)) {
//            return BaseResultDto.error(Constants.NOT_PERMIT);
//        }
//
//    }

    /**
     * 删除客户信息
     *
     * @param entitys
     * @return
     * @throws Exception
     */
    @PostMapping("/{method}/delete")
    public BaseResultDto delete(@PathVariable("method") String method, @RequestBody LongEntitys entitys) throws Exception {
        if (!"potential".equals(method) && !"real".equals(method) && !"approve".equals(method)) {
            return BaseResultDto.error(Constants.NOT_PERMIT);
        }

        return customInfoFeignService.manageDeleteBatch(entitys);

    }

    @PostMapping("/{method}/update")
    public BaseResultDto update(@PathVariable("method") String method, @RequestBody CustomInfoUpdateEntity entity) throws Exception {
        if (!"potential".equals(method) && !"real".equals(method) && !"approve".equals(method)) {
            return BaseResultDto.error(Constants.NOT_PERMIT);
        }

        BaseResultDto resultDto = customInfoFeignService.manageUpdate(entity);

        return resultDto;
    }

    @PostMapping("/apply/real")
    public BaseResultDto applyReal(@RequestBody CustomInfoUpdateAndApplyEntity entity) throws Exception {

        return customInfoFeignService.managerApplyReal(entity);
    }

    @PostMapping("/approve/real")
    public BaseResultDto approveReal(@RequestBody CustomApproveEntity entity) throws Exception {

        if (entity.getStatus() == null || (!Constants.REJECTED_STATUS.equals(entity.getStatus()) && !Constants.PASSED_STATUS.equals(entity.getStatus()))) {
            return BaseResultDto.error(Constants.PARAMETER_ERROR);
        }

        if (Constants.REJECTED_STATUS.equals(entity.getStatus()) && Strings.isNullOrEmpty(entity.getApproveDesc())) {
            return BaseResultDto.error(Constants.INPUT_REJECT_REASON);
        }
        if (Constants.PASSED_STATUS.equals(entity.getStatus())) {
            entity.setApplyRealStatus(Constants.PASSED_STATUS);
        } else {
            entity.setApplyRealStatus(Constants.REJECTED_STATUS);
        }

        customInfoService.approve(entity);
        return BaseResultDto.success();
    }

    @PostMapping("/de/approve")
    public BaseResultDto deApprove(@RequestBody SingleLongEntity SingleLongEntity) throws Exception {
        CustomApproveEntity entity = new CustomApproveEntity();
        entity.setId(SingleLongEntity.getId());
        entity.setApplyRealStatus(Constants.APPLY_REAL_STATUS);
        entity.setStatus(Constants.APPLY_STATUS);
        customInfoService.approve(entity);

        return BaseResultDto.success();
    }

    @PostMapping("/update/info")
    public BaseResultDto update(@RequestBody @Validated CustomInfoUpdateEntity entity) throws Exception {

        return customInfoFeignService.manageUpdate(entity);
    }

    @PostMapping("/update/pay/comment/valid")
    public BaseResultDto manageUpdatePayCommentValid(@RequestBody @Validated CustomInfoUpdatePayCommentValidEntity entity) throws Exception {

        return customInfoFeignService.manageUpdatePayCommentValid(entity);
    }

    @PostMapping("/update/agent")
    public BaseResultDto manageUpdateAgentId(@RequestBody @Validated CustomInfoUpdateAgentEntity entity) throws Exception {

        return customInfoFeignService.manageUpdateAgentId(entity);
    }

    @PostMapping("/batch/update/agent")
    public BaseResultDto<List<BaseResultDto>> manageBatchUpdateAgentId(@RequestBody @Validated List<CustomInfoUpdateAgentEntity> entities) throws Exception {
        BaseResultDto<List<BaseResultDto>> resultDto = BaseResultDto.success();
        resultDto.setData(Lists.newArrayList());
        for (CustomInfoUpdateAgentEntity entity : entities) {
            resultDto.getData().add(customInfoFeignService.manageUpdateAgentId(entity));
        }
        return resultDto;
    }

    @PostMapping("/batch/update/agent/v2")
    public BaseResultDto<BaseResultDto> manageBatchUpdateAgentIdV2(@RequestBody @Validated List<CustomInfoBatchUpdateAgentEntity> entities, InfoEntity infoEntity) throws Exception {
        if (PrefixEnum.PREFIX_ADMIN.equals(infoEntity.getPrefix()) || PrefixEnum.PREFIX_SYSTEM.equals(infoEntity.getPrefix())) {
            BaseResultDto<List<BaseResultDto>> resultDto = BaseResultDto.success();
            resultDto.setData(Lists.newArrayList());
            for (CustomInfoBatchUpdateAgentEntity entity : entities) {
                CustomInfoUpdateAgentEntity customInfoUpdateAgentEntity = new CustomInfoUpdateAgentEntity();
                customInfoUpdateAgentEntity.setId(entity.getCustomId());
                customInfoUpdateAgentEntity.setAgentId(entity.getNewAgentId());
                customInfoUpdateAgentEntity.setModifyTime(entity.getModifyTime());
                customInfoUpdateAgentEntity.setModifyUser(entity.getModifyUser());
                customInfoUpdateAgentEntity.setModifyIp(entity.getModifyIp());
                resultDto.getData().add(customInfoFeignService.manageUpdateAgentId(customInfoUpdateAgentEntity));
            }

            for (BaseResultDto dto : resultDto.getData()) {
                if (Constants.SUCCESS_CODE != dto.getCode()) {
                    return BaseResultDto.success("Partially successful");
                }
            }
            return BaseResultDto.success();
        } else {
            return BaseResultDto.error();
        }
    }

    @PostMapping("/update/balance")
    public BaseResultDto manageUpdateBalance(@RequestBody @Validated CustomInfoUpdateBalanceEntity entity) throws Exception {

        entity.setSource(CustomWalletSourceEnum.MANAGER);
        return customInfoFeignService.manageUpdateBalance(entity);
    }

    @PostMapping("/potential/update/agent")
    public BaseResultDto managePotentialUpdateAgentId(@RequestBody @Validated CustomInfoUpdateAgentEntity entity) throws Exception {

        return customInfoFeignService.manageUpdateAgentId(entity);
    }

    /**
     * 修改外佣和暗点
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/update/point")
    public BaseResultDto manageUpdateComPoint(@RequestBody @Validated CustomUpdateComPointEntity entity) throws Exception {

        return customInfoFeignService.manageUpdateComPoint(entity);
    }

    /**
     * 修改等级
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/update/level")
    public BaseResultDto manageUpdateLevel(@RequestBody @Validated CustomUpdateLevelEntity entity) throws Exception {

        return customInfoFeignService.manageUpdateLevel(entity);
    }


    @PostMapping("/update/password")
    public BaseResultDto updatePassword(@RequestBody @Validated CustomUpdatePasswordByManagerEntity entity) throws Exception {

        entity.setPassword(MD5Util.getMD5(entity.getPassword()));
        customInfoService.updatePassword(entity);
        return BaseResultDto.success();
    }

    @PostMapping("/update/day/withdraw/limit")
    public BaseResultDto updateDayWithdrawLimit(@RequestBody @Validated CustomLoginDayWithdrawLimitUpdateEntity entity) throws Exception {

        customInfoService.updateDayWithdrawLimit(entity);
        return BaseResultDto.success();
    }

    @PostMapping("/upload/head/picture/{customId}")
    public BaseResultDto managerUpload(@RequestParam(value = "file", required = false) MultipartFile file,
                                       @PathVariable("customId") Long customId) throws Exception {

        return customInfoFeignService.managerUpload(file, customId);
    }

    /**
     * 根据cid获取客户
     *
     * @param method
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/search/{method}/single")
    public BaseResultDto<CustomInfoDto> searcherSingleByCId(@PathVariable("method") String method,
                                                            @RequestBody SingleLongEntity entity) throws Exception {

        if (!"potential".equals(method) && !"real".equals(method) && !"approve".equals(method)) {
            return BaseResultDto.error(Constants.NOT_PERMIT);
        }
        return BaseResultDto.success(customInfoService.getSingleCustomInfoByCId(entity.getId()));
    }

    /**
     * 潜在客户列表
     *
     * @param entity
     * @param infoEntity
     * @return
     * @throws Exception
     */
    @PostMapping("/search/potential")
    public BaseResultWithPagerDto<List<CustomListDto>> potentialList(@RequestBody CustomSearchEntity entity,
                                                                     InfoEntity infoEntity) throws Exception {

        if (!PrefixEnum.PREFIX_SYSTEM.equals(infoEntity.getPrefix())) {
            entity.setAgentId(infoEntity.getIbInfo().getId());
        }
//        if (!PrefixEnum.PREFIX_SYSTEM.equals(infoEntity.getPrefix())) {
//            entity.setStamp(infoEntity.getIbInfo().getStamp());
//        }else {
//            entity.setStamp(null);
//        }
        if (PrefixEnum.PREFIX_SALE.equals(infoEntity.getPrefix())) {
            entity.setStamp(infoEntity.getIbInfo().getStamp());
        } else {
            entity.setStamp(null);
        }


        entity.setStatus(0);

        return customInfoService.getPageList(entity);
    }

    @PostMapping("/search/approve")
    public BaseResultDto approveList(@RequestBody CustomSearchEntity entity, InfoEntity infoEntity) throws Exception {
        if (!PrefixEnum.PREFIX_SYSTEM.equals(infoEntity.getPrefix())) {
            entity.setAgentId(infoEntity.getIbInfo().getId());
        }
//        if (!PrefixEnum.PREFIX_SYSTEM.equals(infoEntity.getPrefix())) {
//            entity.setStamp(infoEntity.getIbInfo().getStamp());
//        }else {
//            entity.setStamp(null);
//        }
        if (PrefixEnum.PREFIX_SALE.equals(infoEntity.getPrefix())) {
            entity.setStamp(infoEntity.getIbInfo().getStamp());
        } else {
            entity.setStamp(null);
        }

        entity.setStatus(Constants.APPLY_STATUS);
        return customInfoService.getPageList(entity);
    }

    /**
     * 真实客户
     *
     * @param entity
     * @param infoEntity
     * @return
     * @throws Exception
     */
    @PostMapping("/search/real")
    public BaseResultDto realList(@RequestBody CustomSearchEntity entity, InfoEntity infoEntity) throws Exception {
        entity.setStatus(Constants.PASSED_STATUS);
        if (!PrefixEnum.PREFIX_SYSTEM.equals(infoEntity.getPrefix())) {
            entity.setAgentId(infoEntity.getIbInfo().getId());
        }
//        if (!PrefixEnum.PREFIX_SYSTEM.equals(infoEntity.getPrefix())) {
//            entity.setStamp(infoEntity.getIbInfo().getStamp());
//        }else {
//            entity.setStamp(null);
//        }
        if (PrefixEnum.PREFIX_SALE.equals(infoEntity.getPrefix())) {
            entity.setStamp(infoEntity.getIbInfo().getStamp());
        } else {
            entity.setStamp(null);
        }
        return customInfoService.getPageList(entity);
    }


    @PostMapping("/search/retrieve")
    public BaseResultDto list(@RequestBody CustomSearchEntity entity, InfoEntity infoEntity) throws Exception {

        if (!PrefixEnum.PREFIX_SYSTEM.equals(infoEntity.getPrefix())) {
            entity.setAgentId(infoEntity.getIbInfo().getId());
        }
//        if (!PrefixEnum.PREFIX_SYSTEM.equals(infoEntity.getPrefix())) {
//            entity.setStamp(infoEntity.getIbInfo().getStamp());
//        }else {
//            entity.setStamp(null);
//        }
        if (PrefixEnum.PREFIX_SALE.equals(infoEntity.getPrefix())) {
            entity.setStamp(infoEntity.getIbInfo().getStamp());
        } else {
            entity.setStamp(null);
        }
        return customInfoService.getPageList(entity);
    }

    /**
     * 真实客户
     *
     * @param entity
     * @param infoEntity
     * @return
     * @throws Exception
     */
    @PostMapping("/account/search/real")
    public BaseResultDto customRealList(@RequestBody CustomSearchEntity entity, InfoEntity infoEntity) throws Exception {

        if (entity.getCId() == null && Strings.isNullOrEmpty(entity.getEmail())) {
            throw ServiceException.exception(Constants.PARAMETER_ERROR);
        }
        entity.setStatus(Constants.PASSED_STATUS);
        if (!PrefixEnum.PREFIX_SYSTEM.equals(infoEntity.getPrefix())) {
            entity.setAgentId(infoEntity.getIbInfo().getId());
        }
//        if (!PrefixEnum.PREFIX_SYSTEM.equals(infoEntity.getPrefix())) {
//            entity.setStamp(infoEntity.getIbInfo().getStamp());
//        }else {
//            entity.setStamp(null);
//        }
        if (PrefixEnum.PREFIX_SALE.equals(infoEntity.getPrefix())) {
            entity.setStamp(infoEntity.getIbInfo().getStamp());
        } else {
            entity.setStamp(null);
        }
        return customInfoService.getPageList(entity);
    }

    @PostMapping("/update/ibInvalid")
    public BaseResultDto<Object> updateIBInvalid(@RequestBody @Validated CustomIbInvalidUpdateEntity entity,
                                                 InfoEntity infoEntity) throws Exception {
        entity.setUserId(infoEntity.getIbInfo().getId());
        return customInfoFeignService.updateIBInvalid(entity);
    }

    @GetMapping(value = {"/{method}/export"})
    public void exportList(@PathVariable("method") String method, @RequestParam(name = "cId") Long cId,
                           @RequestParam(name = "email") String email,
                           @RequestParam(name = "identity") String identity, @RequestParam(name = "ibNo") String ibNo
            , @RequestParam(name = "sourceCode") String sourceCode,
                           @RequestParam(name = "startDate") String startDate,
                           @RequestParam(name = "endDate") String endDate,
                           @RequestParam(name = "status") Integer status,
                           @RequestParam(name = "potentialStatus") Integer potentialStatus,
                           HttpServletResponse response, InfoEntity infoEntity) throws Exception {
        if (!"potential".equals(method) && !"real".equals(method) && !"approve".equals(method)) {
            throw new ControllerException(Constants.NOT_PERMIT);
        }
        CustomSearchEntity entity = new CustomSearchEntity();
        if (!PrefixEnum.PREFIX_SYSTEM.equals(infoEntity.getPrefix())) {
            entity.setAgentId(infoEntity.getIbInfo().getId());
        }
//        if (!PrefixEnum.PREFIX_SYSTEM.equals(infoEntity.getPrefix())) {
//            entity.setStamp(infoEntity.getIbInfo().getStamp());
//        }else {
//            entity.setStamp(null);
//        }
        if (PrefixEnum.PREFIX_SALE.equals(infoEntity.getPrefix())) {
            entity.setStamp(infoEntity.getIbInfo().getStamp());
        } else {
            entity.setStamp(null);
        }
        //
        switch (method) {
            case "potential":
                entity.setStatus(0);
                break;
            case "approve":
                entity.setStatus(Constants.APPLY_STATUS);
                break;
            case "real":
                entity.setStatus(Constants.PASSED_STATUS);
            default:
                break;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        entity.setPotentialStatus(potentialStatus);
        entity.setCId(cId);
        entity.setEmail(email);
        entity.setIdentity(identity);
        entity.setIbNo(ibNo);
        entity.setStartDate(Strings.isNullOrEmpty(startDate) ? null : simpleDateFormat.parse(startDate));
        entity.setEndDate(Strings.isNullOrEmpty(endDate) ? null : simpleDateFormat.parse(endDate));
//        entity.setStatus(status);
        entity.setSourceCode(sourceCode);

        List<CustomListDto> customListDtos = customInfoService.getList(entity, false);

        List<CustomListExportDto> dtos = Lists.newArrayList();
        customListDtos.forEach((item) -> {
            CustomListExportDto dto = new CustomListExportDto();
            BeanUtils.copyProperties(item, dto);
            dto.setCID(item.getCId());
            dto.setPIBNO(item.getPIbNo());
            dtos.add(dto);
        });
        ExportUtil.transferToResponse(StringUtil.getXlsxFileName("CUSTOM", true), dtos, CustomListExportDto.class,
                response);

    }

    /**
     * 账号解封
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/unseal")
    public BaseResultDto unseal(@RequestBody @Validated CustomInfoUnsealEntity entity) throws Exception {
        blackListLoginService.removeFromList(PrefixEnum.PREFIX_CUSTOM.getCode() + entity.getLoginName(),
                PrefixEnum.PREFIX_CUSTOM.getCode());
        return BaseResultDto.success();
    }

    /**
     * 检查账号是否被封
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/check/seal")
    public BaseResultDto checkSeal(@RequestBody @Validated CustomInfoCheckSealEntity entity) throws Exception {
        boolean checkSealBool =
                blackListLoginService.checkSeal(PrefixEnum.PREFIX_CUSTOM.getCode() + entity.getLoginName());
        return BaseResultDto.success(checkSealBool);
    }

    @PostMapping("/manager/login/custom")
    public BaseResultDto login(@RequestBody SingleLongEntity entity) throws Exception {

        return customInfoFeignService.manageLogin(entity);

    }

    @PostMapping("/verify/real")
    public BaseResultDto verifyRealAgain(@RequestBody SingleLongEntity entity) throws Exception {
        customInfoService.verifyRealAgain(entity);
        return BaseResultDto.success(Constants.SUCCESS);

    }

    @PostMapping("/update/show/login/type")
    public BaseResultDto updateExcludeShowLoginType(@RequestBody @Validated CustomUpdateExcludeShowLoginTypeEntity entity) throws Exception {
        customInfoFeignService.managerUpdateExcludeShowLoginType(entity);
        return BaseResultDto.success();
    }

    @PostMapping("/search/ucard")
    public BaseResultDto getUcardCustomList(@RequestBody CustomSearchEntity entity) throws Exception {
        if (Strings.isNullOrEmpty(entity.getEmail())) {
            return BaseResultDto.success();
        }
        List<CustomListDto> list = customInfoService.getUcardCustomList(entity);
        return BaseResultDto.success(list);
    }

    @PostMapping("/update/cent/number/limit")
    public BaseResultDto updateCentNumberLimit(@RequestBody @Validated CustomUpdateCentNumberLimitEntity entity) throws Exception {
        customInfoFeignService.updateCentNumberLimit(entity);
        return BaseResultDto.success();
    }

    @PostMapping("/update/email/real")
    public BaseResultDto updateEmailReal(@RequestBody @Validated CustomUpdateEmailEntity entity) throws Exception {
        customInfoFeignService.updateEmailReal(entity);
        return BaseResultDto.success();
    }

}
