package com.xtd.project.hkmanager.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xtd.framework.web.controller.BaseController;
import com.xtd.framework.web.domain.AjaxResult;
import com.xtd.framework.web.page.TableDataInfo;
import com.xtd.project.hkmanager.entity.Region;
import com.xtd.project.hkmanager.entity.RegionForm;
import com.xtd.project.hkmanager.entity.SynLog;
import com.xtd.project.hkmanager.service.RegionService;
import com.xtd.project.hkmanager.service.SynLogService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lym
 * @date 2020/4/10 11:20
 */
@RestController
@RequestMapping("/region")
@Api(description="设备管理")
public class RegionController extends BaseController {

    @Autowired
    RegionService regionService;
    @Autowired
    SynLogService synLogService;
    /**
     * 同步区域信息
     * @return
     */
    @ApiOperation(value = "同步区域信息",notes = "同步区域信息")
    @ApiResponse(code = 200,message = "操作成功")
    @GetMapping("/synRegion")
    public AjaxResult synRegion(Integer pageNo,Integer pageSize,Integer saveNum){
        if (saveNum == null){
            saveNum = 0;
        }

        //路径
        final String url = "/resource/v1/regions";
        Integer total = 0;

        //组装请求参数
        Map<String,Object> bodys = new HashMap<>();
        setPage(bodys,pageNo,pageSize);
        String body = JSON.toJSON(bodys).toString();
        //调用接口
        Object jsonObject = postSelect(url,body,null,null,null);
        if (jsonObject != null){ //查询到区域信息，同步区域信息
            Map json = (Map) jsonObject;
            total = (Integer) json.get("total");
            Object listData = json.get("list");
            int i = batchSave(listData);
            saveNum += i;

            pageNo = Integer.parseInt(bodys.get("pageNo").toString());
            pageSize = Integer.parseInt(bodys.get("pageSize").toString());
            if (total > (pageNo * pageSize)){
                return synRegion(pageNo + 1,pageSize,saveNum);
            }

            saveSynLog(saveNum);
            if (saveNum < 1){
                return AjaxResult.success("没有可同步区域信息");
            }
            return AjaxResult.success("成功同步"+ saveNum +"个区域信息");
        }

        return  AjaxResult.error();
    }

    /**
     * 批量插入区域信息
     * @param data
     * @return
     */
    public int batchSave(Object data){
        List<JSONObject> lists = (List<JSONObject>) data;
        Map<String,Region> map = new HashMap<>();
        Region region = null;
        for (JSONObject json: lists){
            region = new Region();
            String guid = json.get("indexCode").toString();
            region.setGuid(guid);
            region.setRegionName(json.get("name").toString());
            region.setParentId(json.get("parentIndexCode").toString());
            region.setCreateUser(getUserId());
            region.setFkOrgGuid(getDeptId());

            map.put(guid,region);
        }

        int i = 0;
        if (map.size() > 0){
            i = regionService.batchSave(map);
        }

        return i;
    }

    /**
     * 添加同步日志
     * @param saveNum
     */
    private void saveSynLog(Integer saveNum){
        SynLog synLog = new SynLog();
        synLog.setType(0);

        JSONObject json = new JSONObject();
        json.put("saveNum",saveNum);
        synLog.setLogData(json.toJSONString());
        synLog.setCreateUser(getUserId());
        synLogService.saveSelective(synLog);
    }

    /**
     * 查询列表
     * @param region
     * @return
     */
    @ApiOperation(value = "列表查询",notes = "列表查询")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "region",value = "区域信息",dataType = "RegionForm")
    )
    @ApiResponse(code = 200,message = "操作成功")
    @PostMapping("/selectList")
    public TableDataInfo selectList(@RequestBody RegionForm region){
        //region.setFkOrgGuid(getDeptId());
        List<Region> list = regionService.selectList(region);
        return getDataTable(list);
    }

    /**
     * 添加区域信息
     * @author lym
     */
    @ApiOperation(value = "添加区域信息",notes = "添加区域信息")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "region",value = "区域信息",dataType = "Region")
    )
    @ApiResponse(code = 200,message = "操作成功")
    @PostMapping("/save")
    public AjaxResult add(@RequestBody @Valid Region region){
        region.setCreateUser(getUserId());
        region.setFkOrgGuid(getDeptId());
        int i = regionService.saveSelective(region);
        if (i > 0){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * 修改区域信息
     * @param region
     * @return
     */
    @ApiOperation(value = "修改区域信息",notes = "修改区域信息")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "region",value = "区域信息",dataType = "Region")
    )
    @ApiResponse(code = 200,message = "操作成功")
    @PostMapping("/update")
    public AjaxResult update(@RequestBody @Valid Region region){
        region.setModifiedUser(getUserId());
        int i = regionService.modifyByPrimaryKeySelective(region);
        if (i > 0){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * 查询单个区域信息
     * @param guid
     * @return
     */
    @ApiOperation(value = "查询区域详细信息",notes = "查询区域详细信息")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "guid",value = "主键",dataType = "String")
    )
    @ApiResponse(code = 200,message = "操作成功")
    @GetMapping("/getById")
    public AjaxResult getById(@RequestParam("guid") String guid){
        Region region = regionService.queryByPrimaryKey(guid);
        return AjaxResult.success(region);
    }

    @ApiOperation(value = "删除区域信息",notes = "删除区域信息")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "guid",value = "主键",dataType = "String")
    )
    @ApiResponse(code = 200,message = "操作成功")
    @GetMapping("/delete")
    public AjaxResult delete(@RequestParam("guid") String guid){
        int i = regionService.delByPrimaryKey(guid);
        if (i > 0){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * 查询区域树
     * @param region
     * @return
     */
    @ApiOperation(value = "查询区域树",notes = "查询区域树")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "region",value = "区域信息",dataType = "RegionForm")
    )
    @ApiResponse(code = 200,message = "操作成功")
    @PostMapping("/selectTree")
    public AjaxResult selectTree(@RequestBody RegionForm region){
        //region.setFkOrgGuid(getDeptId());
        List<RegionForm> list = regionService.selectTree(region);
        return AjaxResult.success(list);
    }
}
