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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.CompanyInfo;
import com.jpsoft.shinestar.modules.base.entity.CompanyStructureInfo;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.base.service.CompanyStructureInfoService;
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.Menu;
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 java.util.*;

/**
 * 场景单位下的机构管理
 * sz
 * **/
@RestController
@RequestMapping("/base/companyStructureInfo")
@Api(description = "companyStructureInfo")
public class CompanyStructureInfoController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private CompanyStructureInfoService companyStructureInfoService;
    @Autowired
    private CompanyInfoService companyInfoService;


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

        CompanyStructureInfo companyStructureInfo = new CompanyStructureInfo();

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

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

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

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

        try {
            CompanyStructureInfo companyStructureInfo = companyStructureInfoService.get(id);

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

        try {
            companyStructureInfo.setUpdateBy(subject);
            companyStructureInfo.setUpdateTime(new Date());
            
            int affectCount = companyStructureInfoService.update(companyStructureInfo);

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

            int affectCount = companyStructureInfoService.update(companyStructureInfo);

            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) {
                CompanyStructureInfo companyStructureInfo = companyStructureInfoService.get(id);
                companyStructureInfo.setDelFlag(true);
                companyStructureInfo.setUpdateBy(subject);
                companyStructureInfo.setUpdateTime(new Date());

                affectCount += companyStructureInfoService.update(companyStructureInfo);
            }

            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 companyId, String structureName, String positionName, String parentId,
            @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.sort_no","asc"));
        sortList.add(new Sort("a.parent_id","asc"));

        if (StringUtils.isNotEmpty(companyId)) {
            searchParams.put("companyId",companyId);
        }
        if (StringUtils.isNotEmpty(structureName)) {
            searchParams.put("structureName","%" + structureName + "%");
        }
        if (StringUtils.isNotEmpty(positionName)) {
            searchParams.put("positionName","%" + positionName + "%");
        }
        if (StringUtils.isNotEmpty(parentId)) {
            searchParams.put("parentId",parentId);
        }

        Page<CompanyStructureInfo> page = companyStructureInfoService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);
        for(CompanyStructureInfo companyStructureInfo : page.getResult()){
            CompanyInfo companyInfo = companyInfoService.get(companyStructureInfo.getCompanyId());
            if(companyInfo == null){
                continue;
            }
            companyStructureInfo.setCompanyName(companyInfo.getName());
            CompanyStructureInfo companyStructureInfo1 = companyStructureInfoService.get(companyStructureInfo.getParentId());
            if(companyStructureInfo1 != null) {
                companyStructureInfo.setParentName(companyStructureInfo1.getStructureName());
            }
        }

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

        return msgResult;
    }

    @ApiOperation(value="根据公司查机构")
    @RequestMapping(value = "list",method = RequestMethod.POST)
    public MessageResult<List<CompanyStructureInfo>> listByCompanyId(String companyId, @RequestAttribute String subject){
        MessageResult<List<CompanyStructureInfo>> msgResult = new MessageResult<>();
        List<CompanyStructureInfo> list = companyStructureInfoService.findByCompanyId(companyId);
        CompanyStructureInfo topCsi = new CompanyStructureInfo();
        topCsi.setId("0");
        for(CompanyStructureInfo csi : list){
            if(csi.getParentId() == null){
                csi.setParentId("0");
                topCsi.setStructureName(csi.getPositionName());
            }
        }
        list.add(0,topCsi);
        msgResult.setResult(true);
        msgResult.setData(list);
        return msgResult;
    }

    @ApiOperation(value = "查询")
    @RequestMapping(value = "query", method = RequestMethod.POST)
    public MessageResult<List> query(
            String keywords,
            @RequestAttribute String subject) {
        MessageResult<List> msgResult = new MessageResult<>();

        Map<String, Object> searchParams = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("create_time", "asc"));

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

        List<CompanyStructureInfo> companyStructureInfoList = companyStructureInfoService.pageSearch(searchParams,1,100,false, sortList).getResult();

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

        return msgResult;
    }
}
