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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.DistrictInfo;
import com.jpsoft.shinestar.modules.base.entity.RegionInfo;
import com.jpsoft.shinestar.modules.base.entity.ReturnInfo;
import com.jpsoft.shinestar.modules.base.service.DistrictInfoService;
import com.jpsoft.shinestar.modules.base.service.RegionInfoService;
import com.jpsoft.shinestar.modules.base.service.ReturnInfoService;
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.service.DataDictionaryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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("/base/returnInfo")
@Api(description = "设备信息")
public class ReturnInfoController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ReturnInfoService returnInfoService;

    @Autowired
    private RegionInfoService regionInfoService;

    @Autowired
    private DistrictInfoService districtInfoService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

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

        ReturnInfo returnInfo = new ReturnInfo();

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

        return msgResult;
    }

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

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

            int affectCount = returnInfoService.insert(returnInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(returnInfo);
            } 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="获取信息")
    @GetMapping("edit/{id}")
    public MessageResult<ReturnInfo> edit(@PathVariable("id") String id){
        MessageResult<ReturnInfo> msgResult = new MessageResult<>();

        try {
            ReturnInfo returnInfo = returnInfoService.get(id);

            if (returnInfo != null) {
                msgResult.setResult(true);
                msgResult.setData(returnInfo);
            } 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<ReturnInfo> update(@RequestBody ReturnInfo returnInfo,@RequestAttribute String subject){
        MessageResult<ReturnInfo> msgResult = new MessageResult<>();

        try {
            returnInfo.setUpdateBy(subject);
            returnInfo.setUpdateTime(new Date());

            int affectCount = returnInfoService.update(returnInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(returnInfo);
            } 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("delete/{id}")
    public MessageResult<Integer> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            ReturnInfo returnInfo = returnInfoService.get(id);
            returnInfo.setDelFlag(true);
            returnInfo.setUpdateBy(subject);
            returnInfo.setUpdateTime(new Date());

            int affectCount = returnInfoService.update(returnInfo);

            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) {
                ReturnInfo returnInfo = returnInfoService.get(id);
                returnInfo.setDelFlag(true);
                returnInfo.setUpdateBy(subject);
                returnInfo.setUpdateTime(new Date());

                affectCount += returnInfoService.update(returnInfo);
            }

            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 name,String idCard,String phone,Boolean enableUpdate,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") 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("create_time","desc"));

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

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

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

        if (enableUpdate!=null) {
            searchParams.put("enableUpdate",enableUpdate);
        }

        Page<ReturnInfo> page = returnInfoService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);

        for (ReturnInfo returnInfo:page) {
            String regionId = returnInfo.getLiveRegionId();
            RegionInfo regionInfo = regionInfoService.get(regionId);
            returnInfo.setLiveRegionN(regionInfo.getFullName());

            String originId = returnInfo.getOriginId();
            DistrictInfo districtInfo = districtInfoService.get(originId);
            returnInfo.setOriginN(districtInfo.getFullName());

            String typeN = dataDictionaryService.findNameByCatalogNameAndValue("返乡类型",returnInfo.getType());
            returnInfo.setTypeN(typeN);
        }

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

        return msgResult;
    }
}
