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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.dto.ApplicationExamineDTO;
import com.jpsoft.shinestar.modules.base.dto.PersonInfoDTO;
import com.jpsoft.shinestar.modules.base.entity.CompanyInfo;
import com.jpsoft.shinestar.modules.base.entity.PersonRoleInfo;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonRoleInfoService;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.base.entity.ApplicationExamine;
import com.jpsoft.shinestar.modules.base.service.ApplicationExamineService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
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.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.*;

@RestController
@RequestMapping("/base/applicationExamine")
@Api(description = "applicationExamine")
public class ApplicationExamineController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ApplicationExamineService applicationExamineService;

    @Autowired
    private CompanyInfoService companyInfoService;
    @Autowired
    private PersonRoleInfoService personRoleInfoService;
    @Autowired
    private PersonInfoService personInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private DataDictionaryService dataDictionaryService;

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

        ApplicationExamine applicationExamine = new ApplicationExamine();

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

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

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

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

        try {
            ApplicationExamine applicationExamine = applicationExamineService.get(id);

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

        try {
            applicationExamine.setUpdateBy(subject);
            applicationExamine.setUpdateTime(new Date());
            
            int affectCount = applicationExamineService.update(applicationExamine);

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

            int affectCount = applicationExamineService.update(applicationExamine);

            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) {
                ApplicationExamine applicationExamine = applicationExamineService.get(id);
                applicationExamine.setDelFlag(true);
                applicationExamine.setUpdateBy(subject);
                applicationExamine.setUpdateTime(new Date());

                affectCount += applicationExamineService.update(applicationExamine);
            }

            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="applicationCompanyId",defaultValue="")  String applicationCompanyId,
            @RequestParam(value="applicationSubordinate",defaultValue="false")  Boolean applicationSubordinate,
            @RequestParam(value="examineCompanyId",defaultValue="")  String examineCompanyId,
            @RequestParam(value="examineSubordinate",defaultValue="false")  Boolean examineSubordinate,
            @RequestParam(value="applicationRoleId",defaultValue="")  String applicationRoleId,
            @RequestParam(value="type",defaultValue="")  String type,
            @RequestParam(value="level",defaultValue="")  String level,
            @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.type_","asc"));
        sortList.add(new Sort("a.level_","asc"));
        sortList.add(new Sort("b.level_","asc"));
        sortList.add(new Sort("b.sort_no","asc"));
        //sortList.add(new Sort("a.examine_company_id","asc"));
        //sortList.add(new Sort("a.examine_role_id","asc"));

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

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

        if (StringUtils.isNotEmpty(applicationCompanyId)) {
            if(applicationSubordinate) {
                CompanyInfo applicationCompany = companyInfoService.get(applicationCompanyId);
                searchParams.put("applicationCompanyCode", applicationCompany.getCode() + "%");
            }else{
                searchParams.put("applicationCompanyId", applicationCompanyId);
            }
        }else{
            if (!userService.hasRole(subject,"SYSADMIN")) {
                searchParams.put("applicationPermissionCode", userCompanyInfo.getCode() + "%");
            }
        }

        if (StringUtils.isNotEmpty(examineCompanyId)) {
            if(examineSubordinate) {
                CompanyInfo examineCompany = companyInfoService.get(examineCompanyId);
                searchParams.put("examineCompanyCode", examineCompany.getCode() + "%");
            }else{
                searchParams.put("examineCompanyId", examineCompanyId);
            }
        }else{
            if (!userService.hasRole(subject,"SYSADMIN")) {
                searchParams.put("examinePermissionCode", userCompanyInfo.getCode() + "%");
            }
        }

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

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

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

        Page<ApplicationExamine> page = applicationExamineService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);
        Page<ApplicationExamineDTO> pageDTO = PojoUtils.convertPage(page, ApplicationExamineDTO.class);
        for(ApplicationExamineDTO dto : pageDTO.getResult()){
            CompanyInfo applicationCompany = companyInfoService.get(dto.getApplicationCompanyId());

            String[] roleIds = dto.getApplicationRoleId().split(",");
            StringJoiner roleNames = new StringJoiner(",");

            for (String roleId : roleIds) {
                PersonRoleInfo roleInfo = personRoleInfoService.get(roleId);
                roleNames.add(roleInfo.getPersonRoleName());
            }

            CompanyInfo examineCompany = companyInfoService.get(dto.getExamineCompanyId());
            PersonRoleInfo examineRoleInfo = personRoleInfoService.get(dto.getExamineRoleId());

            dto.setApplicationCompanyName(applicationCompany.getName());
            dto.setApplicationRoleName(roleNames.toString());
            dto.setExamineCompanyName(examineCompany.getName());
            dto.setExamineRoleName(examineRoleInfo.getPersonRoleName());

            String typeName = dataDictionaryService.findNameByCatalogNameAndValue("审批类型",dto.getType());
            dto.setTypeName(typeName);
        }

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

        return msgResult;
    }
}
