package io.renren.modules.sys.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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.redis.RedisUtils;
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.ScopeCityCompanyDTO;
import io.renren.modules.sys.dto.ScopeCityDTO;
import io.renren.modules.sys.excel.ScopeCityExcel;
import io.renren.modules.sys.service.ScopeCityCompanyService;
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 springfox.documentation.annotations.ApiIgnore;


/**
 * 落地城市主表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2022-05-28
 */
@RestController
@RequestMapping("sys/scopecity")
@Api(tags="落地城市主表")
public class ScopeCityController {
    @Autowired
    private ScopeCityService scopeCityService;
    @Autowired
    private ScopeCityCompanyService scopeCityCompanyService;
    @Autowired
	private RedisTemplate<String, Object> redisTemplate;

    @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:scopecity:page")
    public Result<PageData<ScopeCityDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<ScopeCityDTO> page = scopeCityService.page(params);

        return new Result<PageData<ScopeCityDTO>>().ok(page);
    }

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

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

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

        //落地页+城市 唯一性校验
        Map<String,Object> params = new HashMap<>();
        params.put("city",dto.getCity()+"");
        params.put("pageId",dto.getPageId()+"");
        List<ScopeCityDTO> repeatList = scopeCityService.list(params);
        if (!CollectionUtils.isEmpty(repeatList)){
            throw new RenException("记录已存在");
        }

        UserDetail userDetail = SecurityUser.getUser();
        dto.setCreateBy(userDetail.getId());
//        dto.setUpdateBy(userDetail.getId());
        dto.setCreateTime(new Date());
//        dto.setUpdateTime(new Date());
        scopeCityService.save(dto);

        return new Result();
    }

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

        //落地页+城市 唯一性校验
        Map<String,Object> params = new HashMap<>();
        params.put("city",dto.getCity()+"");
        params.put("pageId",dto.getPageId()+"");
        List<ScopeCityDTO> repeatList = scopeCityService.list(params);
        if (!CollectionUtils.isEmpty(repeatList)){
            for (ScopeCityDTO scopeCityDTO:repeatList){
                if (scopeCityDTO.getId().longValue()!=dto.getId().longValue()){
                    throw new RenException("记录已存在");
                }
            }
        }

        UserDetail userDetail = SecurityUser.getUser();
        dto.setUpdateBy(userDetail.getId());
        dto.setUpdateTime(new Date());
        scopeCityService.update(dto);
        
        redisTemplate.delete(Constant.SCOPE_CITY_KEY+dto.getId());

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("sys:scopecity:delete")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        UserDetail userDetail = SecurityUser.getUser();
        for (Long id:ids){
            ScopeCityDTO dto = scopeCityService.get(id);
            //判断落地城市是否被公司绑定
            Map<String,Object> param = new HashMap<>();
            param.put("scopeCityId",id+"");
            List<ScopeCityCompanyDTO> bindList = scopeCityCompanyService.list(param);
            if (!CollectionUtils.isEmpty(bindList)){
                throw new RenException("落地页【"+dto.getPageName()+"】"+",城市【"+dto.getCity()+"】已经被公司绑定，无法直接删除");
            }
            dto.setDeleteTime(new Date());
            dto.setStatus(0);
            dto.setUpdateBy(userDetail.getId());
            scopeCityService.update(dto);
            
            redisTemplate.delete(Constant.SCOPE_CITY_KEY+id);
        }

        return new Result();
    }

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

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

}