package com.gic.haoban.manage.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.Page;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.dto.ClerkListDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.enterprise.api.dto.EnterpriseDTO;
import com.gic.enterprise.api.dto.GicTreeDTO;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.enterprise.api.service.StoreGroupService;
import com.gic.enterprise.api.service.StoreService;
import com.gic.haoban.base.api.common.BasePageInfo;
import com.gic.haoban.base.api.common.Constant;
import com.gic.haoban.base.api.common.PageResult;
import com.gic.haoban.base.api.common.ServiceResponse;
import com.gic.haoban.base.api.common.pojo.dto.WebLoginDTO;
import com.gic.haoban.common.utils.AuthWebRequestUtil;
import com.gic.haoban.common.utils.EntityUtil;
import com.gic.haoban.common.utils.HaobanResponse;
import com.gic.haoban.manage.api.dto.DepartmentDTO;
import com.gic.haoban.manage.api.dto.DepartmentShortDTO;
import com.gic.haoban.manage.api.dto.StaffDTO;
import com.gic.haoban.manage.api.dto.StaffDepartmentRelatedDTO;
import com.gic.haoban.manage.api.dto.WxApplicationDTO;
import com.gic.haoban.manage.api.dto.WxEnterpriseDTO;
import com.gic.haoban.manage.api.service.DepartmentApiService;
import com.gic.haoban.manage.api.service.StaffApiService;
import com.gic.haoban.manage.api.service.StaffDepartmentRelatedApiService;
import com.gic.haoban.manage.api.service.WxApplicationApiService;
import com.gic.haoban.manage.api.service.WxEnterpriseApiService;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.vo.DepartmentChainVO;
import com.gic.haoban.manage.web.vo.DepartmentVO;
import com.gic.redis.data.util.RedisUtil;
import com.gic.wechat.api.service.qywx.QywxSuiteApiService;

import cn.hutool.core.collection.CollectionUtil;

@RestController
public class DepartmentContoller extends WebBaseController {

    private static final Logger logger = LoggerFactory.getLogger(DepartmentContoller.class);
    @Autowired
    private DepartmentApiService departmentApiService;
    @Autowired
    private StoreGroupService storeGroupService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private StaffApiService staffApiService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private ClerkService clerkService;
    @Autowired
    private StaffDepartmentRelatedApiService staffDepartmentRelatedApiService;
    @Autowired
    private WxApplicationApiService wxApplicationApiService ;
    @Autowired
    private WxEnterpriseApiService wxEnterpriseApiService ;
    @Autowired
    private QywxSuiteApiService qywxSuiteApiService ;


    @RequestMapping("department-list")
    public HaobanResponse departmentList(String parentId, BasePageInfo pageInfo, String keyWord) {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        logger.info("【部门列表】wxEnterpriseId={}", wxEnterpriseId);

        Page<DepartmentDTO> page = new Page<DepartmentDTO>();
        List<DepartmentDTO> list = new ArrayList<DepartmentDTO>();
        if (StringUtils.isNotBlank(parentId)) {
            page = departmentApiService.pageByParentId(parentId, keyWord, pageInfo);
        } else {
            DepartmentDTO dto = departmentApiService.getRootByEnterpriseId(wxEnterpriseId);
            if(null == dto) {
                return new HaobanResponse(-1,"根部门异常,请重新同步通讯录") ;
            }
            list.add(dto);
            page.setTotalPage(1);
            page.setTotalCount(1);
            page.setResult(list);
        }
        List<DepartmentDTO> result = page.getResult();
        for (DepartmentDTO departmentDTO : result) {
            String chainId = departmentDTO.getChainId() + Constant.ID_SEPARATOR + departmentDTO.getDepartmentId();
            List<DepartmentDTO> sonList = departmentApiService.listByChainId(chainId, wxEnterpriseId);
            int staffCount = 0;
            List<String> departmentIds = new ArrayList<>();
            departmentIds.add(departmentDTO.getDepartmentId());
            for (DepartmentDTO departmentDTO2 : sonList) {
                departmentIds.add(departmentDTO2.getDepartmentId());
            }
            staffCount += staffApiService.countByDepartmentIds(departmentIds);
            departmentDTO.setStaffCount(staffCount);
            departmentDTO.setHasSonNode(departmentApiService.hasSonNode(departmentDTO.getDepartmentId()));
        }
        PageResult<DepartmentDTO> pageVo = new PageResult<>();
        pageVo.setList(result);
        pageVo.setPageNum(page.getCurrentPage());
        pageVo.setPages(page.getPages());
        pageVo.setPageSize(page.getPageSize());
        pageVo.setTotal(page.getTotalCount());
        return resultResponse(HaoBanErrCode.ERR_1, pageVo);

    }

    @RequestMapping("department-list-level")
    public HaobanResponse departmentLevelList(String parentId) {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        logger.info("【部门层级列表】wxEnterpriseId={}", wxEnterpriseId);
        List<DepartmentDTO> list = new ArrayList<DepartmentDTO>();
        if (StringUtils.isNotBlank(parentId)) {
            list = departmentApiService.listByParentId(parentId);
        } else {
            DepartmentDTO dto = departmentApiService.getRootByEnterpriseId(wxEnterpriseId);
            if(null == dto) {
                return new HaobanResponse(-1,"根部门异常,请重新同步通讯录") ;
            }
            list.add(dto);
        }
        Set<String> enterpriseSet = new HashSet<>();
        for (DepartmentDTO departmentDTO : list) {
            String relatedId = departmentDTO.getRelatedId();
            if (StringUtils.isBlank(relatedId)) {
                departmentDTO.setBindFlag(0);
            } else {
                String gicEnterpriseId = departmentDTO.getEnterpriseId();
                enterpriseSet.add(gicEnterpriseId);
                departmentDTO.setBindFlag(1);
            }

            departmentDTO.setHasSonNode(departmentApiService.hasSonNode(departmentDTO.getDepartmentId()));
        }

        Map<String, EnterpriseDTO> enterpriseMap = new HashMap<>();
        List<String> enterpriseSetList = new ArrayList<>(enterpriseSet);
        logger.info("size大小为=====================》{}", enterpriseSetList.size());
        List<EnterpriseDTO> enterprises = enterpriseService.listEnterpriseByIds(enterpriseSetList);
        if (CollectionUtil.isNotEmpty(enterprises)) {
            for (EnterpriseDTO enterprise : enterprises) {
                enterpriseMap.put(enterprise.getEnterpriseId(), enterprise);
            }
        }
        for (DepartmentDTO departmentDTO : list) {
            String enterpriseId = departmentDTO.getEnterpriseId();
            if (StringUtils.isNotBlank(enterpriseId)) {
                EnterpriseDTO enterprise = enterpriseMap.get(enterpriseId);
                if (enterprise != null) {
                    departmentDTO.setGicEnterpriseName(enterprise.getEnterpriseName());
                }
            }

            departmentDTO.setHasSonNode(departmentApiService.hasSonNode(departmentDTO.getDepartmentId()));
        }

        return resultResponse(HaoBanErrCode.ERR_1, EntityUtil.changeEntityListByJSON(DepartmentVO.class, list));

    }

    @RequestMapping("department-sel")
    public HaobanResponse departmentSel(String departmentId) {
        DepartmentDTO dto = departmentApiService.selectById(departmentId);
        if (dto == null || dto.getStatusFlag() == 0) {
            return resultResponse(HaoBanErrCode.ERR_10003);
        }

        return resultResponse(HaoBanErrCode.ERR_1, dto);

    }

    @RequestMapping("department-recycle-count")
    public HaobanResponse departmentRecycleCount() {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        Integer count = departmentApiService.departmentRecycleCount(wxEnterpriseId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("count", count);
        map.put("syncDate", RedisUtil.getCache("haoban-sync-department-" + wxEnterpriseId));
        return resultResponse(HaoBanErrCode.ERR_1, map);

    }

    @RequestMapping("department-chain")
    public HaobanResponse departmentChain(String departmentId) {
        if (StringUtils.isBlank(departmentId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        DepartmentDTO department = departmentApiService.selectById(departmentId);
        if (department == null) {
            return resultResponse(HaoBanErrCode.ERR_10003);
        }
        String chainId = departmentId;
        while (department != null) {
            department = departmentApiService.selectById(department.getParentDepartmentId());
            if (department != null) {
                chainId = department.getDepartmentId() + Constant.ID_SEPARATOR + chainId;
            }
        }
        String[] chainIdArr = chainId.split(Constant.ID_SEPARATOR);
        List<DepartmentChainVO> list = new ArrayList<>();
        for (String string : chainIdArr) {
            DepartmentDTO son = departmentApiService.selectById(string);
            DepartmentChainVO chain = EntityUtil.changeEntityByJSON(DepartmentChainVO.class, son);
            if (son != null) {
                list.add(chain);
            }
        }
        return resultResponse(HaoBanErrCode.ERR_1, list);
    }

    @RequestMapping("department-batch-sync-success")
    public HaobanResponse syncSuccess(String syncKey) {
        if (RedisUtil.getCache(syncKey) == null) {
            return resultResponse(HaoBanErrCode.ERR_1, true);
        } else {
            return resultResponse(HaoBanErrCode.ERR_1, false);
        }
    }


    @RequestMapping("unbind-department-list")
    public HaobanResponse unbindDepartmentList(String departmentId, String enterpriseId, Integer type) {
        List<GicTreeDTO> departmentList = storeGroupService.listGicTree(enterpriseId, type, departmentId);
        logger.info("【未绑定部门列表】enterpriseId={},type={},departmentId={},departmentList={}", enterpriseId, type, departmentId, JSON.toJSONString(departmentList));
        List<DepartmentDTO> dtoList = new ArrayList<DepartmentDTO>();
        for (GicTreeDTO departmentDTO : departmentList) {
            DepartmentDTO dto = departmentApiService.selectByRelatedId(departmentDTO.getId());
            if (dto == null) {
                if (departmentDTO.getType() == 1) {
                    continue;
                }
                DepartmentDTO unBindDTO = new DepartmentDTO();
                unBindDTO.setRelatedId(departmentDTO.getId());
                Integer storeType = departmentDTO.getType();
                if (storeType == 3) {
                    unBindDTO.setIsStore(1);
                } else {
                    unBindDTO.setIsStore(0);
                }
                unBindDTO.setDepartmentName(departmentDTO.getName());
                unBindDTO.setDepartmentId(departmentDTO.getId());
                unBindDTO.setType(departmentDTO.getType());
                unBindDTO.setLevel(departmentDTO.getLevel());
                unBindDTO.setHasSonNode(departmentDTO.isHasChildren());
                dtoList.add(unBindDTO);
            }
        }

        return resultResponse(HaoBanErrCode.ERR_1, EntityUtil.changeEntityListByJSON(DepartmentVO.class, dtoList));

    }


    @RequestMapping("department-recycle-list")
    public HaobanResponse departmentRecycleList(String keyWord, Integer storeFlag, BasePageInfo pageInfo) {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        Integer recycleFlag = 1;
        Page<DepartmentDTO> page = departmentApiService.pageDepartmentByParams(pageInfo, wxEnterpriseId, keyWord, storeFlag, recycleFlag);
        List<DepartmentDTO> list = page.getResult();
        for (DepartmentDTO departmentDTO : list) {
            if (departmentDTO.getIsStore() != null && departmentDTO.getIsStore() == 1) {
                StoreDTO store = storeService.getStore(departmentDTO.getRelatedId());
                if (store != null) {
                    departmentDTO.setStoreCode(store.getStoreCode());
                }
            }
        }
        PageResult<DepartmentDTO> pageVo = new PageResult<>();
        pageVo.setList(list);
        pageVo.setPageNum(page.getCurrentPage());
        pageVo.setPages(page.getPages());
        pageVo.setPageSize(page.getPageSize());
        pageVo.setTotal(page.getTotalCount());
        return resultResponse(HaoBanErrCode.ERR_1, pageVo);

    }


    @RequestMapping("department-cache")
    public HaobanResponse departmentCache(String wxEnterpriseId) {
        RedisUtil.delCache("haoban-sync-department-" + wxEnterpriseId);
        return resultResponse(HaoBanErrCode.ERR_1);

    }

    @RequestMapping("department-user-init")
    public HaobanResponse departmentInit(String corpid, String suiteid, String wxEnterpriseId, Integer wxDepartmentId) {
        RedisUtil.delCache("haoban-user-department-" + wxEnterpriseId);
        //TODO 这里有段代码没提交上来
        staffApiService.initWxUser(corpid, suiteid, wxEnterpriseId, wxDepartmentId, "");
        return resultResponse(HaoBanErrCode.ERR_1);

    }


    @RequestMapping("department-search")
    public HaobanResponse departmentSearch(String search) {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        if (StringUtils.isBlank(wxEnterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_6);
        }
        List<DepartmentShortDTO> list = departmentApiService.searchDepartment(search, wxEnterpriseId);
        return resultResponse(HaoBanErrCode.ERR_1, list);

    }

    /**
     * 加载
     *
     * @return
     */
    @RequestMapping("department-list-cache")
    public HaobanResponse departmentCachelist() {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        if (StringUtils.isBlank(wxEnterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_6);
        }
        Object cache = RedisUtil.getLocalCache("department-list-cache-" + wxEnterpriseId);
        if (null == cache) {
            List<DepartmentShortDTO> list = departmentApiService.listAllDepartment(wxEnterpriseId);
            RedisUtil.setLocalCache("department-list-cache-" + wxEnterpriseId, list, 60*60*24L);
            return resultResponse(HaoBanErrCode.ERR_1, list);
        } else {
            return resultResponse(HaoBanErrCode.ERR_1, cache);
        }
    }
}
