package com.crm.manager.controller;

import com.alibaba.fastjson.JSON;
import com.crm.manager.dto.export.WebActivityOcExportDto;
import com.crm.manager.entity.excel.WebActivityOcExcelEntity;
import com.crm.manager.service.SysConfigService;
import com.crm.manager.service.UserInfoService;
import com.crm.manager.service.activity.WebActivityOcFeignService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.PrefixEnum;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.dto.user.info.SalesInfoDropdownDto;
import com.crm.rely.backend.core.dto.web.activity.oc.WebActivityOcSearchDto;
import com.crm.rely.backend.core.entity.base.SingleLongEntity;
import com.crm.rely.backend.core.entity.custom.info.InfoEntity;
import com.crm.rely.backend.core.entity.web.activity.oc.*;
import com.crm.rely.backend.core.pojo.table.SysConfigTable;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.util.EasyExcelUti;
import com.crm.rely.backend.util.ExportUtil;
import com.crm.rely.backend.util.StringUtil;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
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.util.ArrayList;
import java.util.List;

/**
 * @author: houn
 */
@RestController
@RequestMapping("/web/oc")
@Slf4j
public class WebActivityOcController {

    @Autowired
    private WebActivityOcFeignService service;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private SysConfigService sysConfigService;

    /**
     * 删除活动
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/delete")
    public BaseResultDto delete(@RequestBody @Validated WebActivityOcDeleteEntity entity) throws Exception {

        return service.delete(entity);
    }

    @PostMapping("/search/single")
    public BaseResultDto<WebActivityOcSearchDto> managerSingle(@RequestBody @Validated SingleLongEntity entity) throws Exception {

        return service.managerSingle(entity);

    }

    /**
     * 待分配
     *
     * @param entity
     * @return
     * @throws ServiceException
     */
    @PostMapping("/allocated/search/list")
    public BaseResultDto searchAllocated(@RequestBody @Validated WebActivityOcSearchEntity entity,
                                         InfoEntity infoEntity) throws Exception {

//        if (PrefixEnum.PREFIX_SALE.equals(infoEntity.getPrefix())) {
//            entity.setAllocationAgentId(infoEntity.getIbInfo().getId());
//        }

        entity.setStatus(0);
        entity.setUserEmail(infoEntity.getIbInfo().getEmail());
        return service.list(entity);
    }

    /**
     * 已分配
     *
     * @param entity
     * @return
     * @throws ServiceException
     */
    @PostMapping("/assigned/search/list")
    public BaseResultDto searchAssigned(@RequestBody @Validated WebActivityOcSearchEntity entity,
                                        InfoEntity infoEntity) throws Exception {

        if (PrefixEnum.PREFIX_SALE.equals(infoEntity.getPrefix())) {
            entity.setAllocationAgentId(infoEntity.getIbInfo().getId());
        }
        entity.setStatus(1);
        entity.setUserEmail(infoEntity.getIbInfo().getEmail());
        return service.list(entity);
    }

    /**
     * 已完成名单
     *
     * @param entity
     * @return
     * @throws ServiceException
     */
    @PostMapping("/complete/search/list")
    public BaseResultDto searchComplete(@RequestBody @Validated WebActivityOcSearchEntity entity,
                                        InfoEntity infoEntity) throws Exception {

        if (PrefixEnum.PREFIX_SALE.equals(infoEntity.getPrefix())) {
            entity.setAllocationAgentId(infoEntity.getIbInfo().getId());
        }
        entity.setStatus(2);
        entity.setUserEmail(infoEntity.getIbInfo().getEmail());
        return service.list(entity);
    }

    /**
     * 不分配 无感名单
     *
     * @param entity
     * @return
     * @throws ServiceException
     */
    @PostMapping("/insensibility/search/list")
    public BaseResultDto searchInsensibility(@RequestBody @Validated WebActivityOcSearchEntity entity,
                                             InfoEntity infoEntity) throws Exception {
        if (PrefixEnum.PREFIX_SALE.equals(infoEntity.getPrefix())) {
            entity.setAllocationAgentId(infoEntity.getIbInfo().getId());
        }
        entity.setStatus(3);
        entity.setUserEmail(infoEntity.getIbInfo().getEmail());
        return service.list(entity);
    }

    /**
     * 客户分配
     *
     * @param method
     * @param entity
     * @return
     * @throws ServiceException
     */
    @PostMapping("/{method}/allocation")
    public BaseResultDto allocation(@PathVariable("method") String method,
                                    @RequestBody @Validated WebActivityOcUpdateEntity entity) throws ServiceException {
        if (!method.equals("allocated") && !method.equals("assigned") && !method.equals("insensibility")) {
            return BaseResultDto.error(Constants.NOT_PERMIT);
        }

        if (!entity.getStatus().equals(1)) {
            entity.setAllocationAgentId(null);
        } else {
            if (entity.getAllocationAgentId() == null) {
                return BaseResultDto.error(Constants.PARAMETER_ERROR);
            }
        }
        return service.allocation(entity);
    }

    @PostMapping("/excel")
    public BaseResultDto export(@RequestParam("file") MultipartFile file) throws Exception {


        List<WebActivityOcExcelEntity> webActivityOcExcelEntities = EasyExcelUti.readExcel(file,
                new WebActivityOcExcelEntity(), 1, WebActivityOcExcelEntity.class);

        if (webActivityOcExcelEntities == null || webActivityOcExcelEntities.size() <= 0) {
            return BaseResultDto.success();
        }

        List<WebActivityOcAddEntity> entities = new ArrayList<>();

        for (WebActivityOcExcelEntity webActivityOcExcelEntity : webActivityOcExcelEntities) {
            WebActivityOcAddEntity entity = new WebActivityOcAddEntity();
            BeanUtils.copyProperties(webActivityOcExcelEntity, entity);

            if (Strings.isNullOrEmpty(entity.getCountry()) && Strings.isNullOrEmpty(entity.getName()) && Strings.isNullOrEmpty(entity.getPhone()) && Strings.isNullOrEmpty(entity.getEmail()) && Strings.isNullOrEmpty(entity.getSourceCode())) {
                break;
            }
            entities.add(entity);
        }
        return service.adds(entities);
    }

    @GetMapping("/template/export")
    public void templateExport(HttpServletResponse response) throws Exception {
        List<WebActivityOcExportDto> dtos = Lists.newArrayList();

        ExportUtil.transferToResponse(StringUtil.getXlsxFileName("OC-TEMPLATE", false), dtos,
                WebActivityOcExportDto.class, response);

    }

    /**
     * 代理销售信息
     *
     * @return
     * @throws ServiceException
     */
    @PostMapping("/sales")
    public BaseResultDto<List<SalesInfoDropdownDto>> sales(InfoEntity infoEntity) throws Exception {
        if (infoEntity.getIbInfo().getRoleId() != null && infoEntity.getIbInfo().getRoleId().equals(1035L)) {
            return userInfoService.getSalesLeaderInfoDropdown();
        }
        Long pid = null;
        if (PrefixEnum.PREFIX_SALE.equals(infoEntity.getPrefix())) {
            pid = infoEntity.getIbInfo().getId();
        }
        return userInfoService.getSalesInfoDropdown(pid);
    }


    /**
     * 添加跟进记录
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/follow/add")
    public BaseResultDto managerFollowAdd(@RequestBody @Validated WebActivityOcFollowAddEntity entity) throws Exception {

        return service.followAdd(entity);
    }

    /**
     * 查看跟进记录
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/follow/search/list")
    public BaseResultDto followList(@RequestBody WebActivityOcFollowAddEntity entity) throws Exception {

        return service.followList(entity);
    }

    @PostMapping("/api/add")
    public BaseResultDto allocatedAdd(@RequestHeader("api-key") String apiKey, @RequestBody WebActivityOcApiEntity entity) throws Exception {
        log.info("request api-key:{}, data :{}", apiKey, JSON.toJSONString(entity));

        SysConfigTable sysConfigTable = sysConfigService.getByCode(Constants.ACTIVITY_OC_API_KEY);
        if (sysConfigTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        if(!sysConfigTable.getValue().equals(apiKey)){
            log.error("api-key is error");
            return BaseResultDto.error("api-key is error");
        }

        return service.apiAdd(entity);
    }

    @PostMapping("/click/allocation/roster")
    public BaseResultDto clickAllocationRoster(@RequestBody @Validated WebActivityOcClickEntity entity) throws Exception {
        return service.clickAllocationRoster(entity);
    }

}
