package com.yunzhi.marketing.xlk.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunzhi.marketing.base.BaseController;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.xlk.dto.BuildingChannelDTO;
import com.yunzhi.marketing.xlk.entity.BuildingChannel;
import com.yunzhi.marketing.xlk.service.IBuildingChannelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
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.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
    * 楼盘渠道表  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2021-07-18
 */
@RestController
@RequestMapping("/api")
@Api(value = "楼盘渠道表", tags = "xlk-楼盘渠道表")
public class BuildingChannelController extends BaseController {

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

    @Autowired
    public IBuildingChannelService iBuildingChannelService;

    /**
     * 保存对象
     * @param buildingChannelDTO 实体对象
     * @return
     */
    @ApiOperation(value = "admin-保存楼盘渠道接口", notes = "admin-保存楼盘渠道接口")
    @RequestMapping(value="/admin/buildingChannel",method= RequestMethod.POST)
    public ResponseBean buildingChannelAdd(@RequestHeader("authorization") String token,
                                           @RequestBody BuildingChannelDTO buildingChannelDTO,
                                           HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            if (saveData(buildingChannelDTO, getOrgId(request))){
                responseBean.addSuccess("添加成功");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("buildingChannelAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     *
     * @return
     */
    @ApiOperation(value = "admin-修改楼盘渠道接口", notes = "admin-修改楼盘渠道接口")
    @RequestMapping(value="/admin/buildingChannel",method= RequestMethod.PUT)
    public ResponseBean buildingChannelUpdate(@RequestHeader("authorization") String token,
                                              @RequestBody BuildingChannelDTO buildingChannelDTO,
                                              HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            // 先把此楼盘的渠道全部删除
            iBuildingChannelService.remove(new LambdaQueryWrapper<BuildingChannel>().eq(BuildingChannel::getBuildingId,buildingChannelDTO.getBuildingId()));

            // 重新添加
            if (saveData(buildingChannelDTO, getOrgId(request))){
                responseBean.addSuccess("修改成功");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("buildingChannelUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    private boolean saveData(BuildingChannelDTO buildingChannelDTO, Integer orgId) {
        List<BuildingChannel> buildingChannelList = new ArrayList<>();
        List<String> channelIdList = buildingChannelDTO.getChannelIdList();
        channelIdList.forEach(e -> {
            BuildingChannel buildingChannel = new BuildingChannel();
            BeanUtils.copyProperties(e,buildingChannel);
            buildingChannel.setChannelId(e);
            buildingChannel.setBuildingId(buildingChannelDTO.getBuildingId());
            buildingChannel.setExpirationDate(buildingChannelDTO.getExpirationDate());
            buildingChannel.setRemark(buildingChannelDTO.getRemark());
            buildingChannel.setCreateDate(LocalDateTime.now());
            buildingChannel.setOrgId(orgId);
            buildingChannelList.add(buildingChannel);
        });

        return iBuildingChannelService.saveBatch(buildingChannelList);
    }

    /**
     * 根据id查询对象
     * @param
     */
    @ApiOperation(value = "admin-获取楼盘渠道详情接口", notes = "admin-获取楼盘渠道详情接口")
    @RequestMapping(value="/{plat}/buildingChannel/{buildingId}",method= RequestMethod.GET)
    public ResponseBean buildingChannelGet(@PathVariable String plat,
                                           @PathVariable String buildingId){
        ResponseBean responseBean = new ResponseBean();
        try {
            LambdaQueryWrapper<BuildingChannel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BuildingChannel::getBuildingId,buildingId);
            List<BuildingChannel> list = iBuildingChannelService.list(queryWrapper);

            BuildingChannelDTO buildingChannelDTO = null;
            if (list != null && list.size() > 0) {
                buildingChannelDTO = new BuildingChannelDTO();
                buildingChannelDTO.setChannelIdList(list.stream().map(x -> x.getChannelId()).collect(Collectors.toList()));
                buildingChannelDTO.setBuildingId(buildingId);
                buildingChannelDTO.setExpirationDate(list.get(0).getExpirationDate());
                buildingChannelDTO.setRemark(list.get(0).getRemark());
            }

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