package com.crm.manager.controller;

import com.crm.manager.dto.export.FinanceAgentWithdrawExportDto;
import com.crm.manager.service.finance.FinanceAgentWithdrawFeignService;
import com.crm.manager.service.finance.FinanceWithdrawApiFeignService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.dto.finance.withdraw.FinanceAgentWithdrawDto;
import com.crm.rely.backend.core.entity.base.SingleLongEntity;
import com.crm.rely.backend.core.entity.finance.withdraw.*;
import com.crm.rely.backend.core.entity.finance.withdraw.automatic.FinanceWithdrawInfoEntity;
import com.crm.rely.backend.util.ExportUtil;
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 javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by max on 2020/9/4.
 */
@RestController
@RequestMapping("/finance/agent/withdraw")
public class FinanceAgentWithdrawController {

    @Autowired
    private FinanceAgentWithdrawFeignService financeAgentWithdrawFeignService;

    @Autowired
    private FinanceWithdrawApiFeignService financeWithdrawApiFeignService;

    @PostMapping("/approve")
    public BaseResultDto approve(@RequestBody @Validated FinanceWithdrawApproveEntity entity) throws Exception {
        if (!Constants.PASSED_STATUS.equals(entity.getStatus()) && !Constants.REJECTED_STATUS.equals(entity.getStatus())) {
            return BaseResultDto.error(Constants.NOT_PERMIT);
        }
        if (Constants.PASSED_STATUS.equals(entity.getStatus())) {
            entity.setWithdrawStatus(Constants.MANAGER_PROCESSING_STATUS);
        } else {
            entity.setWithdrawStatus(Constants.MANAGER_PENDING_STATUS);
        }
        entity.setOperationType(Constants.OPERATION_TYPE_MANUAL);

        return financeAgentWithdrawFeignService.approve(entity);
    }

    @PostMapping("/sales/approve")
    public BaseResultDto approveBySales(@RequestBody @Validated FinanceWithdrawApproveSalesEntity entity) throws Exception {
        if (!Constants.PASSED_STATUS.equals(entity.getStatus()) && !Constants.REJECTED_STATUS.equals(entity.getStatus())) {
            return BaseResultDto.error(Constants.NOT_PERMIT);
        }
        return financeAgentWithdrawFeignService.approveBySales(entity);
    }


    @PostMapping("/approve/submit/channel")
    public BaseResultDto approveByChannelSubmits(@RequestBody @Validated FinanceWithdrawApproveChannelSubmitEntity entity) throws Exception {


        return financeAgentWithdrawFeignService.approveBySubmit(entity);
    }

    @PostMapping("/channel")
    public BaseResultDto<Object> channel(@RequestBody @Validated FinanceWithdrawApproveChannelEntity entity) throws Exception {
        return financeAgentWithdrawFeignService.channel(entity);
    }


    @PostMapping("/approves")
    public BaseResultDto<Object> approves(@RequestBody FinanceWithdrawApprovesEntity entity) throws Exception {
        return financeAgentWithdrawFeignService.approves(entity);
    }

    @PostMapping("/approve/submits/channel")
    public BaseResultDto approveBySubmits(@RequestBody @Validated FinanceWithdrawApproveChannelSubmitsEntity entity) throws Exception {
        return financeAgentWithdrawFeignService.approveBySubmits(entity);
    }

    @PostMapping("/channels")
    public BaseResultDto<Object> channels(@RequestBody @Validated FinanceWithdrawApproveChannelsEntity entity) throws Exception {

        return financeAgentWithdrawFeignService.channels(entity);

    }

    @PostMapping("/search/list")
    public BaseResultDto<List<FinanceAgentWithdrawDto>> searcherList(@RequestBody @Validated FinanceAgentWithdrawSearchListEntity entity) throws Exception {

        return financeAgentWithdrawFeignService.searchList(entity);
    }

    @GetMapping("search/list/export")
    public void searcherListExport(@RequestParam(name = "cId") Long cId,
                                   @RequestParam(name = "serial") String serial,
                                   @RequestParam(name = "status") Integer status,
                                   @RequestParam(name = "submitStatus") Integer submitStatus,
                                   @RequestParam(name = "startSubmitDate") String startSubmitDate,
                                   @RequestParam(name = "endSubmitDate") String endSubmitDate,
                                   @RequestParam(name = "startDate") String startDate,
                                   @RequestParam(name = "endDate") String endDate,
                                   @RequestParam(name = "ibNo") String ibNo,
                                   @RequestParam(name = "channelCodes") String channelCodes,
                                   @RequestParam(name = "country") String country,
                                   @RequestParam(name = "pIbNo" , required = false) String pIbNo,
                                   HttpServletResponse response) throws Exception {


        FinanceAgentWithdrawSearchListEntity entity = new FinanceAgentWithdrawSearchListEntity();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        entity.setCId(cId);
        entity.setSerial(serial);
        entity.setStartDate(startDate == null ? new Date() : simpleDateFormat.parse(startDate));
        entity.setEndDate(endDate == null ? new Date() : simpleDateFormat.parse(endDate));
        entity.setStatus(status);
        entity.setIbNo(ibNo);
//        entity.setChannelCode(channelCode);
        if (Strings.isNullOrEmpty(channelCodes)) {
            entity.setChannelCodes(null);
        } else {

            entity.setChannelCodes(Arrays.asList(channelCodes.split(",")));
        }
        entity.setSubmitStatus(submitStatus);
        entity.setCountry(country);
        entity.setPIbNo(pIbNo);
        if ("undefinedundefined".equals(startSubmitDate)) {
            startSubmitDate = null;
        }
        if ("undefinedundefined".equals(endSubmitDate)) {
            endSubmitDate = null;
        }

        entity.setStartSubmitDate(Strings.isNullOrEmpty(startSubmitDate) ? null :
                simpleDateFormat.parse(startSubmitDate));
        entity.setEndSubmitDate(Strings.isNullOrEmpty(endSubmitDate) ? null : simpleDateFormat.parse(endSubmitDate));

        BaseResultDto<List<FinanceAgentWithdrawDto>> resultDto =
                financeAgentWithdrawFeignService.searchListExport(entity);
        List<FinanceAgentWithdrawExportDto> dtos = Lists.newArrayList();
        if (resultDto.getCode() == 200) {

            resultDto.getData().forEach((item) -> {
                FinanceAgentWithdrawExportDto dto = new FinanceAgentWithdrawExportDto();
                BeanUtils.copyProperties(item, dto);
                if (item.getStatus() == 1) {
                    dto.setStatusName("待处理");
                } else if (item.getStatus() == 2) {
                   if (item.getSubmitStatus() == 2 && item.getCallbackStatus() == 1) {
                       dto.setStatusName("已完成");
                   } else {
                       dto.setStatusName("处理中");
                   }
                } else if (item.getStatus() == 3) {
                    dto.setStatusName("拒绝");
                } else if (item.getStatus() == 5) {
                    dto.setStatusName("已取消");
                } else {
                    dto.setStatusName("");
                }


                if (Constants.APPLY_STATUS.equals(item.getSubmitStatus())) {
                    dto.setSubmitStatusName("未处理");
                } else if (Constants.PASSED_STATUS.equals(item.getSubmitStatus())) {
                    dto.setSubmitStatusName("已提交");
                } else if (Constants.REJECTED_STATUS.equals(item.getSubmitStatus())) {
                    dto.setSubmitStatusName("已拒绝");
                }
                dto.setCID(String.valueOf(item.getCId()));
                dtos.add(dto);
            });
        }

        ExportUtil.transferToResponse(genFileName(), dtos, FinanceAgentWithdrawExportDto.class, response);
    }

    @PostMapping("/search/single")
    public BaseResultDto<FinanceAgentWithdrawDto> searcherSingle(@RequestBody @Validated SingleLongEntity entity) throws Exception {
        return financeAgentWithdrawFeignService.searchSingle(entity);
    }

    @RequestMapping("/remit/channel")
    public BaseResultDto remitChannel() throws Exception {
        return financeAgentWithdrawFeignService.remitChannel();
    }

    @RequestMapping("/api/info")
    public BaseResultDto withdrawInfo(@RequestBody FinanceWithdrawInfoEntity entity) throws Exception {

        entity.setWithdrawInfoType(2);
        return financeWithdrawApiFeignService.withdrawInfo(entity.getWithdrawInfoUrl(), entity);
    }

    @RequestMapping("/withdrawapi")
    public BaseResultDto withdraw(@RequestBody Map<String, Object> params) throws Exception {
        String contextPath = params.get("withdrawUrl").toString();

        params.put("withdrawInfoType", 2);

        return financeWithdrawApiFeignService.withdraw(contextPath, params);

    }

    private String genFileName() {
        StringBuffer stringBuffer = new StringBuffer();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        stringBuffer.append("IB_EXPORT");
        stringBuffer.append("_");
        stringBuffer.append(sdf.format(new Date()));
        stringBuffer.append(".xlsx");
        String fileName = stringBuffer.toString();
        return fileName;
    }


}
