package com.jpsoft.shinestar.modules.sys.controller;

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.sys.entity.DataDictionary;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/sys/dataDictionary")
@Api(description = "数据字典")
public class DataDictionaryController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @ApiOperation(value="创建空记录")
    @GetMapping("create")
    public MessageResult<DataDictionary> create(){
        MessageResult<DataDictionary> msgResult = new MessageResult<>();

        DataDictionary dataDictionary = new DataDictionary();

        msgResult.setData(dataDictionary);
        msgResult.setResult(true);

        return msgResult;
    }

    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<DataDictionary> add(@RequestBody DataDictionary dataDictionary,@RequestAttribute String subject){
        MessageResult<DataDictionary> msgResult = new MessageResult<>();

        try {
            dataDictionary.setId(UUID.randomUUID().toString());
            dataDictionary.setDelFlag(false);
            dataDictionary.setCreateBy(subject);
            dataDictionary.setCreateDate(new Date());

            int affectCount = dataDictionaryService.insert(dataDictionary);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(dataDictionary);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("添加失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage("添加失败");
        }

        return msgResult;
    }

    @ApiOperation(value="获取信息")
    @GetMapping("edit/{id}")
    public MessageResult<DataDictionary> edit(@PathVariable("id") String id){
        MessageResult<DataDictionary> msgResult = new MessageResult<>();

        try {
            DataDictionary dataDictionary = dataDictionaryService.get(id);

            if (dataDictionary != null) {
                msgResult.setResult(true);
                msgResult.setData(dataDictionary);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("不存在该记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="更新用户")
    @PostMapping("update")
    public MessageResult<DataDictionary> update(@RequestBody DataDictionary dataDictionary,@RequestAttribute String subject){
        MessageResult<DataDictionary> msgResult = new MessageResult<>();

        try {
            dataDictionary.setUpdateBy(subject);
            dataDictionary.setUpdateDate(new Date());

            int affectCount = dataDictionaryService.update(dataDictionary);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(dataDictionary);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("更新失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage("更新失败");
        }

        return msgResult;
    }

    @ApiOperation(value="删除")
    @PostMapping("delete/{id}")
    public MessageResult<Integer> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            DataDictionary dataDictionary = dataDictionaryService.get(id);
            dataDictionary.setDelFlag(true);
            dataDictionary.setUpdateBy(subject);
            dataDictionary.setUpdateDate(new Date());

            int affectCount = dataDictionaryService.update(dataDictionary);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value="批量删除")
    @PostMapping("batchDelete")
    public MessageResult<Integer> batchDelete(@RequestBody List<String> idList,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            for (String id : idList) {
                DataDictionary dataDictionary = dataDictionaryService.get(id);
                dataDictionary.setDelFlag(true);
                dataDictionary.setUpdateBy(subject);
                dataDictionary.setUpdateDate(new Date());

                affectCount += dataDictionaryService.update(dataDictionary);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String id,
            String name,
            String parentId,
            @RequestParam(name="pageIndex",defaultValue = "1") int pageIndex,
            @RequestParam(name="pageSize",defaultValue = "10") int pageSize,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);

        MessageResult<Map> msgResult = new MessageResult<>();

        Map<String,Object> searchParams = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("sort_no","asc"));

        if (StringUtils.isNotEmpty(parentId)) {
            searchParams.put("parentId",parentId);
        }

        if (StringUtils.isNotEmpty(id)) {
            searchParams.put("id",id);
        }

        if (StringUtils.isNotEmpty(name)) {
            searchParams.put("name","%" + name + "%");
        }

        Page<DataDictionary> page = dataDictionaryService.pageSearch(searchParams,pageIndex, pageSize,sortList);

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;
    }

    @ApiOperation(value = "查询")
    @RequestMapping(value = "query", method = RequestMethod.POST)
    public MessageResult<List> query(
            String keywords,
            String excludeId,
            @RequestParam(value = "dataType", defaultValue = "null") String dataType,
            @RequestParam(value = "limit", defaultValue = "20") int limit,
            @RequestAttribute String subject) {
        MessageResult<List> msgResult = new MessageResult<>();

        Map<String, Object> searchParams = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("a.sort_no", "asc"));

        if (StringUtils.isNotEmpty(keywords)) {
            searchParams.put("name", "%" + keywords + "%");
        }

        if (StringUtils.isNotEmpty(excludeId)) {
            searchParams.put("excludeId", excludeId);
        }

        if (StringUtils.isNotEmpty(dataType)) {
            //1查目录-2查值
            searchParams.put("dataType", dataType);
        }


        Page<DataDictionary> page = dataDictionaryService.pageSearch(searchParams,0, limit,sortList);
        List<DataDictionary> dataDictionaryList = page.getResult();
        msgResult.setResult(true);
        msgResult.setData(dataDictionaryList);

        return msgResult;
    }


    @ApiOperation(value = "查询字典")
    @RequestMapping(value = "queryChildren", method = RequestMethod.POST)
    public MessageResult<List> queryChildren(
            @RequestParam(value = "parentId", defaultValue = "") String parentId,
            @RequestAttribute String subject) {
        MessageResult<List> msgResult = new MessageResult<>();

        List<Map<String, Object>> dataDictionaryList = dataDictionaryService.queryChildren(parentId);
        msgResult.setResult(true);
        msgResult.setData(dataDictionaryList);
        return msgResult;
    }

    @PostMapping("findByCatalogName")
    @ApiOperation(value = "根据目录名称查询数据列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "catalogName",value = "数据目录名称", required = true, paramType = "form",dataType = "String"),
    })
    public MessageResult<List> findByCatalogName(String catalogName){
        MessageResult<List> messageResult = new MessageResult<>();

        try {
            //todo
            List<DataDictionary> list = dataDictionaryService.findByCatalogName(catalogName);
            messageResult.setData(list);

            messageResult.setResult(true);
        }
        catch (Exception ex){
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }
}
