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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.dto.PersonInfoDTO;
import com.jpsoft.shinestar.modules.base.entity.CompanyInfo;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.base.entity.ApprovalConfig;
import com.jpsoft.shinestar.modules.base.service.ApprovalConfigService;
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.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/approvalConfig")
@Api(description = "approvalConfig")
public class ApprovalConfigController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ApprovalConfigService approvalConfigService;
    @Autowired
    private CompanyInfoService companyInfoService;
    @Autowired
    private DataDictionaryService dataDictionaryService;
    @Autowired
    private UserService userService;

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

        ApprovalConfig approvalConfig = new ApprovalConfig();

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

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

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

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

        try {
            ApprovalConfig approvalConfig = approvalConfigService.get(id);

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

        try {
            approvalConfig.setUpdateBy(subject);
            approvalConfig.setUpdateTime(new Date());
            
            int affectCount = approvalConfigService.update(approvalConfig);

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

            int affectCount = approvalConfigService.update(approvalConfig);

            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) {
                ApprovalConfig approvalConfig = approvalConfigService.get(id);
                approvalConfig.setDelFlag(true);
                approvalConfig.setUpdateBy(subject);
                approvalConfig.setUpdateTime(new Date());

                affectCount += approvalConfigService.update(approvalConfig);
            }

            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="subordinate",defaultValue="false") Boolean subordinate,
            @RequestParam(value="type",defaultValue="") String type,
            @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.level_","asc"));
        sortList.add(new Sort("b.sort_no","asc"));
        sortList.add(new Sort("b.name_","asc"));
        sortList.add(new Sort("a.type_","asc"));

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

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

        if (StringUtils.isEmpty(companyId)){
            if (!userService.hasRole(subject,"SYSADMIN")) {
                User user = userService.get(subject);
                CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
                searchParams.put("companyCode", companyInfo.getCode() + "%");
            }
        }
        else {
            CompanyInfo companyInfo = companyInfoService.get(companyId);
            if (subordinate) {
                searchParams.put("companyCode", companyInfo.getCode() + "%");
            } else {
                searchParams.put("companyCode", companyInfo.getCode());
            }
        }

        Page<ApprovalConfig> page = approvalConfigService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);
        for(ApprovalConfig ac : page.getResult()) {
            ac.setTypeN(dataDictionaryService.findNameByCatalogNameAndValue("审批层级类型",ac.getType()));
        }

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

        return msgResult;
    }
}
