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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.CompanyInfo;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.base.entity.AddressInfo;
import com.jpsoft.shinestar.modules.base.service.AddressInfoService;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.mapping.ResultMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/base/addressInfo")
public class AddressInfoController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private AddressInfoService addressInfoService;

    @Autowired
    private UserService userService;

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

        AddressInfo addressInfo = new AddressInfo();

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

        return msgResult;
    }

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

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

            User curUser = userService.get(subject);

            if(curUser!=null){
                addressInfo.setCompanyId(curUser.getCompanyId());
            }

            int affectCount = addressInfoService.insert(addressInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(addressInfo);
            } 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<AddressInfo> detail(@PathVariable("id") String id){
        MessageResult<AddressInfo> msgResult = new MessageResult<>();

        try {
            AddressInfo addressInfo = addressInfoService.get(id);

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

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

            int affectCount = addressInfoService.update(addressInfo);

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

        try {
            AddressInfo addressInfo = addressInfoService.get(id);
            addressInfo.setDelFlag(true);
            addressInfo.setUpdateBy(subject);
            addressInfo.setUpdateTime(new Date());

            int affectCount = addressInfoService.update(addressInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
            } 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) {
                AddressInfo addressInfo = addressInfoService.get(id);
                addressInfo.setDelFlag(true);
                addressInfo.setUpdateBy(subject);
                addressInfo.setUpdateTime(new Date());

                affectCount += addressInfoService.update(addressInfo);
            }

            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,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            HttpServletRequest request){
        String subject = (String)request.getAttribute("subject");

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

        User curUser = userService.get(subject);

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

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

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("create_time","desc"));

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

        if(StringUtils.isNotEmpty(curUser.getCompanyId())){
            searchParms.put("companyId",curUser.getCompanyId());
        }
        else{
            searchParms.put("companyId","-1");
        }

        Page<AddressInfo> page = addressInfoService.pageSearch(searchParms,pageIndex,pageSize,sortList);

        for (AddressInfo addressInfo:page) {
            User user = userService.get(addressInfo.getCreateBy());
            if(user!=null){
                addressInfo.setCreateByN(user.getRealName());
            }
        }

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

        return msgResult;
    }


    @ApiOperation(value="列表")
    @RequestMapping(value = "list",method = RequestMethod.POST)
    public MessageResult<List<AddressInfo>> list(HttpServletRequest request){
        String subject = (String)request.getAttribute("subject");

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

        User curUser = userService.get(subject);

        MessageResult<List<AddressInfo>> msgResult = new MessageResult<>();

        List<AddressInfo> list = addressInfoService.list(curUser.getCompanyId());

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

        return msgResult;
    }
}
