package com.kiisoo.ic.wx.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kiisoo.ic.config.WxCpConfiguration;
import com.kiisoo.ic.customer.entity.OpCustomer;
import com.kiisoo.ic.customer.mapper.OpCustomerDOMapper;
import com.kiisoo.ic.customer.mapper.OpSellerCustomerRelationDOMapper;
import com.kiisoo.ic.department.entity.DepartmentDO;
import com.kiisoo.ic.employee.entity.CpUserCustomerRelationDO;
import com.kiisoo.ic.employee.entity.EmployeeDO;
import com.kiisoo.ic.employee.entity.PrivilageCpUserDO;
import com.kiisoo.ic.employee.mapper.PrivilageCpUserDOMapper;
import com.kiisoo.ic.store.mapper.PrivilageCpUserStoreDOMapper;
import com.kiisoo.ic.tag.entity.TagDO;
import lombok.extern.slf4j.Slf4j;
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.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
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
@Slf4j
public class QWMailListManageService {

    private final Integer applicationid = APPLICATIONID;

    private WxCpService wxCpService;

    @Autowired
    private PrivilageCpUserStoreDOMapper privilageCpUserStoreDOMapper;

    @Autowired
    private PrivilageCpUserDOMapper privilageCpUserDOMapper;

    @Autowired
    private OpSellerCustomerRelationDOMapper opSellerCustomerRelationDOMapper;

    @Autowired
    private OpCustomerDOMapper opCustomerDOMapper;

    /**
     * 增加企业微信用户
     */
    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 Map<String,String> getCpUserIdByCode(String code) throws WxErrorException {
        Map<String,String> result = new HashMap<> ();
        wxCpService = WxCpConfiguration.getCpService(applicationid);
        WxCpMaJsCode2SessionResult wxCpMaJsCode2SessionResult = wxCpService.jsCode2Session(code);
        String userId = wxCpMaJsCode2SessionResult.getUserId();
        String sessionKey = wxCpMaJsCode2SessionResult.getSessionKey();
        result.put("cpUserId",userId);
        result.put("sessionKey",sessionKey);
        return result;
    }

    public List<WxCpUserExternalContactInfo> getCustomer(String cpUserId) throws WxErrorException {
        //查询店铺id——店铺ID存在说明该账号的客户都绑在店上，不存在则说明绑在账号上
        Long storeId = privilageCpUserStoreDOMapper.selectOneByCpUserId(cpUserId);

        //账号一定存在，不存在则返回null
        QueryWrapper<PrivilageCpUserDO> cpQw = new QueryWrapper<>();
        cpQw.eq("cp_user_id",cpUserId).last("limit 1");
        PrivilageCpUserDO privilageCpUserDO = privilageCpUserDOMapper.selectOne(cpQw);
        if (privilageCpUserDO == null){
            return null;
        }

        //获取第三方接口方法
        List<WxCpUserExternalContactInfo> customers = null;
        wxCpService = WxCpConfiguration.getCpService(applicationid);
        WxCpExternalContactService externalContactService = wxCpService.getExternalContactService();
        List<String> customerStrs = externalContactService.listExternalContacts(cpUserId);
        //查询客户列表为空则直接返回
        if (CollectionUtils.isNotEmpty(customerStrs)){
            customers = new ArrayList<>();
            for (String customerStr:customerStrs){
                //查询该客户id的关系是否存在
                QueryWrapper<OpCustomer> customerQueryWrapper = new QueryWrapper<>();
                customerQueryWrapper.eq("external_userid",customerStr).last("limit 1");
                OpCustomer opCustomer = opCustomerDOMapper.selectOne(customerQueryWrapper);
                //客户都不存在则直接下一步
                if (opCustomer != null){
                    Long relationId = opSellerCustomerRelationDOMapper.selectSellerCustomerRelation(opCustomer.getId(), privilageCpUserDO.getId(), storeId);
                    //关系存在则不查询明细
                    if (relationId != null){
                        continue;
                    }
                }
                try{
                    WxCpUserExternalContactInfo contactDetail = externalContactService.getContactDetail(customerStr);
                    customers.add(contactDetail);
                }catch (Exception e){
                    log.error("企业微信查询客户明细失败",e);
                    continue;
                }


            }
        }
        return customers;
    }
}
