package io.renren.modules.sys.controller;

import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.exception.RenException;
import io.renren.common.page.PageData;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sys.dto.BudgetDTO;
import io.renren.modules.sys.dto.LandingPagesDTO;
import io.renren.modules.sys.dto.ScopeCityCompanyDTO;
import io.renren.modules.sys.dto.ScopeCityDTO;
import io.renren.modules.sys.excel.LandingPagesExcel;
import io.renren.modules.sys.service.LandingPagesService;
import io.renren.modules.sys.service.ScopeCityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 落地页
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2022-05-28
 */
@RestController
@RequestMapping("sys/landingpages")
@Api(tags="落地页")
public class LandingPagesController {
    @Autowired
    private LandingPagesService landingPagesService;
    @Autowired
    private ScopeCityService scopeCityService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    @RequiresPermissions("sys:landingpages:page")
    public Result<PageData<LandingPagesDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<LandingPagesDTO> page = landingPagesService.page(params);
        return new Result<PageData<LandingPagesDTO>>().ok(page);
    }

    @GetMapping("list")
    @ApiOperation("落地页列表")
    public Result<List<LandingPagesDTO>> list(){
        List<LandingPagesDTO> list = landingPagesService.list(new HashMap<>());
        return new Result<List<LandingPagesDTO>>().ok(list);
        //return new Result<List<LandingPagesDTO>>().ok(landingPagesService.getPagesListByUser());
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("sys:landingpages:info")
    public Result<LandingPagesDTO> get(@PathVariable("id") Long id){
        LandingPagesDTO data = landingPagesService.get(id);

        return new Result<LandingPagesDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("sys:landingpages:save")
    public Result save(@RequestBody LandingPagesDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        //名称 唯一性校验
        Map<String,Object> params = new HashMap<>();
        params.put("name",dto.getName()+"");
        List<LandingPagesDTO> repeatList = landingPagesService.list(params);
        if (!CollectionUtils.isEmpty(repeatList)){
            throw new RenException("落地页名称已存在");
        }
        params = new HashMap<>();
        params.put("url",dto.getUrl()+"");
        List<LandingPagesDTO> repeatUrlList = landingPagesService.list(params);
        if (!CollectionUtils.isEmpty(repeatUrlList)){
            throw new RenException("页面地址已存在");
        }
        UserDetail userDetail = SecurityUser.getUser();
        dto.setCreateBy(userDetail.getId());
//        dto.setUpdateBy(userDetail.getId());
        dto.setCreateTime(new Date());
//        dto.setUpdateTime(new Date());
        landingPagesService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("sys:landingpages:update")
    public Result update(@RequestBody LandingPagesDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        //名称 唯一性校验
        Map<String,Object> params = new HashMap<>();
        params.put("name",dto.getName()+"");
        List<LandingPagesDTO> repeatList = landingPagesService.list(params);
        if (!CollectionUtils.isEmpty(repeatList)){
            for (LandingPagesDTO landingPagesDTO:repeatList){
                if (landingPagesDTO.getId().longValue()!=dto.getId().longValue()){
                    throw new RenException("落地页名称已存在");
                }
            }
        }
        params = new HashMap<>();
        params.put("url",dto.getUrl()+"");
        List<LandingPagesDTO> repeatUrlList = landingPagesService.list(params);
        if (!CollectionUtils.isEmpty(repeatUrlList)){
            for (LandingPagesDTO landingPagesDTO:repeatUrlList){
                if (landingPagesDTO.getId().longValue()!=dto.getId().longValue()){
                    throw new RenException("页面地址已存在");
                }
            }
        }
        UserDetail userDetail = SecurityUser.getUser();
        dto.setUpdateBy(userDetail.getId());
        dto.setUpdateTime(new Date());

        landingPagesService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("sys:landingpages:delete")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        UserDetail userDetail = SecurityUser.getUser();
        for (Long id:ids){
            LandingPagesDTO dto = landingPagesService.get(id);
            //判断落地页是否被落地城市绑定
            Map<String,Object> param = new HashMap<>();
            param.put("pageId",id+"");
            List<ScopeCityDTO> bindList = scopeCityService.list(param);
            if (!CollectionUtils.isEmpty(bindList)){
                throw new RenException(dto.getName()+"已经被落地城市绑定，无法直接删除");
            }
            dto.setDeleteTime(new Date());
            dto.setStatus(0);
            dto.setUpdateBy(userDetail.getId());
            landingPagesService.update(dto);
        }

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("sys:landingpages:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<LandingPagesDTO> list = landingPagesService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, list, LandingPagesExcel.class);
    }

}