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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.modules.base.dto.CompanyInfoDTO;
import com.jpsoft.shinestar.modules.base.dto.PersonDeviceRelationDTO;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.common.utils.OSSUtil;
import com.jpsoft.shinestar.modules.common.utils.POIUtils;
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.jpsoft.shinestar.modules.pacs.service.IGuardService;
import com.jpsoft.shinestar.modules.sys.entity.DataDictionary;
import com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import com.jpsoft.shinestar.modules.sys.service.UserCompanyService;
import com.jpsoft.shinestar.modules.sys.service.UserService;
import com.sun.org.apache.xpath.internal.operations.Bool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.text.DecimalFormat;
import java.util.*;

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

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private UserService userService;

    @Autowired
    private CompanyPositionService companyPositionService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private CompanyDeviceRelationService companyDeviceRelationService;

    @Autowired
    private DeviceInfoService deviceInfoService;

    @Autowired
    private IGuardService lapiService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private PersonDeviceRelationService personDeviceRelationService;

    @Autowired
    private UserCompanyService userCompanyService;

    @Autowired
    RabbitTemplate rabbitTemplate;

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

        CompanyInfoDTO companyInfoDTO = new CompanyInfoDTO();
        companyInfoDTO.setEnableChangeParent(true);

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

        return msgResult;
    }

    @ApiOperation(value = "添加信息")
    @PostMapping("add")
    public MessageResult<Map> add(@RequestBody CompanyInfoDTO companyInfoDTO, @RequestAttribute String subject) {
        MessageResult<Map> msgResult = new MessageResult<>();
        Map<String, Object> map = new HashMap<>();

        try {
            CompanyInfo companyInfo = new CompanyInfo();
            PojoUtils.map(companyInfoDTO, companyInfo);
            companyInfo.setId(UUID.randomUUID().toString());

            DecimalFormat df = new DecimalFormat("000");

            //上级单位code
            if (StringUtils.isNotEmpty(companyInfo.getParentId())) {
                CompanyInfo parent = companyInfoService.get(companyInfo.getParentId());
                companyInfo.setCode(parent.getCode() + "," + companyInfo.getId());
                companyInfo.setLevel(parent.getLevel() + 1);
            } else {
                companyInfo.setCode(companyInfo.getId());
                companyInfo.setLevel(1);
            }

            companyInfo.setDelFlag(false);
            companyInfo.setCreateBy(subject);
            companyInfo.setCreateTime(new Date());
            companyInfoService.insert(companyInfo);
            map.put("companyInfo", companyInfo);

            CompanyPosition companyPosition = new CompanyPosition();
            companyPosition.setId(UUID.randomUUID().toString());
            companyPosition.setCompanyId(companyInfo.getId());
            companyPosition.setPosition1Name(companyInfoDTO.getPosition1Name());
            companyPosition.setPosition2Name(companyInfoDTO.getPosition2Name());
            companyPosition.setPosition3Name(companyInfoDTO.getPosition3Name());
            companyPosition.setPosition4Name(companyInfoDTO.getPosition4Name());
            companyPosition.setPosition5Name(companyInfoDTO.getPosition5Name());
            companyPosition.setDelFlag(false);
            companyPosition.setCreateBy(subject);
            companyPosition.setCreateTime(new Date());
            int affectCount = companyPositionService.insert(companyPosition);
            map.put("companyPosition", companyPosition);

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

        try {
            User user = userService.get(subject);

            CompanyInfo companyInfo = companyInfoService.get(id);

            CompanyInfoDTO companyInfoDTO = new CompanyInfoDTO();

            if (companyInfo != null) {
                PojoUtils.map(companyInfo, companyInfoDTO);

                companyInfoDTO.setEnableChangeParent(true);

                if (!userService.hasRole(user.getId(), "SYSADMIN")) {
                    if (user.getCompanyId().equals(id)) {
                        //企业管理员所在单位不能修改上级单位
                        companyInfoDTO.setEnableChangeParent(false);
                    }
                }

//                CompanyPosition companyPosition = new CompanyPosition();
//                Map<String,Object> searchParams1 = new HashMap<>();
//                searchParams1.put("companyId",companyInfo.getId());
//                List<Sort> sortList1 = new ArrayList<>();
//                sortList1.add(new Sort("id_","asc"));
//                Page<CompanyPosition> page1 = companyPositionService.pageSearch(searchParams1,1,1,false,sortList1);
//                if(page1.size() > 0) {
//                    companyPosition = page1.get(0);
//                    companyInfoDTO.setPosition1Name(companyPosition.getPosition1Name());
//                    companyInfoDTO.setPosition2Name(companyPosition.getPosition2Name());
//                    companyInfoDTO.setPosition3Name(companyPosition.getPosition3Name());
//                    companyInfoDTO.setPosition4Name(companyPosition.getPosition4Name());
//                    companyInfoDTO.setPosition5Name(companyPosition.getPosition5Name());
//                }

                msgResult.setResult(true);
                msgResult.setData(companyInfoDTO);
            } 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<Map> update(@RequestBody CompanyInfoDTO companyInfoDTO, @RequestAttribute String subject) {
        MessageResult<Map> msgResult = new MessageResult<>();
        Map<String, Object> map = new HashMap<>();

        try {
            int affectCount = 0;
            CompanyInfo srcCompany = companyInfoService.get(companyInfoDTO.getId());

            CompanyInfo destCompany = new CompanyInfo();
            PojoUtils.map(companyInfoDTO, destCompany);

            //上级单位code
            if (StringUtils.isNotEmpty(destCompany.getParentId())) {
                CompanyInfo parent = companyInfoService.get(destCompany.getParentId());
                destCompany.setCode(parent.getCode() + "," + destCompany.getId());
                destCompany.setLevel(parent.getLevel() + 1);
            } else {
                destCompany.setCode(destCompany.getId());
                destCompany.setLevel(1);
            }

            String newCode = destCompany.getCode();
            String oldCode = srcCompany.getCode();

            if (StringUtils.isNotEmpty(oldCode) && !oldCode.equals(newCode)) {
                companyInfoService.updateCode(oldCode, newCode);
//                List<CompanyInfo> children = companyInfoService.findByCompanyCode(oldCode + "%");
//
//                for (CompanyInfo child : children) {
//                    child.setCode(newCode + child.getCode().substring(oldCode.length()));
//                    child.setUpdateTime(new Date());
//                    child.setUpdateBy(subject);
//
//                    companyInfoService.update(child);
//                }
            }

            destCompany.setUpdateBy(subject);
            destCompany.setUpdateTime(new Date());
            companyInfoService.update(destCompany);

            map.put("companyInfo", destCompany);

            affectCount++;

            CompanyPosition companyPosition = new CompanyPosition();
            Map<String, Object> searchParams1 = new HashMap<>();
            searchParams1.put("companyId", destCompany.getId());
            List<Sort> sortList1 = new ArrayList<>();
            sortList1.add(new Sort("id_", "asc"));

            Page<CompanyPosition> page1 = companyPositionService.pageSearch(searchParams1, 1, 1, false, sortList1);

            if (page1.size() > 0) {
                companyPosition = page1.get(0);
                companyPosition.setPosition1Name(companyInfoDTO.getPosition1Name());
                companyPosition.setPosition2Name(companyInfoDTO.getPosition2Name());
                companyPosition.setPosition3Name(companyInfoDTO.getPosition3Name());
                companyPosition.setPosition4Name(companyInfoDTO.getPosition4Name());
                companyPosition.setPosition5Name(companyInfoDTO.getPosition5Name());
                companyPosition.setUpdateBy(subject);
                companyPosition.setUpdateTime(new Date());
                companyPositionService.update(companyPosition);
                affectCount++;
            }

            map.put("companyPosition", companyPosition);

//            //更新设备人脸库
//            //查询公司绑定的设备
//            List<CompanyDeviceRelation> relations = companyDeviceRelationService.findByCompanyId(companyInfoDTO.getId());
//            for(CompanyDeviceRelation relation : relations) {
//                //修改不捕获异常,发送请求就行
//                new Thread(()->{
//                    try {
//                        lapiService.updateCompanyLib(relation.getCompanyId(), relation.getDeviceId(),relation.getLibraryId());
//                    }
//                    catch (Exception ex){
//                        logger.error(ex.getMessage(),ex);
//                    }
//                }).start();
//            }


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

            int affectCount = companyInfoService.update(companyInfo);

            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) {
                CompanyInfo companyInfo = companyInfoService.get(id);
                companyInfo.setDelFlag(true);
                companyInfo.setUpdateBy(subject);
                companyInfo.setUpdateTime(new Date());

                affectCount += companyInfoService.update(companyInfo);
            }

            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 name, String parentId, Boolean subordinate, String sceneId,
            String type,
            String unitType,
            @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("level_", "asc"));
        sortList.add(new Sort("sort_no", "asc"));
        sortList.add(new Sort("name_", "asc"));

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

        if (StringUtils.isNotEmpty(parentId)) {
            CompanyInfo parent = companyInfoService.get(parentId);

            if (parent != null) {
                if (subordinate != null && subordinate) {
                    searchParams.put("parentCode", parent.getCode() + "%");
                } else {
                    searchParams.put("parentCode", parent.getCode());
                }
            }
        }

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

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

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

        User user = userService.get(subject);

        boolean isAdmin = false;

        if (!userService.hasRole(user.getId(), "SYSADMIN")) {
            CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
            searchParams.put("bindCompanyCode", companyInfo.getCode() + "%");

            //查询关联单位表
            List<CompanyInfo> relateList = userCompanyService.findByUserId(user.getId());
            searchParams.put("relateCompanyList" , relateList);
        } else {
            if (StringUtils.isEmpty(name) && StringUtils.isEmpty(parentId)) {
                //系统管理员，如果查询条件为空则只查根目录
                searchParams.put("root", true);
                isAdmin = true;
            }
        }

        Page<CompanyInfo> page = companyInfoService.pageSearch(searchParams, pageIndex, pageSize, sortList);
        Page<CompanyInfoDTO> pageDTO = PojoUtils.convertPage(page, CompanyInfoDTO.class);

        for (CompanyInfoDTO li : pageDTO.getResult()) {
            String unitTypeName = dataDictionaryService.findNameByCatalogNameAndValue("单位性质", li.getUnitType());
            li.setUnitTypeName(unitTypeName);

            li.setIsAdmin(isAdmin);

            //查询是否有子单位
            Boolean hasChildren = companyInfoService.hasChildren(li.getId());

            li.setHasChildren(hasChildren);
        }

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

        return msgResult;
    }

    @ApiOperation(value = "查询子单位")
    @RequestMapping(value = "children", method = RequestMethod.POST)
    public MessageResult<List<CompanyInfoDTO>> children(String parentId) {
        MessageResult<List<CompanyInfoDTO>> msgResult = new MessageResult<>();

        try {
            List<CompanyInfo> list = companyInfoService.findByParentId(parentId);

            List<CompanyInfoDTO> dtoList = new ArrayList<>();

            for (CompanyInfo companyInfo : list) {
                CompanyInfoDTO dto = new CompanyInfoDTO();

                PojoUtils.map(companyInfo, dto);

                Boolean hasChildren = companyInfoService.hasChildren(companyInfo.getId());
                dto.setHasChildren(hasChildren);

                dtoList.add(dto);
            }

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

        return msgResult;
    }

    @ApiOperation(value = "所有单位列表")
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public MessageResult<List<CompanyInfo>> list(String companyId, String type, String scope, @RequestAttribute String subject) {

        MessageResult<List<CompanyInfo>> msgResult = new MessageResult<>();
        User user = userService.get(subject);
        String companyCode = "";

        if (StringUtils.isNotEmpty(companyId)) {
            CompanyInfo companyInfo = companyInfoService.get(companyId);
            companyCode = companyInfo.getCode();
        } else {
            if (userService.hasRole(subject, "SYSADMIN") || "all".equals(scope)) {
                companyCode = "";
            } else {
                CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
                companyCode = companyInfo.getCode();
            }
        }

        List<CompanyInfo> list = companyInfoService.findByCompanyCodeAndType(companyCode + "%", type);

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

        return msgResult;
    }


    @ApiOperation(value = "食堂管理员查询单位列表")
    @RequestMapping(value = "canteenManagelist", method = RequestMethod.POST)
    public MessageResult<List<Map>> canteenManagelist(HttpServletRequest request) {

        String subject = (String) request.getAttribute("subject");

        MessageResult<List<Map>> msgResult = new MessageResult<>();
        User user = userService.get(subject);
        List<CompanyInfo> list = new ArrayList<>();

        if (userService.hasRole(subject, "SYSADMIN")||userService.hasRole(subject, "食堂")) {
            list = companyInfoService.list();
        } else {
            CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
            list = companyInfoService.findByCompanyCode(companyInfo.getCode() + "%", null);

            //查询关联单位表
            List<CompanyInfo> relateList = userCompanyService.findByUserId(user.getId());

            for (CompanyInfo relateCompany : relateList) {
                if (list.stream().filter(item->item.getId().equals(relateCompany.getId())).count()==0){
                    list.add(relateCompany);
                }
            }
        }

        //id_,name_,parent_id,type_
        List<Map> mapList = new ArrayList<>();

        for (CompanyInfo companyInfo : list) {
            Map<String, Object> map = new HashMap<>();

            map.put("id", companyInfo.getId());
            map.put("name", companyInfo.getName());
            map.put("parentId", companyInfo.getParentId());
            map.put("type", companyInfo.getType());

            mapList.add(map);
        }

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

        return msgResult;
    }

    @GetMapping("queryBindDeviceList")
    public MessageResult<Map> queryBindDeviceList(String companyId,
                                                  @RequestParam(value = "deviceNo", defaultValue = "") String deviceNo,
                                                  @RequestParam(value = "deviceName", defaultValue = "") String deviceName,
                                                  @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
                                                  @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
                                                  @RequestAttribute String subject) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            User user = userService.get(subject);

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

            if (!userService.hasRole(user.getId(), "SYSADMIN")) {
                searchParams.put("bindCompanyId", user.getCompanyId());
            }


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

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

            List<Sort> sorts = new ArrayList<>();


            if (StringUtils.isNotEmpty(companyId)) {
                searchParams.put("isBoundCompanyId", companyId);
                sorts.add(new Sort("is_bind", "desc"));
            }
            sorts.add(new Sort("create_time", "asc"));

            //设备列表
            Page<DeviceInfo> deviceInfoPage = deviceInfoService.pageSearch(searchParams, pageIndex, pageSize, true, sorts);

//            //查询已绑定设备
//            List<DeviceInfo> bindDeviceList = companyDeviceRelationService.findDeviceByCompanyId(companyId);
//
//            List<Map> mapList = new ArrayList<>();
//
//            for (DeviceInfo deviceInfo : deviceInfoPage) {
//                Map<String,Object> map = new HashMap<>();
//
//                map.put("device",deviceInfo);
//
//                long count = bindDeviceList.stream().filter((d)->d.getId().equals(deviceInfo.getId())).count();
//
//                if (count>0){
//                    map.put("bound",true);
//                }
//                else{
//                    map.put("bound",false);
//                }
//
//                mapList.add(map);
//            }

            //Map<String,Object> dataMap = PojoUtils.pageWrapper(deviceInfoPage);

            //dataMap.put("data",mapList);

            messageResult.setData(PojoUtils.pageWrapper(deviceInfoPage));
            messageResult.setResult(true);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("bindDevice")
    public MessageResult<String> bindDevice(String companyId, String deviceIds, @ModelAttribute String subject) {
        MessageResult<String> messageResult = new MessageResult<>();

        try {
            String[] arr = deviceIds.split(",");

//            companyDeviceRelationService.deleteByCompanyId(companyId);
            String libraryId = "";
            for (String deviceId : arr) {
                CompanyDeviceRelation cdr = new CompanyDeviceRelation();
                cdr.setId(UUID.randomUUID().toString());
                cdr.setCompanyId(companyId);
                cdr.setDeviceId(deviceId);

                cdr.setCreateBy(subject);
                cdr.setCreateTime(new Date());

                /**设备添加人脸库**/
                /*
                //设备添加人脸库
                List<LapiResult> lapiResults= lapiService.addCompanyLib(companyId,deviceId);
                for (int i = 0; i < lapiResults.size(); i++) {
                    LapiResult lapiResult = lapiResults.get(i);

                    if (lapiResult.isSuccess()) {
                        //默认人脸库ID defaultFaceLibraryId
                        //LibraryId
                        HashMap dataMap = (HashMap) lapiResult.getData();
                        libraryId = dataMap.get("LibraryId").toString();
                        System.out.println("LibraryId=============" + libraryId);
                    }
                }
                 */

                cdr.setLibraryId(libraryId);
                companyDeviceRelationService.insert(cdr);
            }

            messageResult.setResult(true);
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("unbindDevice")
    public MessageResult<String> unbindDevice(String companyId, String deviceIds, @ModelAttribute String subject) {
        MessageResult<String> messageResult = new MessageResult<>();

        try {
            String[] arr = deviceIds.split(",");

            for (String deviceId : arr) {
                companyDeviceRelationService.deleteByCompanyIdAndDeviceId(companyId, deviceId);
                /** 删除人脸库操作**/
                /*
                CompanyDeviceRelation companyDeviceRelation = companyDeviceRelationService.findByCompanyIdAndDeviceId(companyId, deviceId);
                if (companyDeviceRelation != null) {
                    //设备删除人脸库
                    LapiResult lapiResult = lapiService.deleteCompanyLib(deviceId, companyDeviceRelation.getLibraryId());
                    if (lapiResult.isSuccess()) {
                        //删除成功
                        companyDeviceRelationService.deleteByCompanyIdAndDeviceId(companyId, deviceId);
                    }
                }
                */
            }
            messageResult.setResult(true);
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


    @ApiOperation(value = "单位树")
    @RequestMapping(value = "treeList", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "subject", value = "当前用户编号(不传)", paramType = "form"),
    })
    public MessageResult<List<Map>> treeList(HttpServletRequest request) {
        String subject = (String) request.getAttribute("subject");

        MessageResult<List<Map>> msgResult = new MessageResult<>();
        User user = userService.get(subject);
        List<CompanyInfo> list = new ArrayList<>();

        if (userService.hasRole(subject, "SYSADMIN")) {
            list = companyInfoService.list();
        } else {
            CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
            list = companyInfoService.findByCompanyCode(companyInfo.getCode() + "%", null);

            //查询关联单位表
            List<CompanyInfo> relateList = userCompanyService.findByUserId(user.getId());

            for (CompanyInfo relateCompany : relateList) {
                if (list.stream().filter(item->item.getId().equals(relateCompany.getId())).count()==0){
                    list.add(relateCompany);
                }
            }
        }

        //id_,name_,parent_id,type_
        List<Map> mapList = new ArrayList<>();

        for (CompanyInfo companyInfo : list) {
            Map<String, Object> map = new HashMap<>();

            map.put("id", companyInfo.getId());
            map.put("name", companyInfo.getName());
            map.put("parentId", companyInfo.getParentId());
            map.put("type", companyInfo.getType());

            mapList.add(map);
        }

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

        return msgResult;
    }

    @ApiOperation(value = "分类单位树")
    @RequestMapping(value = "classifyTreeList", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "subject", value = "当前用户编号(不传)", paramType = "form"),
    })
    public MessageResult<List<Map>> classifyTreeList(HttpServletRequest request) {
        String subject = (String) request.getAttribute("subject");
        MessageResult<List<Map>> msgResult = new MessageResult<>();

        //List<DataDictionary> classifyList = dataDictionaryService.findByCatalogName("单位分类");
        Boolean hq1 = false;
        Boolean hq2 = false;
        if (userService.hasRole(subject, "SYSADMIN")) {
            hq1 = true;
            hq2 = true;
        }

        if (userService.hasRole(subject, "后勤1")) {
            hq1 = true;
        }

        if (userService.hasRole(subject, "后勤2")) {
            hq2 = true;
        }

        List<Map> mapList = new ArrayList<>();

        if(hq1) {
            //后勤1
            List<CompanyInfo> list1 = companyInfoService.findByClassify("1");
            //id_,name_,parent_id,type_

            Map<String, Object> map1 = new HashMap<>();
            map1.put("id", "hq1");
            map1.put("name", "后勤1");
            map1.put("parentId", "");
            map1.put("type", "1");
            //保存外勤1
            mapList.add(map1);
            for (CompanyInfo companyInfo : list1) {
                Map<String, Object> map = new HashMap<>();

                map.put("id", companyInfo.getId());
                map.put("name", companyInfo.getName());
                map.put("parentId", "hq1");
                map.put("type", companyInfo.getType());

                mapList.add(map);
            }
        }

        if(hq2) {
            //后勤2
            List<CompanyInfo> list2 = companyInfoService.findByClassify("2");

            Map<String, Object> map2 = new HashMap<>();
            map2.put("id", "hq2");
            map2.put("name", "后勤2");
            map2.put("parentId", "");
            map2.put("type", "1");
            //保存外勤2
            mapList.add(map2);
            for (CompanyInfo companyInfo : list2) {
                Map<String, Object> map = new HashMap<>();

                map.put("id", companyInfo.getId());
                map.put("name", companyInfo.getName());
                map.put("parentId", "hq2");
                map.put("type", companyInfo.getType());

                mapList.add(map);
            }

        }
        msgResult.setResult(true);
        msgResult.setData(mapList);

        return msgResult;
    }

    @ApiOperation(value = "外协单位树")
    @RequestMapping(value = "outScourcerTreeList", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "subject", value = "当前用户编号(不传)", paramType = "form"),
            @ApiImplicitParam(name = "isOutsourcer", value = "是否外协,不传默认为是", paramType = "form"),
    })
    public MessageResult<List<Map>> treeList(
            @RequestParam(value="isOutsourcer",defaultValue="true") Boolean isOutsourcer,
            HttpServletRequest request) {
        String subject = (String) request.getAttribute("subject");

        MessageResult<List<Map>> msgResult = new MessageResult<>();
        User user = userService.get(subject);
        List<CompanyInfo> list = new ArrayList<>();

        if (userService.hasRole(subject, "SYSADMIN")) {
            list = companyInfoService.findByOutscourcer(isOutsourcer);
        } else {
            CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
            list = companyInfoService.findByCompanyCodeAndOutscourcer(companyInfo.getCode() + "%", null,isOutsourcer);

            //查询关联单位表
            List<CompanyInfo> relateList = userCompanyService.findByUserIdAndOutscourcer(user.getId(),isOutsourcer);

            for (CompanyInfo relateCompany : relateList) {
                if (list.stream().filter(item->item.getId().equals(relateCompany.getId())).count()==0){
                    list.add(relateCompany);
                }
            }
        }

        //id_,name_,parent_id,type_
        List<Map> mapList = new ArrayList<>();

        for (CompanyInfo companyInfo : list) {
            Map<String, Object> map = new HashMap<>();

            map.put("id", companyInfo.getId());
            map.put("name", companyInfo.getName());
            map.put("parentId", companyInfo.getParentId());
            map.put("type", companyInfo.getType());

            mapList.add(map);
        }

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

        return msgResult;
    }

    @ApiOperation(value = "导入企业")
    @PostMapping("importXls")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uploadFile", value = "上传文件", required = true, paramType = "form", dataType = "__file")
    })
    public MessageResult<String> importXls(MultipartFile uploadFile,
                                           @RequestAttribute String subject) {
        User user = userService.get(subject);

        MessageResult<String> msgResult = new MessageResult<>();

        try {
            POIUtils poiUtils = new POIUtils(uploadFile.getInputStream());
            int sheetIndex = 0;
            Sheet sheet1 = poiUtils.getSheetAt(sheetIndex);

            int affectCount = 0;
            int failCount = 0;
            int validateColIndex = 10;

            for (int rowIndex = 1; rowIndex <= sheet1.getLastRowNum(); rowIndex++) {
                try {
                    String sort = (String) poiUtils.getCellValue(sheetIndex, rowIndex, 0).toString().replace(" ", "");
                    String name = (String) poiUtils.getCellValue(sheetIndex, rowIndex, 1).toString().replace(" ", "");
                    String parentName = (String) poiUtils.getCellValue(sheetIndex, rowIndex, 2).toString().replace(" ", "");
                    String type = (String) poiUtils.getCellValue(sheetIndex, rowIndex, 3).toString().replace(" ", "");
                    String fullName = (String) poiUtils.getCellValue(sheetIndex, rowIndex, 4).toString().replace(" ", "");
//                    String position1 = (String) poiUtils.getCellValue(sheetIndex, rowIndex, 5).toString().replace(" ", "");
//                    String position2 = (String) poiUtils.getCellValue(sheetIndex, rowIndex, 6).toString().replace(" ", "");
//                    String position3 = (String) poiUtils.getCellValue(sheetIndex, rowIndex, 7).toString().replace(" ", "");
//                    String position4 = (String) poiUtils.getCellValue(sheetIndex, rowIndex, 8).toString().replace(" ", "");
//                    String position5 = (String) poiUtils.getCellValue(sheetIndex, rowIndex, 9).toString().replace(" ", "");

                    if (StringUtils.isEmpty(name)) {
                        break;
                    }

                    CompanyInfo companyInfo = companyInfoService.findByName(name);

                    if (companyInfo != null) {
                        sheet1.getRow(rowIndex).createCell(validateColIndex).setCellValue("该企业已存在!");
                        failCount++;
                        continue;
                    } else {
                        companyInfo = new CompanyInfo();
                        companyInfo.setId(UUID.randomUUID().toString());
                        companyInfo.setSortNo(Integer.valueOf(sort));
                        companyInfo.setName(name);
                        if (StringUtils.isNotEmpty(parentName)) {
                            CompanyInfo li = companyInfoService.findByName(parentName);
                            if (li != null) {
                                companyInfo.setParentId(li.getId());
                            }
                        }
                        if (type.contains("企业")) {
                            companyInfo.setType("1");
                        }
                        if (type.contains("学校")) {
                            companyInfo.setType("2");
                        }
                        companyInfo.setFullName(fullName);
                        companyInfo.setDelFlag(false);
                        companyInfo.setCreateBy(subject);
                        companyInfo.setCreateTime(new Date());

                        if (companyInfoService.insert(companyInfo) > 0) {
                            affectCount++;

                            CompanyPosition companyPosition = new CompanyPosition();
                            companyPosition.setId(UUID.randomUUID().toString());
                            companyPosition.setCompanyId(companyInfo.getId());
//                            companyPosition.setPosition1Name(position1);
//                            companyPosition.setPosition2Name(position2);
//                            companyPosition.setPosition3Name(position3);
//                            companyPosition.setPosition4Name(position4);
//                            companyPosition.setPosition5Name(position5);
                            companyPosition.setDelFlag(false);
                            companyPosition.setCreateBy(subject);
                            companyPosition.setCreateTime(new Date());
                            companyPositionService.insert(companyPosition);
                        }
                    }
                } catch (Exception innerEx) {
                    logger.error(innerEx.getMessage(), innerEx);
                }
            }

            if (failCount > 0) {
                //有导入失败的记录
                msgResult.setResult(false);
                msgResult.setMessage("数据成功导入" + affectCount + "条,有" + failCount + "条数据未导入成功，错误原因请查看报表。");

                //todo 只保留错误数据的sheet
                Workbook wb = poiUtils.exportErrorXls(sheetIndex, validateColIndex, 1 + affectCount + failCount);

                //todo 将wb保存到oss
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                wb.write(output);

                byte[] buffer = output.toByteArray();
                ByteArrayInputStream input = new ByteArrayInputStream(buffer);

                String downloadUrl = OSSUtil.upload(ossConfig, "import", "error.xls", input);

                //todo 返回导入失败报表下载链接
                msgResult.setData(downloadUrl);
            } else {
                msgResult.setResult(true);
                msgResult.setMessage("数据成功导入" + affectCount + "条");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);

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

        return msgResult;
    }


    @ApiOperation(value = "修改单位是否支持手机支付")
    @RequestMapping(value = "isOpenMobilePayment", method = RequestMethod.POST)
    public MessageResult<Integer> isOpenMobilePayment(String id, Boolean isMobilePayment, @RequestAttribute String subject) {

        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            CompanyInfo companyInfo = companyInfoService.get(id);
            companyInfo.setIsMobilePayment(isMobilePayment);
            companyInfo.setUpdateBy(subject);
            companyInfo.setUpdateTime(new Date());

            int count = companyInfoService.update(companyInfo);

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

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

        return msgResult;
    }

    @ApiOperation(value = "获取部门名称")
    @RequestMapping(value = "getCompanyName", method = RequestMethod.POST)
    public MessageResult<String> getCompanyName(String id) {
        MessageResult<String> msgResult = new MessageResult<>();

        String name = "";

        CompanyInfo companyInfo = companyInfoService.get(id);

        if (companyInfo != null) {
            name = companyInfo.getName();
        }

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

        return msgResult;
    }

    @ApiOperation(value = "所有部门列表")
    @RequestMapping(value = "departmentList", method = RequestMethod.POST)
    public MessageResult<Object> departmentList() {
        MessageResult<Object> msgResult = new MessageResult<>();

        List<CompanyInfo> list = companyInfoService.list();

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

        return msgResult;
    }


    @PostMapping("syncDevice")
    public MessageResult<Integer> syncDevice(String companyId,String deviceId,String mode,@ModelAttribute String subject){
        MessageResult<Integer> messageResult = new MessageResult<>();

        try {
            //同步该单位下所有人或只同步已绑定但未上传照片到设备的人员
            List<PersonInfo> personInfoList = personInfoService.findByCompanyId(companyId);

            int affectCount = 0;

            for (PersonInfo personInfo : personInfoList) {
                if (StringUtils.isNotEmpty(personInfo.getFaceImageUrl())){
                    boolean allowImport = false;

                    if ("all".equals(mode)){
                        allowImport = true;

                        PersonDeviceRelation pdr = personDeviceRelationService.findByDeviceIdAndPersonId(deviceId,personInfo.getId());

                        if(pdr==null){
                            pdr = new PersonDeviceRelation();
                            pdr.setId(UUID.randomUUID().toString());
                            pdr.setDeviceId(deviceId);
                            pdr.setPersonId(personInfo.getId());
                            pdr.setCreateBy(subject);
                            pdr.setDelFlag(false);
                            pdr.setCreateTime(new Date());
                            pdr.setIsBound(false);

                            personDeviceRelationService.insert(pdr);
                        }
                    }
                    else{
                        PersonDeviceRelation pdr = personDeviceRelationService.findByDeviceIdAndPersonId(deviceId,personInfo.getId());

                        if (pdr!=null && (pdr.getIsBound()==null || !pdr.getIsBound())){
                            allowImport = true;
                        }
                    }

                    if(allowImport) {
                        PersonDeviceRelationDTO dto = new PersonDeviceRelationDTO();
                        dto.setPersonId(personInfo.getId());
                        dto.setDeviceId(deviceId);

                        rabbitTemplate.convertAndSend("importImageExchange", "importImage", dto);
                        affectCount++;
                    }
                }
            }

            messageResult.setData(affectCount);
            messageResult.setResult(true);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }
}
