package com.yunzhi.marketing.xlk.controller;

import com.alibaba.fastjson.JSONObject;
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.center.taUser.entity.TaUser;
import com.yunzhi.marketing.center.taUser.service.ITaUserService;
import com.yunzhi.marketing.common.StringUtils;
import com.yunzhi.marketing.entity.*;
import com.yunzhi.marketing.service.*;
import com.yunzhi.marketing.xlk.entity.CustomerInfo;
import com.yunzhi.marketing.xlk.entity.CustomerInfoModifyRecord;
import com.yunzhi.marketing.xlk.service.ICustomerInfoModifyRecordService;
import com.yunzhi.marketing.xlk.service.ICustomerInfoService;
import com.yunzhi.marketing.xlk.vo.CustomerInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
    * 客户基本信息表  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2021-07-29
 */
@RestController
@RequestMapping("/api")
@Api(value = "客户基本信息表", tags = "xlk-客户基本信息表")
public class CustomerInfoController extends BaseController {

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

    @Autowired
    public ICustomerInfoService iCustomerInfoService;

    @Autowired
    private ICustomerInfoModifyRecordService customerInfoModifyRecordService;

    @Autowired
    public ITaPersonService taPersonService;

    @Autowired
    public ITaRecommendCustomerService iTaRecommendCustomerService;

    @Autowired
    private TaChannelPersonService taChannelPersonService;

    @Autowired
    private TaChannelService taChannelService;

    @Autowired
    private ITaPersonBuildingService taPersonBuildingService;

    @Autowired
    private ITaUserService taUserService;

    @Autowired
    private ITaBuildingService taBuildingService;
    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/customerInfo",method= RequestMethod.GET)
    public ResponseBean customerInfoList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                         @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
		    IPage<CustomerInfo> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<CustomerInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("create_date");

            IPage<CustomerInfo> result = iCustomerInfoService.page(pg, queryWrapper);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("customerInfoList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     * @param customerInfo 实体对象
     * @return
     */
    @ApiOperation(value = "wx-保存客户信息", notes = "wx-保存客户信息")
    @RequestMapping(value="/wx/customerInfo",method= RequestMethod.POST)
    public ResponseBean customerInfoAdd(@RequestBody CustomerInfo customerInfo, @RequestHeader("authorization") String token, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        String openid = getOpenId(request);
        Integer orgId = getOrgId(request);
        List<TaPerson> persons = taPersonService.getPersonsByOpenId(openid);
        if (null == persons || persons.size() == 0) {
            return ResponseBean.error("当前账户信息异常, 清除缓存重试", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson person = persons.get(0);
        try {
            LambdaQueryWrapper<CustomerInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(CustomerInfo::getCustomerId,customerInfo.getCustomerId());
            CustomerInfo oldCustomerInfo = iCustomerInfoService.getOne(lambdaQueryWrapper);
            if (null != oldCustomerInfo) {
                if (iCustomerInfoService.updateById(customerInfo)){
                    // 记录到修改记录表中
                    CustomerInfoModifyRecord customerInfoModifyRecord = new CustomerInfoModifyRecord();
                    customerInfoModifyRecord.setCreateDate(LocalDateTime.now());
                    customerInfoModifyRecord.setCustomerInfoId(oldCustomerInfo.getCustomerId());
                    customerInfoModifyRecord.setModifyPersonId(person.getPersonId());
                    customerInfoModifyRecord.setOrgId(orgId);
                    customerInfoModifyRecord.setContent(JSONObject.toJSONString(customerInfo));
                    customerInfoModifyRecordService.save(customerInfoModifyRecord);
                    responseBean.addSuccess(customerInfo);
                }else {
                    responseBean.addError("fail");
                }
                return responseBean;
            }

            customerInfo.setCreateDate(LocalDateTime.now());
            customerInfo.setCreatePerson(person.getPersonId());
            customerInfo.setOrgId(orgId);
            if (iCustomerInfoService.save(customerInfo)){
                responseBean.addSuccess(customerInfo);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("customerInfoAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ResponseBody
    @RequestMapping(value="/customerInfo/{id}", method= RequestMethod.DELETE)
    public ResponseBean customerInfoDelete(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            if(iCustomerInfoService.removeById(id)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("customerInfoDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param customerId  实体ID
     * @param customerInfo 实体对象
     * @return
     */
    @RequestMapping(value="/wx/customerInfo/{customerId}",method= RequestMethod.PUT)
    public ResponseBean customerInfoUpdate(@PathVariable String customerId,
                                        @RequestBody CustomerInfo customerInfo, @RequestHeader("authorization") String token,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        String openid = getOpenId(request);
        Integer orgId = getOrgId(request);
        List<TaPerson> persons = taPersonService.getPersonsByOpenId(openid);
        if (null == persons || persons.size() == 0) {
            return ResponseBean.error("当前账户信息异常, 清除缓存重试", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson person = persons.get(0);
        try {
            LambdaQueryWrapper<CustomerInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(CustomerInfo::getCustomerId,customerId);
            CustomerInfo oldCustomerInfo = iCustomerInfoService.getOne(lambdaQueryWrapper);
            if (iCustomerInfoService.updateById(customerInfo)){
                // 记录到修改记录表中
                CustomerInfoModifyRecord customerInfoModifyRecord = new CustomerInfoModifyRecord();
                customerInfoModifyRecord.setCreateDate(LocalDateTime.now());
                customerInfoModifyRecord.setCustomerInfoId(oldCustomerInfo.getCustomerId());
                customerInfoModifyRecord.setModifyPersonId(person.getPersonId());
                customerInfoModifyRecord.setOrgId(orgId);
                customerInfoModifyRecord.setContent(JSONObject.toJSONString(customerInfo));
                customerInfoModifyRecordService.save(customerInfoModifyRecord);
                responseBean.addSuccess(customerInfo);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("customerInfoUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param
     */
    @ApiOperation(value = "wx-查询客户信息", notes = "wx-查询客户信息")
    @RequestMapping(value="/wx/customerInfo/{customerId}",method= RequestMethod.GET)
    public ResponseBean customerInfoGet(@PathVariable String customerId, @RequestHeader("authorization") String token){
        ResponseBean responseBean = new ResponseBean();
        try {
            LambdaQueryWrapper<CustomerInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(CustomerInfo::getCustomerId,customerId);

            CustomerInfo customerInfo = iCustomerInfoService.getOne(lambdaQueryWrapper);
            TaRecommendCustomer customer = iTaRecommendCustomerService.getById(customerId);
            if (null == customer) {
                return ResponseBean.error("请求客户不存在", ResponseBean.ERROR_UNAVAILABLE);
            }
            if (null == customerInfo) {
                customerInfo = new CustomerInfo();
            }
            customerInfo.setName(customer.getName());
            customerInfo.setSex(customer.getSex());
            customerInfo.setPhone(customer.getPhone());
            customerInfo.setPicture(customer.getPicture());

            responseBean.addSuccess(customerInfo);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("customerInfoDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param
     */
    @ApiOperation(value = "admin-查询客户信息", notes = "admin-查询客户信息")
    @RequestMapping(value="/admin/customerInfo/{customerId}",method= RequestMethod.GET)
    public ResponseBean customerInfoPc(@PathVariable String customerId, @RequestHeader("authorization") String token){
        ResponseBean responseBean = new ResponseBean();
        CustomerInfoVO customerInfoVO = new CustomerInfoVO();
        try {
            LambdaQueryWrapper<CustomerInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(CustomerInfo::getCustomerId,customerId);

            CustomerInfo customerInfo = iCustomerInfoService.getOne(lambdaQueryWrapper);

            TaRecommendCustomer customer = iTaRecommendCustomerService.getById(customerId);
            if (null == customerInfo && null == customer) {
                return ResponseBean.error("请求客户不存在", ResponseBean.ERROR_UNAVAILABLE);
            }
            // 查看置业顾问信息
            if (!StringUtils.isEmpty(customer.getRealtyConsultant())) {
                TaPerson realtyPerson = taPersonService.getById(customer.getRealtyConsultant());
                customerInfoVO.setRealtyConsultantPerson(realtyPerson);
                // 所属楼盘和 用户信息
                LambdaQueryWrapper<TaPersonBuilding> taPersonBuildingLambdaQueryWrapper = new LambdaQueryWrapper<>();
                taPersonBuildingLambdaQueryWrapper.eq(TaPersonBuilding::getPersonId,customer.getRealtyConsultant());
                List<TaPersonBuilding> list = taPersonBuildingService.list(taPersonBuildingLambdaQueryWrapper);
                if (list.size() > 0) {
                    TaUser taUser = taUserService.getById(list.get(0).getUserId());
                    customerInfoVO.setTaUser(taUser);
                    // 获取楼盘相关信息
                    LambdaQueryWrapper<TaBuilding> taBuildingLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    taBuildingLambdaQueryWrapper.in(TaBuilding::getBuildingId,list.stream().map(TaPersonBuilding::getBuildingId).collect(Collectors.toList()));
                    List<TaBuilding> taBuildingList = taBuildingService.list(taBuildingLambdaQueryWrapper);
                    customerInfoVO.setTaBuildingList(taBuildingList);
                }
            }

            // 获取渠道名字
            LambdaQueryWrapper<TaChannelPerson> channelPersonLambdaQueryWrapper = new LambdaQueryWrapper<>();
            channelPersonLambdaQueryWrapper.eq(TaChannelPerson::getPersonId,customer.getPersonId());
            TaChannelPerson taChannelPerson = taChannelPersonService.getOne(channelPersonLambdaQueryWrapper);
            if (null != taChannelPerson) {
                TaChannel taChannel = taChannelService.getById(taChannelPerson.getChannelId());
                customerInfoVO.setChannelName(taChannel.getChannelName());
            }

            customerInfoVO.setTaRecommendCustomer(customer);
            customerInfoVO.setCustomerInfo(customerInfo);
            iCustomerInfoService.getOtherInfo(customerInfoVO);
            responseBean.addSuccess(customerInfoVO);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("customerInfoDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
