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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.sun.org.apache.xpath.internal.operations.Bool;
import io.swagger.annotations.Api;
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.web.bind.annotation.*;

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

/**
 * 角色管理
 * sz
 * **/
@RestController
@RequestMapping("/base/personRoleInfo")
@Api(description = "personRoleInfo")
public class PersonRoleInfoController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PersonRoleInfoService personRoleInfoService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private IconInfoService iconInfoService;

    @Autowired
    private PersonRoleIconService personRoleIconService;

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

        PersonRoleInfo personRoleInfo = new PersonRoleInfo();

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

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

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

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

        try {
            PersonRoleInfo personRoleInfo = personRoleInfoService.get(id);

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

        try {
            personRoleInfo.setUpdateBy(subject);
            personRoleInfo.setUpdateTime(new Date());
            
            int affectCount = personRoleInfoService.update(personRoleInfo);

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

            int affectCount = personRoleInfoService.update(personRoleInfo);

            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) {
                PersonRoleInfo personRoleInfo = personRoleInfoService.get(id);
                personRoleInfo.setDelFlag(true);
                personRoleInfo.setUpdateBy(subject);
                personRoleInfo.setUpdateTime(new Date());

                affectCount += personRoleInfoService.update(personRoleInfo);
            }

            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="sceneId",defaultValue="") String sceneId,
            @RequestParam(value="useEnable",defaultValue="") String useEnable,
            @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("a.create_time","asc"));

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

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

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

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

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

        return msgResult;
    }

    @ApiOperation(value="根据公司查角色")
    @RequestMapping(value = "listByCompanyId",method = RequestMethod.POST)
    public MessageResult<List<PersonRoleInfo>> listByCompanyId(String companyId, @RequestAttribute String subject){
        MessageResult<List<PersonRoleInfo>> msgResult = new MessageResult<>();
        CompanyInfo ci = companyInfoService.get(companyId);

        if(ci!=null) {
            List<PersonRoleInfo> list = personRoleInfoService.findBySceneId(ci.getSceneId());
            msgResult.setResult(true);
            msgResult.setData(list);
        }
        else{
            msgResult.setResult(false);
        }

        return msgResult;
    }

    @ApiOperation(value="根据公司查角色")
    @RequestMapping(value = "findBySceneId",method = RequestMethod.POST)
    public MessageResult<List<PersonRoleInfo>> findBySceneId(String sceneId, @RequestAttribute String subject){
        MessageResult<List<PersonRoleInfo>> msgResult = new MessageResult<>();

        List<PersonRoleInfo> list = personRoleInfoService.findBySceneId(sceneId);
        msgResult.setResult(true);
        msgResult.setData(list);

        return msgResult;
    }

    @ApiOperation(value="查询所有角色")
    @RequestMapping(value = "findAll",method = RequestMethod.POST)
    public MessageResult<List<PersonRoleInfo>> findAll(@RequestAttribute String subject){
        MessageResult<List<PersonRoleInfo>> msgResult = new MessageResult<>();

        List<PersonRoleInfo> list = personRoleInfoService.findAll();

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

        return msgResult;
    }

    @GetMapping("findAllIcon")
    @ApiOperation(value="查询所有菜单")
    public MessageResult<List> findAllIcon(){
        MessageResult<List> messageResult = new MessageResult<>();

        try {
            List<IconInfo> data = iconInfoService.list();

            //todo 填写具体代码
            messageResult.setData(data);
            messageResult.setResult(true);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return messageResult;
    }

    @GetMapping("findRelatedIcon")
    @ApiOperation(value="查询分配菜单")
    public MessageResult<List> findRelatedIcon(String personRoleId,String mode){
        MessageResult<List> messageResult = new MessageResult<>();

        try {
            List<IconInfo> data = null;

            if ("common".equals(mode)){
                data = personRoleIconService.findCommonByPersonRoleId(personRoleId);
            }
            else if("default".equals(mode)){
                data = personRoleIconService.findDefaultIconByPersonRoleId(personRoleId);
            }

            //todo 填写具体代码
            messageResult.setData(data);
            messageResult.setResult(true);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return messageResult;
    }

    @PostMapping("saveRelatedIcon")
    @ApiOperation(value="保存分配菜单")
    public MessageResult<Integer> saveRelatedIcon(String personRoleId,String mode,String idList,@RequestAttribute String subject){
        MessageResult<Integer> messageResult = new MessageResult<>();

        try {
            if ("common".equals(mode)){
                personRoleIconService.deleteCommonByPersonRoleId(personRoleId);
            }
            else if("default".equals(mode)){
                personRoleIconService.deleteDefaultIconByPersonRoleId(personRoleId);
            }

            String[] idArr = idList.split(",");

            int affectCount = 0;

            Date now = new Date();

            for (String iconId : idArr) {
                PersonRoleIcon personRoleIcon = new PersonRoleIcon();
                personRoleIcon.setId(UUID.randomUUID().toString());
                personRoleIcon.setPersonRoleId(personRoleId);
                personRoleIcon.setIconId(iconId);
                personRoleIcon.setCreateBy(subject);
                personRoleIcon.setCreateTime(now);
                personRoleIcon.setDelFlag(false);
                personRoleIcon.setSortNo(affectCount+1);

                if ("common".equals(mode)) {
                    personRoleIcon.setCommonStatus(true);
                }

                if("default".equals(mode)){
                    personRoleIcon.setDefaultStatus(true);
                }

                affectCount += personRoleIconService.insert(personRoleIcon);

                //创建时间顺延100毫秒
                now = new Date(now.getTime() + 100);
            }

            //todo 填写具体代码
            messageResult.setData(affectCount);
            messageResult.setResult(true);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return messageResult;
    }

    @ApiOperation(value="查询是否拥有菜单")
    @RequestMapping(value = "findHaveIcon",method = RequestMethod.POST)
    public MessageResult<Boolean> findHaveIcon(String personRoleId,String iconId){
        MessageResult<Boolean> messageResult = new MessageResult<>();
        try {
            Boolean haveing = false;
            PersonRoleIcon personRoleIcon = personRoleIconService.findByPersonRoleIdAndIconId(personRoleId,iconId);
            if(personRoleIcon != null){
                haveing = true;
            }
            messageResult.setData(haveing);
            messageResult.setResult(true);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return messageResult;
    }

}
