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.entity.PunchLocation;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.base.service.PunchLocationService;
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.User;
import com.jpsoft.shinestar.modules.sys.service.UserService;
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.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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/punchLocation")
@Api(description = "punchLocation")
public class PunchLocationController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PunchLocationService punchLocationService;
    @Autowired
    private UserService userService;
    @Autowired
    private CompanyInfoService companyInfoService;

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

        PunchLocation punchLocation = new PunchLocation();

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

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

        try {
            punchLocation.setId(UUID.randomUUID().toString());
            punchLocation.setDelFlag(false);
            punchLocation.setIsEnable(false);
            punchLocation.setCreateBy(subject);
            punchLocation.setCreateTime(new Date());
            
            int affectCount = punchLocationService.insert(punchLocation);

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

        try {
            PunchLocation punchLocation = punchLocationService.get(id);

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

        try {
            punchLocation.setUpdateBy(subject);
            punchLocation.setUpdateTime(new Date());
            
            int affectCount = punchLocationService.update(punchLocation);

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

            int affectCount = punchLocationService.update(punchLocation);

            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) {
                PunchLocation punchLocation = punchLocationService.get(id);
                punchLocation.setDelFlag(true);
                punchLocation.setUpdateBy(subject);
                punchLocation.setUpdateTime(new Date());

                affectCount += punchLocationService.update(punchLocation);
            }

            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,
            @RequestParam(value="companyId",defaultValue="") String companyId,
            @RequestParam(value="name",defaultValue="") String name,
            @RequestParam(value="isEnable",defaultValue="") String isEnable,
            @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("b.sort_no","asc"));
        sortList.add(new Sort("a.create_time","asc"));

        //当前用户ID
        User user = userService.get(subject);
        CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());

        if (!userService.hasRole(subject,"SYSADMIN")) {
            String[] arr = companyInfo.getCode().split(",");
            searchParams.put("companyIds",  Arrays.asList(arr));
        }

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

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

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

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

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

        return msgResult;
    }

    @ApiOperation(value = "修改启用状态")
    @PostMapping("changeEnable")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "编号", required = false, paramType = "form", dataType = "String")
    })
    public MessageResult<Boolean> changeEnable(@RequestParam(value = "id", defaultValue = "") String id, @RequestAttribute String subject) {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        MessageResult<Boolean> msgResult = new MessageResult<>();
        msgResult.setData(true);

        try {
            PunchLocation punchLocation = punchLocationService.get(id);

            if (punchLocation.getIsEnable()) {
                punchLocation.setIsEnable(false);
            } else {
                if(StringUtils.isNotEmpty(punchLocation.getLatitude())) {
                    punchLocation.setIsEnable(true);
                }else{
                    throw new Exception("请先完成定位!");
                }
            }
            punchLocation.setUpdateBy(subject);
            punchLocation.setUpdateTime(new Date());

            int affectCount = punchLocationService.update(punchLocation);

            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;
    }
}
