package com.crm.manager.controller;

import com.crm.manager.dto.export.CustomAllocationExportCsvDto;
import com.crm.manager.service.CustomAllocationRosterCommentService;
import com.crm.manager.service.CustomAllocationRosterRecordService;
import com.crm.manager.service.CustomAllocationRosterService;
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.dto.base.BaseResultDto;
import com.crm.rely.backend.core.dto.base.ExportCsvDto;
import com.crm.rely.backend.core.dto.custom.allocation.roster.CustomAllocationRosterCsvDto;
import com.crm.rely.backend.core.dto.custom.allocation.roster.comment.CustomAllocationRosterCommentDto;
import com.crm.rely.backend.core.dto.custom.allocation.roster.record.CustomAllocationRosterRecordDto;
import com.crm.rely.backend.core.dto.user.info.SalesInfoDropdownDto;
import com.crm.rely.backend.core.entity.custom.allocation.roster.CustomAllocationRosterClickEntity;
import com.crm.rely.backend.core.entity.custom.allocation.roster.CustomAllocationRosterSearchEntity;
import com.crm.rely.backend.core.entity.custom.allocation.roster.CustomAllocationRosterUpdateEntity;
import com.crm.rely.backend.core.entity.custom.allocation.roster.comment.CustomAllocationRosterCommentAddEntity;
import com.crm.rely.backend.core.entity.custom.allocation.roster.comment.CustomAllocationRosterCommentSearchEntity;
import com.crm.rely.backend.core.entity.custom.allocation.roster.record.CustomAllocationRosterRecordSearchEntity;
import com.crm.rely.backend.core.entity.custom.info.InfoEntity;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.util.StringUtil;
import com.crm.rely.backend.util.ToCsvFile;
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 javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author houn
 * @Date 2023/2/20 17:04
 * @PackageName:com.crm.manager.controller
 * @ClassName: CustomAllocationRosterController
 * @Description: TODO
 */
@RestController
@RequestMapping("/custom/allocation/roster")
public class CustomAllocationRosterController {
    @Autowired
    private CustomAllocationRosterService customAllocationRosterService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private CustomAllocationRosterCommentService customAllocationRosterCommentService;

    @Autowired
    private CustomAllocationRosterRecordService customAllocationRosterRecordService;


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

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

        entity.setStatus(0);
        return customAllocationRosterService.selectPageList(entity);
    }

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

        if (PrefixEnum.PREFIX_SALE.equals(infoEntity.getPrefix()) && !infoEntity.getIbInfo().getRoleId().equals(1035L)) {
            entity.setAllocationAgentId(infoEntity.getIbInfo().getId());
        }
        entity.setStatus(1);
        return customAllocationRosterService.selectPageList(entity);
    }

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

        if (PrefixEnum.PREFIX_SALE.equals(infoEntity.getPrefix()) && !infoEntity.getIbInfo().getRoleId().equals(1035L)) {
            entity.setAllocationAgentId(infoEntity.getIbInfo().getId());
        }
        entity.setStatus(2);
        return customAllocationRosterService.selectPageList(entity);
    }

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

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

        //如果非销售 则可以回收0 分配1 完成2 和无感4
        //如果是销售 则只能是分配 不能回收
        if (PrefixEnum.PREFIX_SALE.equals(infoEntity.getPrefix()) && !infoEntity.getIbInfo().getRoleId().equals(1035L)) {
            if (!entity.getStatus().equals(1) && !entity.getStatus().equals(3)) {
                return BaseResultDto.error(Constants.PARAMETER_ERROR);
            }
            entity.setAllocationId(infoEntity.getIbInfo().getId());
            //entity.setStatus(1);
        }

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

        customAllocationRosterService.update(entity);
        return BaseResultDto.success();
    }

    /**
     * 添加备注
     *
     * @param method
     * @param entity
     * @return
     * @throws ServiceException
     */
    @PostMapping("/{method}/comment")
    public BaseResultDto addComment(@PathVariable("method") String method,
                                    @RequestBody @Validated CustomAllocationRosterCommentAddEntity entity) throws ServiceException {
        if (!method.equals("allocated") && !method.equals("assigned") && !method.equals("insensibility")) {
            return BaseResultDto.error(Constants.NOT_PERMIT);
        }
        customAllocationRosterCommentService.add(entity);

        return BaseResultDto.success();
    }

    /**
     * 查看备注
     *
     * @param method
     * @param entity
     * @return
     * @throws ServiceException
     */
    @PostMapping("/{method}/search/list/comment")
    public BaseResultDto searchComment(@PathVariable("method") String method,
                                       @RequestBody @Validated CustomAllocationRosterCommentSearchEntity entity) throws ServiceException {
        if (!method.equals("allocated") && !method.equals("assigned") && !method.equals("complete") && !method.equals("insensibility")) {
            return BaseResultDto.error(Constants.NOT_PERMIT);
        }
        List<CustomAllocationRosterCommentDto> dtos = customAllocationRosterCommentService.selectList(entity);
        return BaseResultDto.success(dtos);
    }

    /**
     * 查看分配记录
     *
     * @param method
     * @param entity
     * @return
     * @throws ServiceException
     */
    @PostMapping("/{method}/search/list/record")
    public BaseResultDto searchRecord(@PathVariable("method") String method,
                                      @RequestBody @Validated CustomAllocationRosterRecordSearchEntity entity) throws ServiceException {
        if (!method.equals("allocated") && !method.equals("assigned") && !method.equals("complete") && !method.equals("insensibility")) {
            return BaseResultDto.error(Constants.NOT_PERMIT);
        }
        List<CustomAllocationRosterRecordDto> dtos = customAllocationRosterRecordService.selectList(entity);
        return BaseResultDto.success(dtos);
    }

    @GetMapping("/{method}/export")
    public void export(@PathVariable("method") String method,
                       @RequestParam(name = "areaId") Long areaId,
                       @RequestParam(name = "sourceCode") String sourceCode,
                       @RequestParam(name = "country") String country,
                       @RequestParam(name = "email") String email,
                       @RequestParam(name = "allocationPibNo") String allocationPibNo,
                       @RequestParam(name = "allocationSalesIbNo") String allocationSalesIbNo,
                       @RequestParam(name = "startDate") String startDate,
                       @RequestParam(name = "endDate") String endDate, HttpServletResponse response) throws Exception {

        CustomAllocationRosterSearchEntity entity = new CustomAllocationRosterSearchEntity();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

        entity.setStartDate(Strings.isNullOrEmpty(startDate) ? null : simpleDateFormat.parse(startDate));
        entity.setEndDate(Strings.isNullOrEmpty(endDate) ? null : simpleDateFormat.parse(endDate));
        entity.setAgentId(areaId);
        entity.setSourceCode(sourceCode);
        entity.setCountry(country);
        entity.setEmail(email);
        entity.setAllocationPibNo(allocationPibNo);
        entity.setAllocationSalesIbNo(allocationSalesIbNo);

        if (!method.equals("allocated") && !method.equals("assigned") && !method.equals("complete") && !method.equals("insensibility")) {
            throw ServiceException.exception(Constants.NOT_PERMIT);
        }
        if (method.equals("allocated")) {
            entity.setStatus(0);
        }
        if (method.equals("assigned")) {
            entity.setStatus(1);
        }
        if (method.equals("complete")) {
            entity.setStatus(2);
        }
        if (method.equals("insensibility")) {
            entity.setStatus(3);
        }


        List<CustomAllocationRosterCsvDto> dtos = customAllocationRosterService.selectCsvList(entity);


        String[] headArr = new String[]{"first name", "last name", "email", "company", "phone"};
        List<ExportCsvDto> exportCsvDtoList = new ArrayList<>();
        for (CustomAllocationRosterCsvDto dto : dtos) {

            CustomAllocationExportCsvDto customAllocationExportCsvDto = new CustomAllocationExportCsvDto();
            customAllocationExportCsvDto.setCompany(Strings.isNullOrEmpty(dto.getAllocationPibEmail()) ? "Company" :
                    dto.getAllocationPibEmail());
            customAllocationExportCsvDto.setFirstName(Strings.isNullOrEmpty(dto.getFirstName()) ? "--" :
                    dto.getFirstName().replace(",", "").replace("\"", ""));
            customAllocationExportCsvDto.setLastName(Strings.isNullOrEmpty(dto.getLastName()) ? "--" :
                    dto.getLastName().replace(",", "").replace("\"", ""));
            customAllocationExportCsvDto.setEmail(dto.getEmail());
            customAllocationExportCsvDto.setPhone("+" + dto.getAreaCode() + dto.getPhone());
            exportCsvDtoList.add(customAllocationExportCsvDto);
        }


        ToCsvFile.toCsvFile(StringUtil.getCsvFileName("", false), headArr, exportCsvDtoList, 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);
    }

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