package com.kiisoo.ic.wx.service;

import com.alibaba.fastjson.JSON;
import com.kiisoo.ic.config.WxCpConfiguration;
import com.kiisoo.ic.department.entity.DepartmentDO;
import com.kiisoo.ic.employee.entity.EmployeeDO;
import com.kiisoo.ic.tag.entity.TagDO;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.*;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.WxCpMaJsCode2SessionResult;
import me.chanjar.weixin.cp.bean.WxCpTag;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.kiisoo.ic.config.WxCpConfiguration.APPLICATIONID;
import static com.kiisoo.ic.department.constant.Constants.MAIN_DEPARTMENT_ID;

/**
 * @Description: 企业微信用户管理service
 * @Auther: yechenhao
 * @Date: 2020/4/7 0002 10:06
 * @Version: v1
 */
@Service
public class QWMailListManageService {

    private final Integer applicationid = APPLICATIONID;

    private WxCpService wxCpService;

    /**
     * 增加企业微信用户
     */
    public void addUser(EmployeeDO employeeDO) throws WxErrorException {
        wxCpService = WxCpConfiguration.getCpService(applicationid);
        WxCpUserService userService = wxCpService.getUserService();
        WxCpUser wxCpUser = new WxCpUser();
        BeanUtils.copyProperties(employeeDO,wxCpUser);
        userService.create(wxCpUser);
    }

    public WxCpUser getUser(String cpUserId) throws WxErrorException {
        wxCpService = WxCpConfiguration.getCpService(applicationid);
        WxCpUserService userService = wxCpService.getUserService();
        WxCpUser wx = userService.getById(cpUserId);
        return wx;
    }
    /**
     * 查询企业微信用户
     */
    public List<WxCpUser> syncUser() throws WxErrorException {
        wxCpService = WxCpConfiguration.getCpService(applicationid);
        WxCpUserService userService = wxCpService.getUserService();
        return userService.listByDepartment(MAIN_DEPARTMENT_ID,true,0);
    }
    /**
     * 修改企业微信用户
     */
    public void updateUser(EmployeeDO employeeDO) throws WxErrorException {
        wxCpService = WxCpConfiguration.getCpService(applicationid);
        WxCpUserService userService = wxCpService.getUserService();
        WxCpUser wxCpUser = new WxCpUser();
        BeanUtils.copyProperties(employeeDO,wxCpUser);
        userService.update(wxCpUser);
    }
    /**
     * 修改企业微信用户
     */
    public void deleteUser(String userId) throws WxErrorException {
        wxCpService = WxCpConfiguration.getCpService(applicationid);
        WxCpUserService userService = wxCpService.getUserService();
        userService.delete(userId);
    }

    /**
     * 增加企业微信部门
     */
    public void addDepartment(DepartmentDO departmentDO) throws WxErrorException {
        wxCpService = WxCpConfiguration.getCpService(applicationid);
        WxCpDepartmentService departmentService = wxCpService.getDepartmentService();
        WxCpDepart wxCpDepart = new WxCpDepart();
        BeanUtils.copyProperties(departmentDO,wxCpDepart);
        departmentService.create(wxCpDepart);
    }

    /**
     * 修改企业微信部门
     */
    public void updateDepartment(DepartmentDO departmentDO) throws WxErrorException {
        wxCpService = WxCpConfiguration.getCpService(applicationid);
        WxCpDepartmentService departmentService = wxCpService.getDepartmentService();
        WxCpDepart wxCpDepart = new WxCpDepart();
        BeanUtils.copyProperties(departmentDO,wxCpDepart);
        departmentService.update(wxCpDepart);
    }

    /**
     * 修改企业微信部门
     */
    public void deleteDepartment(Long departmentId) throws WxErrorException {
        wxCpService = WxCpConfiguration.getCpService(applicationid);
        WxCpDepartmentService departmentService = wxCpService.getDepartmentService();
        departmentService.delete(departmentId);
        //todo 删除部门后操作员工
    }

    /**
     * 增加企业微信标签
     */
    public void addTag(TagDO tagDO) throws WxErrorException {
        wxCpService = WxCpConfiguration.getCpService(applicationid);
        WxCpTagService tagService = wxCpService.getTagService();
        tagService.create(tagDO.getName(),tagDO.getId().intValue());
    }

    /**
     * 修改企业微信部门
     */
    public void updateTag(TagDO tagDO) throws WxErrorException {
        wxCpService = WxCpConfiguration.getCpService(applicationid);
        WxCpTagService tagService = wxCpService.getTagService();
        tagService.update(tagDO.getId().toString(),tagDO.getName());
    }

    /**
     * 修改企业微信部门
     */
    public void deleteTag(Long tagId) throws WxErrorException {
        wxCpService = WxCpConfiguration.getCpService(applicationid);
        WxCpTagService tagService = wxCpService.getTagService();
        tagService.delete(tagId.toString());
    }

    /**
     * 获取企业微信所有部门架构
     */
    public List<WxCpDepart> syncDepartment() throws WxErrorException {
        wxCpService = WxCpConfiguration.getCpService(applicationid);
        WxCpDepartmentService departmentService = wxCpService.getDepartmentService();
        return departmentService.list(null);
    }

    public void sendWelcomeMsg(String welcomeCode, String content, File file) throws WxErrorException {
        String mediaType = "";
        wxCpService = WxCpConfiguration.getCpService(applicationid);
        WxCpMediaService mediaService = wxCpService.getMediaService();
        WxMediaUploadResult upload = mediaService.upload(mediaType,file);
        String url = wxCpService.getWxCpConfigStorage().getApiUrl("/cgi-bin/externalcontact/send_welcome_msg");
        String accessToken = wxCpService.getWxCpConfigStorage().getAccessToken();
        Map<String, Object> map = new HashMap<>();
        map.put("access_token", accessToken);


        Map<String, Object> text = new HashMap<>();
        map.put("content", content);


        Map<String, Object> image = new HashMap<>();
        map.put("media_id", upload.getMediaId());

        Map<String, Object> link = new HashMap<>();
        map.put("title", "");
        map.put("picurl", "");
        map.put("desc", "");
        map.put("url", "");

        Map<String, Object> miniprogram = new HashMap<>();
        map.put("title", "");
        map.put("pic_media_id", "");
        map.put("appid", "");
        map.put("page", "");


        map.put("text",text);
        map.put("image",image);
        map.put("link",link);
        map.put("miniprogram",miniprogram);


        String result = wxCpService.post(url, JSON.toJSONString(map));

        //todo判断返回码
    }


    public void sendExternalContactMsg(List<String> cpUserIds, String sender,String content, File file) throws WxErrorException {
        String mediaType = "";
        wxCpService = WxCpConfiguration.getCpService(applicationid);
        WxCpMediaService mediaService = wxCpService.getMediaService();
        WxMediaUploadResult upload = mediaService.upload(mediaType,file);
        String url = wxCpService.getWxCpConfigStorage().getApiUrl("/cgi-bin/externalcontact/send_welcome_msg");
        String accessToken = wxCpService.getWxCpConfigStorage().getAccessToken();
        Map<String, Object> map = new HashMap<>();
        map.put("access_token", accessToken);
        map.put("chat_type", "single");
        map.put("external_userid", cpUserIds);
        map.put("sender", sender);


        Map<String, Object> text = new HashMap<>();
        map.put("content", content);


        Map<String, Object> image = new HashMap<>();
        map.put("media_id", upload.getMediaId());

        Map<String, Object> link = new HashMap<>();
        map.put("title", "");
        map.put("picurl", "");
        map.put("desc", "");
        map.put("url", "");

        Map<String, Object> miniprogram = new HashMap<>();
        map.put("title", "");
        map.put("pic_media_id", "");
        map.put("appid", "");
        map.put("page", "");


        map.put("text",text);
        map.put("image",image);
        map.put("link",link);
        map.put("miniprogram",miniprogram);


        String result = wxCpService.post(url, JSON.toJSONString(map));

        //todo判断返回码
    }

    /**
     * 获取企业微信code
     * @param code
     * @return
     * @throws WxErrorException
     */
    public String getCpUserIdByCode(String code) throws WxErrorException {
        wxCpService = WxCpConfiguration.getCpService(1000043);
        WxCpMaJsCode2SessionResult wxCpMaJsCode2SessionResult = wxCpService.jsCode2Session(code);
        return wxCpMaJsCode2SessionResult.getUserId();
    }

}
