package com.crm.manager.controller;

import com.crm.manager.service.CustomInfoFeignService;
import com.crm.manager.service.CustomInfoService;
import com.crm.manager.service.FinanceCustomFeignService;
import com.crm.manager.service.UserInfoService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.PrefixEnum;
import com.crm.rely.backend.core.constant.StatusConstants;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.dto.base.BaseResultWithPagerDto;
import com.crm.rely.backend.core.exception.ServiceException;
import com.crm.rely.backend.model.dto.custom.CustomInfoDto;
import com.crm.rely.backend.core.entity.base.LongEntitys;
import com.crm.rely.backend.core.entity.base.SingleLongEntity;
import com.crm.rely.backend.model.entity.user.info.UserInfoEntity;
import com.crm.rely.backend.model.dto.custom.potential.CustomListDto;
import com.crm.rely.backend.model.entity.custom.CustomInfoFundsEntity;
import com.crm.rely.backend.model.entity.custom.info.CustomApproveEntity;
import com.crm.rely.backend.model.entity.custom.info.CustomInfoUpdateAgentEntity;
import com.crm.rely.backend.model.entity.custom.info.CustomInfoUpdateEntity;
import com.crm.rely.backend.model.entity.custom.info.CustomSearchEntity;
import com.google.common.base.Strings;
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 java.util.ArrayList;
import java.util.List;

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

    @Autowired
    private CustomInfoService customInfoService;

    @Autowired
    private CustomInfoFeignService customInfoFeignService;

    @Autowired
    private FinanceCustomFeignService financeCustomFeignService;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 删除客户信息
     *
     * @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("/approve/real")
    public BaseResultDto approveReal(@RequestBody CustomApproveEntity entity) throws Exception {

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

        if (StatusConstants.REJECTED_STATUS.equals(entity.getStatus()) && Strings.isNullOrEmpty(entity.getApproveDesc())) {
            return BaseResultDto.error(Constants.INPUT_REJECT_REASON);
        }
        if (StatusConstants.PASSED_STATUS.equals(entity.getStatus())) {
            entity.setApplyRealStatus(StatusConstants.PASSED_STATUS);
        } else {
            entity.setApplyRealStatus(StatusConstants.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(StatusConstants.APPLY_PENDING_STATUS);
//        entity.setStatus(StatusConstants.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/agent")
    public BaseResultDto manageUpdateAgentId(@RequestBody @Validated CustomInfoUpdateAgentEntity entity) throws Exception {

        entity = userInfoService.getAgent(entity);
        return customInfoFeignService.manageUpdateAgentId(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("/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,
                                                                     UserInfoEntity infoEntity) throws Exception {

        if (!PrefixEnum.PREFIX_SYSTEM.equals(infoEntity.getPrefix())) {
            entity.setAgentId(infoEntity.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.getStamp());
        } else {
            entity.setStamp(null);
        }

        if (!StatusConstants.PASSED_STATUS.equals(entity.getStatus())) {
            entity.setStatus(0);
        }

        validSortName(entity.getSortName());
        return customInfoService.getPageList(entity);
    }

    @PostMapping("/search/approve")
    public BaseResultDto approveList(@RequestBody CustomSearchEntity entity, UserInfoEntity infoEntity) throws Exception {
        if (!PrefixEnum.PREFIX_SYSTEM.equals(infoEntity.getPrefix())) {
            entity.setAgentId(infoEntity.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.getStamp());
        } else {
            entity.setStamp(null);
        }
        validSortName(entity.getSortName());
        entity.setStatus(StatusConstants.APPLY_STATUS);
        return customInfoService.getPageList(entity);
    }

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

        return customInfoService.getPageList(entity);
    }

    private void validSortName(String sortName) {
        if (!Strings.isNullOrEmpty(sortName)) {
            List<String> tableFields = new ArrayList<>(10);
            tableFields.add("last_ip");
            tableFields.add("add_ip");
            tableFields.add("modify_ip");
            if (!tableFields.contains(sortName)) {
                throw ServiceException.exception(Constants.FAIL);
            }
        }
    }
}
