package com.bocloud.ims.booter.controller.resource;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.bocloud.ims.booter.annotation.ShowBindingBusiness;
import com.bocloud.ims.entity.common.Column;
import com.bocloud.ims.interfaces.resource.ExtFileDownLoadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import com.bocloud.cmp.model.SubnetParam;
import com.bocloud.common.annotations.Log;
import com.bocloud.common.enums.BoCloudService;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.GridBean;
import com.bocloud.common.model.Pager;
import com.bocloud.common.model.RequestContext;
import com.bocloud.common.utils.Common;
import com.bocloud.ims.entity.resource.Subnet;
import com.bocloud.ims.interfaces.resource.SubnetService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/v1/subnets")
@Api(value = "子网管理", tags = "子网管理")
public class SubnetController {

    @Autowired
    private SubnetService subnetService;
    private ExtFileDownLoadService extFileDownLoadService;

    /**
     * 列表
     *
     * @param pager
     * @return
     */
    @ShowBindingBusiness
    @ApiOperation(tags = {"CMC", "CSC"}, value = "查询子网列表", httpMethod = "GET")
    @Log(module = BoCloudService.IMS, target = "子网", operation = "查询子网列表")
    @GetMapping
    public BocloudResult<GridBean<Subnet>> list(Pager pager) {
        return subnetService.list(pager);
    }

    /**
     * 根据condition查询子网列表
     *
     * @param condition
     * @return
     */
    @ApiOperation(tags = {"CMC", "CSC"}, value = "根据condition查询子网列表", httpMethod = "GET")
    @Log(module = BoCloudService.IMS, target = "子网", operation = "查询子网列表")
    @GetMapping("/condition")
    public BocloudResult<List<Subnet>>
        condition(@RequestParam(value = Common.CONDITION, required = false) String condition) {
        return subnetService.condition(condition);
    }

    /**
     * 创建
     *
     * @param params
     * @param context
     * @return
     */
    @ApiOperation(tags = {"CMC", "CSC"}, value = "创建子网", httpMethod = "POST")
    @Log(module = BoCloudService.IMS, target = "子网", operation = "创建子网")
    @PostMapping
    public BocloudResult create(@RequestBody Subnet subnet, @Value(Common.REQ_CONTEXT) RequestContext context) {
        return subnetService.create(subnet, context);
    }

    /**
     * 修改
     *
     * @param id
     * @param params
     * @param context
     * @return
     */
    @ApiOperation(tags = {"CMC", "CSC"}, value = "修改子网", httpMethod = "PUT")
    @Log(module = BoCloudService.IMS, target = "子网", operation = "修改子网")
    @PutMapping(value = "/{id}")
    public BocloudResult<String> modify(@PathVariable(value = Common.ID) Long id, @RequestBody Subnet subnet,
        @Value(Common.REQ_CONTEXT) RequestContext context) {
        subnet.setId(id);
        return subnetService.modify(subnet, context);
    }

    /**
     * 删除
     *
     * @param id
     * @param context
     * @return
     */
    @ApiOperation(tags = {"CMC", "CSC"}, value = "删除子网", httpMethod = "DELETE")
    @Log(module = BoCloudService.IMS, target = "子网", operation = "删除子网")
    @DeleteMapping(value = "/{id}")
    public BocloudResult<String> remove(@PathVariable(value = Common.ID) Long id,
        @Value(Common.REQ_CONTEXT) RequestContext context) {
        return subnetService.remove(id, context);
    }

    /**
     * 批量删除子网
     *
     * @param params
     * @param context
     * @return
     */
    @ApiOperation(tags = {"CMC", "CSC"}, value = "删除子网", httpMethod = "DELETE")
    @Log(module = BoCloudService.IMS, target = "子网", operation = "批量删除子网")
    @DeleteMapping
    public BocloudResult<String> batchRemove(@RequestBody List<Long> ids,
        @Value(Common.REQ_CONTEXT) RequestContext context) {
        return subnetService.batchRemove(ids, context);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @ApiOperation(tags = {"CMC", "CSC"}, value = "查看子网详情", httpMethod = "GET")
    @Log(module = BoCloudService.IMS, target = "子网", operation = "查看子网详情")
    @GetMapping(value = "/{id}")
    public BocloudResult<Subnet> detail(@PathVariable(value = Common.ID) Long id) {
        return subnetService.detail(id);
    }

    /**
     * 子网操作类
     *
     * @param id
     * @param params
     * @param context
     * @param action
     * @return
     */
    @ApiOperation(value = "子网操作", response = BocloudResult.class, httpMethod = "PATCH",
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Log(module = BoCloudService.IMS, target = "子网", operation = "子网操作")
    @PatchMapping(value = "/{id}/operation")
    public BocloudResult operation(@PathVariable(value = Common.ID) Long id, @RequestBody SubnetParam subnetParam,
        @Value(Common.REQ_CONTEXT) RequestContext context) {
        return subnetService.operations(id, subnetParam, context);
    }

    /**
     * 子网更换路由表
     *
     * @param id
     * @param params
     * @param context
     * @param action
     * @return
     */
    @ApiOperation(value = "子网更换路由表", response = BocloudResult.class, httpMethod = "PATCH",
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Log(module = BoCloudService.IMS, target = "子网", operation = "子网操子网更换路由表作")
    @PatchMapping(value = "/{id}/routetable/{routeTableId}")
    public BocloudResult associate(@PathVariable(value = Common.ID) Long id,
        @PathVariable(value = "routeTableId") Long routeTableId, @Value(Common.REQ_CONTEXT) RequestContext context) {
        return subnetService.updateRouteTable(id, routeTableId, context);
    }

    /**
     * 导出vpc列表
     *
     * @return
     */
    @ApiOperation(tags = {"CMC", "CSC"}, value = "导出vpc列表", httpMethod = "GET")
    @Log(module = BoCloudService.IMS, target = "vpc", operation = "导出vpc列表")
    @GetMapping("/download")
    public BocloudResult download(@RequestParam(value = "columnStr") String columnStr, Pager pager,
                                  @RequestParam(value = Common.CONDITION, required = false) String condition,
                                  @Value(Common.REQ_CONTEXT) RequestContext context, HttpServletRequest request, HttpServletResponse response) {
        List<Column> columns = JSONArray.parseArray(columnStr).toJavaList(Column.class);
        BocloudResult<Map<String, Object>> bocloudResult =
                extFileDownLoadService.vmDownload(pager, condition, columns, context, "subnet");
        if (bocloudResult.isSuccess()) {
            String content;
            try {
                Map<String, Object> result = bocloudResult.getData();
                String fileName = result.get("fileName").toString();
                if (fileName.contains("pdf")) {
                    response.setContentType("application/pdf");
                } else {
                    response.setContentType("application/vnd.ms-excel");
                }
                final String userAgent = request.getHeader("user-agent").toLowerCase();
                if (userAgent.contains("trident") || userAgent.contains("edge")) {
                    fileName = URLEncoder.encode(fileName, "UTF-8");
                } else {
                    fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
                }
                response.setCharacterEncoding("utf-8");
                response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
                OutputStream outputStream = response.getOutputStream();
                content = (String)result.get("data");
                if (content != null) {
                    byte[] bytes = Base64.getDecoder().decode(content);
                    outputStream.write(bytes);
                    outputStream.close();
                }
            } catch (Exception e) {
                return new BocloudResult(false, "内部错误");
            }
        }
        return bocloudResult;
    }

}
