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

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.PersonInfo;
import com.jpsoft.shinestar.modules.base.entity.PersonRoleInfo;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonRoleInfoService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.base.entity.RolePersonCheckOn;
import com.jpsoft.shinestar.modules.base.service.RolePersonCheckOnService;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
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/rolePersonCheckOn")
public class RolePersonCheckOnController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RolePersonCheckOnService rolePersonCheckOnService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private PersonRoleInfoService personRoleInfoService;

    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<RolePersonCheckOn> add(@ModelAttribute RolePersonCheckOn rolePersonCheckOn){
        MessageResult<RolePersonCheckOn> msgResult = new MessageResult<>();

        try {
            rolePersonCheckOn.setId(UUID.randomUUID().toString());

            int affectCount = rolePersonCheckOnService.insert(rolePersonCheckOn);

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

        try {
            String[] idArray = id.split(",");

            List<PersonInfo> personInfoList = new ArrayList<>();

            RolePersonCheckOn rolePersonCheckOn = new RolePersonCheckOn();

            for (String item:idArray) {
                PersonInfo personInfo = personInfoService.get(Long.parseLong(item));
                if(personInfo!=null){
                    personInfoList.add(personInfo);
                    rolePersonCheckOn = rolePersonCheckOnService.findByPersonId(item);
                    if(rolePersonCheckOn == null){
                        rolePersonCheckOn = new RolePersonCheckOn();
                    }
                    else{
                        if(rolePersonCheckOn.getCheckOnCountFlag()&&StringUtils.isNotEmpty(rolePersonCheckOn.getCheckOnCount())){
                            JSONObject jsonObject = JSONUtil.parseObj(rolePersonCheckOn.getCheckOnCount());
                            rolePersonCheckOn.setCome(jsonObject.get("come").toString());
                            rolePersonCheckOn.setOut(jsonObject.get("out").toString());
                        }
                    }
                    rolePersonCheckOn.setPersonInfoList(personInfoList);
                }
            }

            msgResult.setResult(true);
            msgResult.setData(rolePersonCheckOn);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

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

        try {
            String[] idArray = id.split(",");

            List<PersonRoleInfo> personRoleInfoList = new ArrayList<>();

            RolePersonCheckOn rolePersonCheckOn = new RolePersonCheckOn();

            for (String item:idArray) {
                PersonRoleInfo personRoleInfo = personRoleInfoService.get(item);
                if(personRoleInfo!=null){
                    personRoleInfoList.add(personRoleInfo);
                    rolePersonCheckOn = rolePersonCheckOnService.findByRoleId(item);
                    if(rolePersonCheckOn == null){
                        rolePersonCheckOn = new RolePersonCheckOn();
                    }
                    else{
                        if(rolePersonCheckOn.getCheckOnCountFlag()&&StringUtils.isNotEmpty(rolePersonCheckOn.getCheckOnCount())){
                            JSONObject jsonObject = JSONUtil.parseObj(rolePersonCheckOn.getCheckOnCount());
                            rolePersonCheckOn.setCome(jsonObject.get("come").toString());
                            rolePersonCheckOn.setOut(jsonObject.get("out").toString());
                        }
                    }
                    rolePersonCheckOn.setPersonRoleInfoList(personRoleInfoList);
                }
            }

            msgResult.setResult(true);
            msgResult.setData(rolePersonCheckOn);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    @ApiOperation(value="保存")
    @PostMapping("save")
    public MessageResult<RolePersonCheckOn> save(@RequestBody RolePersonCheckOn rolePersonCheckOn,@RequestAttribute String subject){
        MessageResult<RolePersonCheckOn> msgResult = new MessageResult<>();

        try {
            Date now = new Date();

            int affectCount = 0;

            if(rolePersonCheckOn.getRolePerson() == 1){
                List<PersonInfo> list = rolePersonCheckOn.getPersonInfoList();

                for (PersonInfo personInfo:list) {
                    RolePersonCheckOn curItem = rolePersonCheckOnService.findByPersonId(String.valueOf(personInfo.getId()));
                    if(curItem!=null){
                        curItem.setUpdateBy(subject);
                        curItem.setUpdateTime(now);
                        curItem.setRolePerson(rolePersonCheckOn.getRolePerson());
                        curItem.setRolePersonId(personInfo.getId().toString());
                        curItem.setCheckOnTimeFlag(rolePersonCheckOn.getCheckOnTimeFlag());
                        if(rolePersonCheckOn.getCheckOnTimeFlag()){
                            String checkTimeRange = rolePersonCheckOn.getCheckTimeRange();
                            String[] checkTimeArray = checkTimeRange.split(",");
                            if(checkTimeArray.length==2){
                                curItem.setCheckStartTime(checkTimeArray[0]);
                                curItem.setCheckEndTime(checkTimeArray[1]);
                            }
                        }
                        else{
                            curItem.setCheckStartTime("");
                            curItem.setCheckEndTime("");
                        }
                        curItem.setCheckOnCountFlag(rolePersonCheckOn.getCheckOnCountFlag());
                        if(rolePersonCheckOn.getCheckOnCountFlag()){
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("come",rolePersonCheckOn.getCome());
                            jsonObject.put("out",rolePersonCheckOn.getOut());
                            curItem.setCheckOnCount(jsonObject.toString());
                        }
                        else{
                            curItem.setCheckOnCount("");
                        }

                        affectCount += rolePersonCheckOnService.update(curItem);
                    }
                    else{
                        curItem = new RolePersonCheckOn();
                        curItem.setId(UUID.randomUUID().toString());
                        curItem.setCreateBy(subject);
                        curItem.setCreateTime(now);
                        curItem.setDelFlag(false);
                        curItem.setRolePerson(rolePersonCheckOn.getRolePerson());
                        curItem.setRolePersonId(personInfo.getId().toString());
                        curItem.setCheckOnTimeFlag(rolePersonCheckOn.getCheckOnTimeFlag());
                        if(rolePersonCheckOn.getCheckOnTimeFlag()){

                            String checkTimeRange = rolePersonCheckOn.getCheckTimeRange();
                            String[] checkTimeArray = checkTimeRange.split(",");
                            if(checkTimeArray.length==2){
                                curItem.setCheckStartTime(checkTimeArray[0]);
                                curItem.setCheckEndTime(checkTimeArray[1]);
                            }
                        }
                        else{
                            curItem.setCheckStartTime("");
                            curItem.setCheckEndTime("");
                        }
                        curItem.setCheckOnCountFlag(rolePersonCheckOn.getCheckOnCountFlag());
                        if(rolePersonCheckOn.getCheckOnCountFlag()){
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("come",rolePersonCheckOn.getCome());
                            jsonObject.put("out",rolePersonCheckOn.getOut());
                            curItem.setCheckOnCount(jsonObject.toString());
                        }
                        else{
                            curItem.setCheckOnCount("");
                        }
                        affectCount += rolePersonCheckOnService.insert(curItem);
                    }
                }
            }
            else if(rolePersonCheckOn.getRolePerson() == 0){
                List<PersonRoleInfo> list = rolePersonCheckOn.getPersonRoleInfoList();

                for (PersonRoleInfo personRoleInfo:list) {
                    RolePersonCheckOn curItem = rolePersonCheckOnService.findByRoleId(personRoleInfo.getId());

                    if(curItem!=null){
                        curItem.setUpdateBy(subject);
                        curItem.setUpdateTime(now);
                        curItem.setRolePerson(rolePersonCheckOn.getRolePerson());
                        curItem.setRolePersonId(personRoleInfo.getId());
                        curItem.setCheckOnTimeFlag(rolePersonCheckOn.getCheckOnTimeFlag());
                        if(rolePersonCheckOn.getCheckOnTimeFlag()){
                            String checkTimeRange = rolePersonCheckOn.getCheckTimeRange();
                            String[] checkTimeArray = checkTimeRange.split(",");
                            if(checkTimeArray.length==2){
                                curItem.setCheckStartTime(checkTimeArray[0]);
                                curItem.setCheckEndTime(checkTimeArray[1]);
                            }
                        }
                        else{
                            curItem.setCheckStartTime("");
                            curItem.setCheckEndTime("");
                        }
                        curItem.setCheckOnCountFlag(rolePersonCheckOn.getCheckOnCountFlag());
                        if(rolePersonCheckOn.getCheckOnCountFlag()){
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("come",rolePersonCheckOn.getCome());
                            jsonObject.put("out",rolePersonCheckOn.getOut());
                            curItem.setCheckOnCount(jsonObject.toString());
                        }
                        else{
                            curItem.setCheckOnCount("");
                        }

                        affectCount += rolePersonCheckOnService.update(curItem);
                    }
                    else{
                        curItem = new RolePersonCheckOn();
                        curItem.setId(UUID.randomUUID().toString());
                        curItem.setCreateBy(subject);
                        curItem.setCreateTime(now);
                        curItem.setDelFlag(false);
                        curItem.setRolePerson(rolePersonCheckOn.getRolePerson());
                        curItem.setRolePersonId(personRoleInfo.getId());
                        curItem.setCheckOnTimeFlag(rolePersonCheckOn.getCheckOnTimeFlag());
                        if(rolePersonCheckOn.getCheckOnTimeFlag()){

                            String checkTimeRange = rolePersonCheckOn.getCheckTimeRange();
                            String[] checkTimeArray = checkTimeRange.split(",");
                            if(checkTimeArray.length==2){
                                curItem.setCheckStartTime(checkTimeArray[0]);
                                curItem.setCheckEndTime(checkTimeArray[1]);
                            }
                        }
                        else{
                            curItem.setCheckStartTime("");
                            curItem.setCheckEndTime("");
                        }
                        curItem.setCheckOnCountFlag(rolePersonCheckOn.getCheckOnCountFlag());
                        if(rolePersonCheckOn.getCheckOnCountFlag()){
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("come",rolePersonCheckOn.getCome());
                            jsonObject.put("out",rolePersonCheckOn.getOut());
                            curItem.setCheckOnCount(jsonObject.toString());
                        }
                        else{
                            curItem.setCheckOnCount("");
                        }
                        affectCount += rolePersonCheckOnService.insert(curItem);
                    }
                }
            }

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

        try {
            int affectCount = rolePersonCheckOnService.delete(id);

            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/{id}")
    public MessageResult<RolePersonCheckOn> batchDelete(@PathVariable("id") String id){
        MessageResult<RolePersonCheckOn> msgResult = new MessageResult<>();

        msgResult.setResult(false);
        msgResult.setMessage("未实现");

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "list",method = RequestMethod.POST)
    public MessageResult<Map> list(
            String id,
            @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);

        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(id)) {
            searchParms.put("id","%" + id + "%");
        }

        Page<RolePersonCheckOn> page = rolePersonCheckOnService.pageSearch(searchParms,pageIndex,pageSize,sortList);

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

        return msgResult;
    }
}
