package com.yunzhi.marketing.xlk.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunzhi.marketing.base.BaseController;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.common.DateUtils;
import com.yunzhi.marketing.common.StringUtils;
import com.yunzhi.marketing.entity.TaBuilding;
import com.yunzhi.marketing.entity.TaPerson;
import com.yunzhi.marketing.entity.TaRecommendCustomer;
import com.yunzhi.marketing.service.ITaBuildingService;
import com.yunzhi.marketing.service.ITaPersonService;
import com.yunzhi.marketing.service.ITaRecommendCustomerService;
import com.yunzhi.marketing.statistic.entity.TaCustomerFollowUpRecord;
import com.yunzhi.marketing.statistic.service.ITaCustomerFollowUpRecordService;
import com.yunzhi.marketing.xlk.dto.*;
import com.yunzhi.marketing.xlk.entity.ChannelCustomer;
import com.yunzhi.marketing.xlk.service.IChannelCustomerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
    * 渠道报备客户表  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2021-07-19
 */
@RestController
@RequestMapping("/api")
@Api(value = "森哥看这里-渠道报备客户表", tags = "森哥看这里-xlk-渠道报备客户表")
public class ChannelCustomerController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(ChannelCustomerController.class);

    @Autowired
    public IChannelCustomerService iChannelCustomerService;

    @Autowired
    ITaRecommendCustomerService taRecommendCustomerService;

    @Autowired
    private ITaPersonService taPersonService;

    @Autowired
    private ITaBuildingService iTaBuildingService;

    @Autowired
    private ITaCustomerFollowUpRecordService iTaCustomerFollowUpRecordService;


    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "admin-渠道报备客户表", notes = "admin-渠道报备客户表")
    @RequestMapping(value="/admin/channelCustomer",method= RequestMethod.GET)
    public ResponseBean channelCustomerList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                            @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                            @RequestParam(value ="buildingId", required = false) String buildingId,
                                            @RequestParam(value ="name", required = false) String name,
                                            @RequestParam(value ="phone", required = false) String phone,
                                            @RequestParam(value ="recommendPersonName", required = false) String recommendPersonName,
                                            @RequestParam(value ="recommendPhone", required = false) String recommendPhone,
                                            @RequestParam(value ="status", required = false) String status,
                                            @RequestParam(value ="type") String type,
                                            HttpServletRequest request){
        Integer orgId = getOrgId(request);
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
		    IPage<ChannelCustomer> pg = new Page<>(pageNum, pageSize);

            IPage<ChannelCustomer> result = iChannelCustomerService.getProfileList(pg,
                    orgId,
                    buildingId,
                    name,
                    phone,
                    recommendPersonName,
                    recommendPhone,
                    status,type,getUserId(request),getInstitutionIds(request));
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("channelCustomerList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 审核
     * @param id  实体ID
     * @param channelCustomerDTO 实体对象
     * @return
     */
    @ApiOperation(value = "admin-渠道报备客户审核", notes = "admin-渠道报备客户审核")
    @RequestMapping(value="/admin/channelCustomer/{id}",method= RequestMethod.PUT)
    public ResponseBean channelCustomerUpdate(@PathVariable String id,
                                              @RequestHeader("authorization") String token,
                                        @RequestBody ChannelCustomerDTO channelCustomerDTO){
        return iChannelCustomerService.auditCustomer(id,channelCustomerDTO);
    }


    /**
     * 驻场 确认到访
     *
     * @param
     * @return
     */
    @ApiOperation(value = "森哥看这里-wx-驻场确认到访", notes = "森哥看这里-wx-驻场确认到访")
    @RequestMapping(value="/{plat}/marking/visit",method= RequestMethod.PUT)
    public ResponseBean channelCustomerUpdate(@RequestBody MarkingChannelCustomerDTO params){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iChannelCustomerService.markingChannelCustomer(params);
        }catch (Exception e){
            responseBean.addError("不允许重复报备");
        }
        return responseBean;
    }

    /**
     * 驻场 确认认筹
     *
     * @param
     * @return
     */
    @ApiOperation(value = "森哥看这里-wx-驻场确认认筹", notes = "森哥看这里-wx-驻场确认认筹")
    @RequestMapping(value="/{plat}/marking/preparatory",method= RequestMethod.PUT)
    public ResponseBean preparatoryCustomer(@RequestBody MarkingPreparatoryCustomerDTO params){
        return iChannelCustomerService.preparatoryCustomer(params);
    }

    /**
     * 驻场 结佣
     *
     * @param
     * @return
     */
    @ApiOperation(value = "森哥看这里-wx-驻场确认结佣", notes = "森哥看这里-wx-驻场确认结佣")
    @RequestMapping(value="/{plat}/marking/commission",method= RequestMethod.PUT)
    public ResponseBean commissionCustomer(@RequestBody MarkingCommissionCustomerDTO params){
        return iChannelCustomerService.commissionCustomer(params);
    }

    /**
     * 驻场 确认签约
     *
     * @param
     * @return
     */
    @ApiOperation(value = "森哥看这里-wx-驻场确认签约", notes = "森哥看这里-wx-驻场确认签约")
    @RequestMapping(value="/{plat}/marking/signatory",method= RequestMethod.PUT)
    public ResponseBean signatoryCustomer(@RequestBody MarkingSignatoryCustomerDTO params){
        return iChannelCustomerService.signatoryCustomer(params);
    }


    /**
     * 驻场 无效报备
     *
     * @param
     * @return
     */
    @ApiOperation(value = "森哥看这里-wx-无效报备", notes = "森哥看这里-wx-无效报备")
    @RequestMapping(value="/{plat}/marking/invalidCustomer",method= RequestMethod.PUT)
    public ResponseBean invalidCustomerUpdate(@RequestBody MarkingChannelCustomerDTO params){
        return iChannelCustomerService.invalidCustomerUpdate(params);
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @ApiOperation(value = "森哥看这里-admin-后台获取详情信息", notes = "森哥看这里-admin-后台获取详情信息")
    @RequestMapping(value="/admin/channelCustomer/{id}",method= RequestMethod.GET)
    public ResponseBean channelCustomerGet(@PathVariable String id, @RequestHeader("authorization") String token){
        ResponseBean responseBean = new ResponseBean();
        try {
            ChannelCustomer channelCustomer = iChannelCustomerService.getById(id);
            if (StringUtils.isEmpty(channelCustomer.getCustomerId())){
                return ResponseBean.success(channelCustomer);
            }
            responseBean = taRecommendCustomerService.getCustDetail(channelCustomer.getCustomerId());
        }catch (Exception e){
            e.printStackTrace();
            logger.error("channelCustomerDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param customerId  实体ID
     */
    @ApiOperation(value = "森哥看这里-admin-后台获取详情信息", notes = "森哥看这里-admin-后台获取详情信息")
    @RequestMapping(value="/admin/customer/detail/{customerId}",method= RequestMethod.GET)
    public ResponseBean detailCustomerGet(@PathVariable String customerId, @RequestHeader("authorization") String token){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = taRecommendCustomerService.getCustDetail(customerId);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("channelCustomerDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/wx/channelCustomer/{id}",method= RequestMethod.GET)
    public ResponseBean wxGetCust(@PathVariable String id) {
        ResponseBean responseBean = new ResponseBean();
        try {
            ChannelCustomer channelCustomer = iChannelCustomerService.getMoreInfoById(id);
            responseBean.addSuccess(channelCustomer);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("channelCustomerDelete -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    @ApiOperation(value = "森哥看这里-wx-查询经纪人的我的客户列表", notes = "森哥看这里-wx-查询经纪人的我的客户列表")
    @GetMapping("/wx/channelCustomer/recommend/mine")
    public ResponseBean getWxCustomersIRecommended(@RequestParam int pageNumber, @RequestParam int pageSize,
                                                   @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
                                                   @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate,
                                                   @RequestParam(value = "status", required = false) Integer status,
                                                   @RequestParam(value = "name", required = false) String name,
                                                   HttpServletRequest request) {
        Integer orgId = getOrgId(request);
        String personId = getPersonId(request);
        TaPerson person = taPersonService.getById(personId);
        try {
            RecommendCustomerDTO recommendCustomerDTO = new RecommendCustomerDTO();
            recommendCustomerDTO.setEndDate(endDate);
            recommendCustomerDTO.setStartDate(startDate);
            recommendCustomerDTO.setOrgId(orgId);
            recommendCustomerDTO.setPersonId(personId);
            recommendCustomerDTO.setStatus(status);
            recommendCustomerDTO.setName(name);
            return iChannelCustomerService.getCustomersIRecommended(pageNumber, pageSize, recommendCustomerDTO);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 获取客户的几个基本状态
     * @param customerId
     * @return
     */
    @GetMapping("/wx/channelCustomer/status/{customerId}")
    public ResponseBean getWxCustomerStatus(@PathVariable String customerId) {
        TaRecommendCustomer customer = taRecommendCustomerService.getById(customerId);
        if (null == customer) {
            return ResponseBean.error("当前客户不存在", ResponseBean.ERROR_UNAVAILABLE);
        }

        // 报备信息
        QueryWrapper<ChannelCustomer> query = new QueryWrapper<>();
        query.eq("customer_id", customerId);
        query.last("limit 1");
        ChannelCustomer channelCustomer = iChannelCustomerService.getOne(query);

        // 所属楼盘
        TaBuilding taBuilding = null;
        if (null != customer.getBuildingId()) {
            taBuilding = iTaBuildingService.getById(customer.getBuildingId());
        }

        // 跟进信息
        QueryWrapper<TaCustomerFollowUpRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_id", customerId);
        queryWrapper.like("record_type", "%跟进%");
        queryWrapper.last(" and DATE_FORMAT(create_date, '%Y-%m-$d') = '"+ DateUtils.today() +"'");
        int num = iTaCustomerFollowUpRecordService.count(queryWrapper);

        Map<String, Object> rtn = new HashMap<>();
        rtn.put("channelCustomer", channelCustomer);
        rtn.put("building", taBuilding);
        rtn.put("followed", num > 0);

        return ResponseBean.success(rtn);
    }
}
