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.StringUtils;
import com.yunzhi.marketing.entity.TaBuilding;
import com.yunzhi.marketing.service.ITaBuildingService;
import com.yunzhi.marketing.xlk.dto.BrandDTO;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yunzhi.marketing.xlk.service.IBrandService;
import com.yunzhi.marketing.xlk.entity.Brand;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * <p>
    * 品牌开发商表  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2021-05-13
 */
@RestController
@RequestMapping("/api")
@Api(value = "品牌开发商表", tags = "xlk-品牌开发商表")
public class BrandController extends BaseController {

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

    @Autowired
    public IBrandService iBrandService;

    @Autowired
    private ITaBuildingService taBuildingService;


    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "admin-品牌开发商表列表", notes = "admin-品牌开发商表列表")
    @RequestMapping(value="/{plat}/brand",method= RequestMethod.GET)
    public ResponseBean brandList(@PathVariable String plat,
                                  @RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                  @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                  @RequestParam(value ="brandName",required = false) String brandName,
                                  @RequestHeader("authorization") String token,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
		    IPage<Brand> pg = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<Brand> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Brand::getOrgId,getOrgId(request));
            queryWrapper.like(!StringUtils.isEmpty(brandName),Brand::getBrandName,brandName);
            queryWrapper.orderByDesc(Brand::getCreatedTime);

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

    /**
     * 保存对象
     * @param brandDTO 实体对象
     * @return
     */
    @ApiOperation(value = "admin-添加品牌开发商表", notes = "admin-添加品牌开发商表")
    @RequestMapping(value="/admin/brand",method= RequestMethod.POST)
    public ResponseBean brandAdd(@RequestBody BrandDTO brandDTO, @RequestHeader("authorization") String token, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            Brand brand = new Brand();
            BeanUtils.copyProperties(brandDTO,brand);
            brand.setCreatedTime(LocalDateTime.now());
            brand.setCreatedBy(getUserId(request));
            brand.setOrgId(getOrgId(request));
            if (iBrandService.save(brand)){
                responseBean.addSuccess(brand);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("brandAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ApiOperation(value = "admin-删除品牌开发商表", notes = "admin-删除品牌开发商表")
    @RequestMapping(value="/admin/brand/{id}", method= RequestMethod.DELETE)
    public ResponseBean brandDelete(@PathVariable String id, @RequestHeader("authorization") String token){
        ResponseBean responseBean = new ResponseBean();
        try {
            if(iBrandService.removeById(id)){
                // 同时更新项目里面的品牌商id和name为空
                LambdaQueryWrapper<TaBuilding> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(TaBuilding::getBrandId,id);
                List<TaBuilding> list = taBuildingService.list(queryWrapper);
                list.forEach(e -> {
                    e.setBrandId(null);
                    e.setBrandName(null);
                    taBuildingService.updateById(e);
                });
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("brandDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param brandDTO 实体对象
     * @return
     */
    @ApiOperation(value = "admin-修改品牌开发商表", notes = "admin-修改品牌开发商表")
    @RequestMapping(value="/admin/brand/{id}",method= RequestMethod.PUT)
    public ResponseBean brandUpdate(@PathVariable("id") String id,@RequestBody BrandDTO brandDTO,@RequestHeader("authorization") String token,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            Brand brand = new Brand();
            BeanUtils.copyProperties(brandDTO,brand);
            brand.setBrandId(id);
            brand.setUpdatedBy(getUserId(request));
            brand.setUpdatedTime(LocalDateTime.now());
            if (iBrandService.updateById(brand)){
                // 同时更新项目里面的品牌商id和name为更新后的名称
                LambdaQueryWrapper<TaBuilding> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(TaBuilding::getBrandId,brand.getBrandId());
                List<TaBuilding> list = taBuildingService.list(queryWrapper);
                list.forEach(e -> {
                    e.setBrandName(brand.getBrandName());
                    taBuildingService.updateById(e);
                });
                responseBean.addSuccess(brand);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("brandUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @ApiOperation(value = "admin-获取品牌开发商表详情数据", notes = "admin-获取品牌开发商表详情数据")
    @RequestMapping(value="/{plat}/brand/{id}",method= RequestMethod.GET)
    public ResponseBean brandGet(@PathVariable String plat,
                                 @PathVariable String id,
                                 @RequestHeader("authorization") String token){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iBrandService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("brandDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
