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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gic.commons.util.EntityUtil;
import com.gic.haoban.base.api.common.pojo.dto.WebLoginDTO;
import com.gic.haoban.common.anno.IgnoreLogin;
import com.gic.haoban.common.utils.AuthWebRequestUtil;
import com.gic.haoban.common.utils.HaobanResponse;
import com.gic.haoban.manage.api.dto.*;
import com.gic.haoban.manage.api.enums.SecretTypeEnum;
import com.gic.haoban.manage.api.service.*;
import com.gic.haoban.manage.web.config.Config;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.vo.ApplicationVO;
import com.gic.wechat.api.service.qywx.QywxSuiteApiService;
import com.gic.wechat.api.service.qywx.QywxUserApiService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
public class ApplicationController extends WebBaseController {

    private static final Logger log = LogManager.getLogger(ApplicationController.class);
    @Autowired
    private ApplicationApiService applicationApiService;
    @Autowired
    private QywxSuiteApiService qywxSuiteApiService;
    @Autowired
    private WxApplicationApiService wxApplicationApiService;
    @Autowired
    private WxEnterpriseApiService wxEnterpriseApiService;
    @Autowired
    private WxEnterpriseRelatedApiService wxEnterpriseRelatedApiService;
    @Autowired
    private Config config;
    @Autowired
    private DepartmentApiService departmentApiService;
    @Autowired
    private ApplicationSettingApiService applicationSettingApiService;
    @Autowired
    private DealSyncOperationApiService dealSyncOperationApiService;

    @Autowired
    private QywxUserApiService qywxUserApiService;

    @RequestMapping("application-list")
    public HaobanResponse applicationList() {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        List<ApplicationDTO> list = applicationApiService.listApplicationByWxEnterpriseId(wxEnterpriseId);
        return resultResponse(HaoBanErrCode.ERR_1, list);
    }

    @IgnoreLogin
    @RequestMapping("application-open-close-list")
    public HaobanResponse applicationList(String wxEnterpriseId) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser() ;
        if(null != loginUser) {
            wxEnterpriseId = loginUser.getWxEnterpriseId() ;
        }
        if (StringUtils.isAnyBlank(wxEnterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        Map<String, Object> map = new HashMap<>();
        List<ApplicationDTO> list = applicationApiService.listApplicationByWxEnterpriseId(wxEnterpriseId);
        Iterator<ApplicationDTO> it = list.iterator();
        // 判断模板
        List<String> tempIdList = null ;
        List<ApplicationDTO> tempList = this.applicationApiService.listApplicationByWxEnterpriseId(wxEnterpriseId) ;
        if(CollectionUtils.isNotEmpty(tempList)) {
           tempIdList = tempList.stream().map(dto->dto.getApplicationId()).collect(Collectors.toList()) ;
        }
        while (it.hasNext()) {
            ApplicationDTO s = it.next();
            // 我的客户、营销任务、看数据、云日报、月指标、商品中心、订单评价、扫码核销、E袋洗、佣金结算
            if(Arrays.asList("11111","11114","11121","11122").contains(s.getApplicationId())) {
                it.remove();
            }
            // 11123E袋洗   11124佣金结算
            if(CollectionUtils.isNotEmpty(tempIdList)) {
                if(Arrays.asList("11124").contains(s.getApplicationId())) {
                    if(!tempIdList.contains(s.getApplicationId())) {
                        it.remove();
                    }
                }
            }
        }
        //开启
        List<String> applicationIds = list.stream().map(s -> s.getApplicationId()).collect(Collectors.toList());
        List<ApplicationSettingDTO> openList = applicationSettingApiService.listOpenByWxEnterpriseIdAndApplicationIds(wxEnterpriseId, applicationIds);
        if(null == openList) {
            openList = new ArrayList<>() ;
        }
        List<String> openApplicationIds = openList.stream().map(s -> s.getApplicationId()).collect(Collectors.toList());
        List<ApplicationVO> allList = new ArrayList<>();
        list.forEach(item->{
            ApplicationVO vo = EntityUtil.changeEntity(ApplicationVO.class, item) ;
            if(openApplicationIds.contains(vo.getApplicationId())) {
                vo.setOpenFlag(1);
            }else {
                vo.setOpenFlag(0);
            }
            allList.add(vo) ;
        });
        map.put("allList", allList) ;
        if(null != loginUser) {
            String enterpriseId = loginUser.getEnterpriseId() ;
            EnterpriseDetailDTO dto = this.wxEnterpriseRelatedApiService.getByEnterpriseId(wxEnterpriseId, enterpriseId) ;
            Integer clerkEditInfo = dto.getClerkEditFlag() ;
            map.put("clerkEditInfo", ClerkEditInfoDTO.info(clerkEditInfo)) ;
        }
        return resultResponse(HaoBanErrCode.ERR_1, map);
    }

    @RequestMapping("open-or-close")
    public HaobanResponse saveOpenOrClose(String dataJson) {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        log.info("dataJson={}",dataJson);
        if(StringUtils.isBlank(dataJson)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        JSONArray jsonArr = JSONArray.parseArray(dataJson) ;
        if(jsonArr.size()<=0) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        this.applicationSettingApiService.saveSetting(wxEnterpriseId,jsonArr);
        return resultResponse(HaoBanErrCode.ERR_1);
    }
    
    @RequestMapping("save-clerk-edit-flag")
    public HaobanResponse saveClerkEditFlag(ClerkEditInfoDTO clerkEditInfo) {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        String enterpriseId = login.getEnterpriseId();
        this.wxEnterpriseRelatedApiService.saveClerkEditFlag(wxEnterpriseId, enterpriseId, ClerkEditInfoDTO.getValue(clerkEditInfo));
        return resultResponse(HaoBanErrCode.ERR_1);
    }


    @RequestMapping("has-bind-contract")
    public HaobanResponse hasBindContract() {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        WxEnterpriseDTO enterpriseDTO = this.wxEnterpriseApiService.getOne(wxEnterpriseId);
        if (enterpriseDTO != null) {
            SecretSettingDTO secretSetting = wxEnterpriseApiService.getSecretSetting(enterpriseDTO.getWxEnterpriseId(), SecretTypeEnum.CUSTOMIZED_APP.getVal(), null);
            if (null == secretSetting || secretSetting.getCheckFlag() == 0) {
                log.info("没有配置secret：{}", JSONObject.toJSONString(enterpriseDTO));
                return resultResponse(HaoBanErrCode.ERR_1, true);
            }
            if (enterpriseDTO.getContactFlag() != null && enterpriseDTO.getContactFlag() == 0) {
                String taskId = dealSyncOperationApiService.createQywxTask(wxEnterpriseId, "同步企业微信架构", login.getClerkId(), "首次同步企业微信架构");
                if (StringUtils.isBlank(taskId)) {
                    log.info("【是否绑定】taskId={}", taskId);
                    return resultResponse(HaoBanErrCode.ERR_1, true);
                }
                dealSyncOperationApiService.dealQywxDepartment(taskId, wxEnterpriseId);
                enterpriseDTO.setContactFlag(1);
                wxEnterpriseApiService.update(enterpriseDTO);

                applicationApiService.insertApplicationRelation(wxEnterpriseId);
            }
        }
        return resultResponse(HaoBanErrCode.ERR_1, true);
    }


    /**
     * 初始化同步企业微信架构
     *
     * @return
     */
    @RequestMapping("init-wx-department")
    public HaobanResponse initWxDepartment() {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        WxEnterpriseDTO enterpriseDTO = this.wxEnterpriseApiService.getOne(wxEnterpriseId);
        if (enterpriseDTO != null) {
            SecretSettingDTO secretSetting = wxEnterpriseApiService.getSecretSetting(enterpriseDTO.getWxEnterpriseId(), SecretTypeEnum.CUSTOMIZED_APP.getVal(), null);
            if (null == secretSetting || secretSetting.getCheckFlag() == 0) {
                log.info("没有配置secret");
                return resultResponse(HaoBanErrCode.ERR_1, false);
            }
            if (StringUtils.isNotBlank(secretSetting.getSecretVal()) && enterpriseDTO.getContactFlag() != null) {
                String taskId = dealSyncOperationApiService.createQywxTask(wxEnterpriseId, "后门同步企业微信架构", login.getClerkId(), "后门同步企业微信架构");
                if (StringUtils.isBlank(taskId)) {
                    return resultResponse(HaoBanErrCode.ERR_1, false);
                }
                dealSyncOperationApiService.dealQywxDepartment(taskId, wxEnterpriseId);
            }
        }
        return resultResponse(HaoBanErrCode.ERR_1, true);
    }

    @RequestMapping("get-auth-url")
    public HaobanResponse getAuthUrl() {
        String suiteId = config.getSuiteId();
        log.info("通讯录应用ID：{}", suiteId);
        String redictUrl = config.getHost() + "callback";
        String authorizationUrl = this.qywxSuiteApiService.getGrantAuthorizationUrl(suiteId, redictUrl);
        return resultResponse(HaoBanErrCode.ERR_1, authorizationUrl);
    }

    @RequestMapping("callback")
    public void callback(String auth_code, HttpServletResponse response) {
        String suiteId = config.getSuiteId();
        String result = this.qywxSuiteApiService.corpAuth(suiteId, auth_code);
        log.info("企业微信回调结果：{}. {}", auth_code, result);
        QywxCorpInfoDTO dto = JSON.parseObject(result, QywxCorpInfoDTO.class);
        WxApplicationDTO applicationDTO = new WxApplicationDTO();
        WxEnterpriseDTO enterpriseDTO = this.wxEnterpriseApiService.getEnterpriseBycorpId(dto.getCorpid());
        if (enterpriseDTO != null) {
            applicationDTO.setName(dto.getAgentName());
            applicationDTO.setWxEnterpriseId(enterpriseDTO.getWxEnterpriseId());
            applicationDTO.setAgentId(dto.getAgentid());
            applicationDTO.setApplicationType(1);
            applicationDTO.setAgentName(dto.getAgentName());
            applicationDTO.setSiteId(dto.getSuiteId());
            wxApplicationApiService.addSuite(applicationDTO);
            SecretSettingDTO secretSetting = wxEnterpriseApiService.getSecretSetting(enterpriseDTO.getWxEnterpriseId(), SecretTypeEnum.CUSTOMIZED_APP.getVal(), null);
            if (null == secretSetting || secretSetting.getCheckFlag() == 0) {
                log.info("没有配置secret：{}", JSONObject.toJSONString(enterpriseDTO));
                return;
            }
            this.departmentApiService.initwxDepartment(dto.getCorpid(), secretSetting.getSecretVal(), enterpriseDTO.getWxEnterpriseId());
            enterpriseDTO.setContactFlag(1);
            wxEnterpriseApiService.update(enterpriseDTO);
        }
        String redirectUri = config.getHost() + "index";
        redirectUri = redirectUri.replace("haoban-manage3-web", "haoban-3/#");
        try {
            response.sendRedirect(redirectUri);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("cancal-suite")
    @IgnoreLogin
    public HaobanResponse cancelSuite(String corpId, String suiteId) {
        this.wxApplicationApiService.cancelSuite(corpId, suiteId);
        return resultResponse(HaoBanErrCode.ERR_0, "s");
    }


    @RequestMapping("list-external-user")
    @IgnoreLogin
    public Object list(String corpid, String suiteid, String userid) {
        return this.qywxUserApiService.listExternalUserid(corpid, suiteid, userid);
    }

    @RequestMapping("corp-external-user")
    @IgnoreLogin
    public Object corpuserid(String corpid, String suiteid) {
        return this.qywxUserApiService.listCorpExternalUser(corpid, suiteid);
    }

    @RequestMapping("get-external-user-info")
    @IgnoreLogin
    public Object userInfo(String corpid, String suiteid, String userid) {
        return resultResponse(HaoBanErrCode.ERR_0, this.qywxUserApiService.getExternalUseridInfo(corpid, suiteid, userid));
    }

    @RequestMapping("get-external-unionid")
    @IgnoreLogin
    public Object userInfoUninid(String corpid, String suiteid, String unionid) {
        return resultResponse(HaoBanErrCode.ERR_0, this.qywxUserApiService.getExternalUseridByUnionid(corpid, suiteid, unionid));
    }

    /**
     * 初始化应用
     *
     * @param wxEnterpriseId
     * @return
     */
    @RequestMapping("init-application-relation")
    @IgnoreLogin
    public HaobanResponse insertApplicationRelation(String wxEnterpriseId) {
        applicationApiService.insertApplicationRelation(wxEnterpriseId);
        return resultResponse(HaoBanErrCode.ERR_1);
    }
}
