package com.jpsoft.shinestar.modules.business.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.business.entity.FillAttendance;
import com.jpsoft.shinestar.modules.business.service.FillAttendanceService;
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.DataDictionaryService;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/business/fillAttendance")
@Api(description = "fillAttendance")
public class FillAttendanceController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private FillAttendanceService fillAttendanceService;

    @Autowired
    private UserService userService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

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

        FillAttendance fillAttendance = new FillAttendance();

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

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

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

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

        try {
            FillAttendance fillAttendance = fillAttendanceService.get(id);

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

        try {
            fillAttendance.setUpdateBy(subject);
            fillAttendance.setUpdateTime(new Date());
            
            int affectCount = fillAttendanceService.update(fillAttendance);

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

            int affectCount = fillAttendanceService.update(fillAttendance);

            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) {
                FillAttendance fillAttendance = fillAttendanceService.get(id);
                fillAttendance.setDelFlag(true);
                fillAttendance.setUpdateBy(subject);
                fillAttendance.setUpdateTime(new Date());

                affectCount += fillAttendanceService.update(fillAttendance);
            }

            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="列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "personName", value =  "申请人姓名", required = false, paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "type", value = "类型", required = false, paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "status", value = "状态", required = false, paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "parentId",value = "上级企业ID", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "subordinate",value = "是否查询下级单位", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "fillDay",value = "补卡日", required = false, paramType = "form",dataType = "String"),
    })
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String id,
            @RequestParam(value="personName",defaultValue="") String personName,
            @RequestParam(value="type",defaultValue="") String type,
            @RequestParam(value="status",defaultValue="") String status,
            @RequestParam(value="parentId",defaultValue="")  String parentId,
            @RequestParam(value="startTime",defaultValue="")  String startTime,
            @RequestParam(value="endTime",defaultValue="")  String endTime,
            @RequestParam(value="subordinate",defaultValue="false")  Boolean subordinate,
            @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"));

        //系统管理员
        boolean sysAdmin = userService.hasRole(subject,"SYSADMIN");

        if(!sysAdmin){
            User user = userService.get(subject);
            String companyId = user.getCompanyId();
            CompanyInfo companyInfo = companyInfoService.get(companyId);
            searchParams.put("companyCode", companyInfo.getCode() + "%");
        }

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

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

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

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

        if(StringUtils.isNotEmpty(parentId)){
            CompanyInfo parentCompanyInfo = companyInfoService.get(parentId);

            String parentCode = parentCompanyInfo.getCode();

            if (StringUtils.isEmpty(parentCode)){
                if (!userService.hasRole(subject,"SYSADMIN")) {
                    searchParams.put("companyCode", parentCode + "%");
                }
            }
            else{
                if(subordinate){
                    searchParams.put("companyCode", parentCode + "%");
                }
                else {
                    searchParams.put("companyCode", parentCode);
                }
            }
        }

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

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

        Page<FillAttendance> page = fillAttendanceService.pageSearch(searchParams,pageIndex,pageSize,sortList);
        for(FillAttendance fillAttendance : page.getResult()){
            String typeN = dataDictionaryService.findNameByCatalogNameAndValue("补卡类型",fillAttendance.getType());
            fillAttendance.setTypeN(typeN);

            if(StringUtils.isNotEmpty(fillAttendance.getStatus())){
                if(fillAttendance.getStatus().equals("0")){
                    fillAttendance.setStatusN("审核中");
                }
                else if(fillAttendance.getStatus().equals("1")){
                    fillAttendance.setStatusN("同意");
                }
                else if(fillAttendance.getStatus().equals("2")){
                    fillAttendance.setStatusN("拒绝");
                }
            }

        }

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

        return msgResult;
    }


    @ApiOperation(value="异地打卡记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "personName", value = "申请人姓名", required = false, paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "请假开始日期",required = false, paramType = "form"),
            @ApiImplicitParam(name = "endTime", value = "请假结束日期",required = false, paramType = "form"),
            @ApiImplicitParam(name = "status", value = "状态", required = false, paramType = "form", dataType = "String"),
    })
    @RequestMapping(value = "clockPageList",method = RequestMethod.POST)
    public MessageResult<Map> clockPageList(
            @RequestParam(value="personName",defaultValue="") String personName,
            String startTime,
            String endTime,
            @RequestParam(value="status",defaultValue="") String status,
            @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"));

        //系统管理员
        boolean sysAdmin = userService.hasRole(subject,"SYSADMIN");

        if(!sysAdmin){
            User user = userService.get(subject);
            CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
            searchParams.put("bindCompanyCode",companyInfo.getCode()  + "%");
        }


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

        searchParams.put("type","1");

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

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


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


        Page<FillAttendance> page = fillAttendanceService.pageSearch(searchParams,pageIndex,pageSize,sortList);
        for(FillAttendance fillAttendance : page.getResult()){

            if(StringUtils.isNotEmpty(fillAttendance.getStatus())){
                if(fillAttendance.getStatus().equals("0")){
                    fillAttendance.setStatusN("审核中");
                }
                else if(fillAttendance.getStatus().equals("1")){
                    fillAttendance.setStatusN("同意");
                }
                else if(fillAttendance.getStatus().equals("2")){
                    fillAttendance.setStatusN("拒绝");
                }
            }

        }

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

        return msgResult;
    }
}
