package com.cftech.base.org.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cftech.base.org.model.Qytag;
import com.cftech.base.org.model.Qyuser;
import com.cftech.base.org.service.QytagService;
import com.cftech.base.org.service.QyuserService;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.QyTokenUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 企业号标签同步
 *
 * @author Neil
 */
@Slf4j
@Component
public class QyTagUtil {


    @Autowired
    private QyTokenUtil qyTokenUtil;
    @Autowired
    private QytagService qytagService;
    @Autowired
    private QyuserService qyuserService;

    public int create(Qytag qytag) {
        JSONObject postObj = new JSONObject();
        postObj.put("tagname", qytag.getName());
        JSONObject retObj = WxApiUtils.tagCreate(qyTokenUtil.getToken(qytag.getAccountsId()), postObj);

        if (retObj.getIntValue("errcode") == 0) {
            return retObj.getIntValue("tagid");
        }
        return -1;
    }

    public boolean update(Qytag qytag) {

        JSONObject postObj = new JSONObject();

        postObj.put("tagid", qytag.getWxtagId());
        postObj.put("tagname", qytag.getName());

        JSONObject retObj = WxApiUtils.tagUpdate(qyTokenUtil.getToken(qytag.getAccountsId()), postObj);
        return retObj.getIntValue("errcode") == 0;
    }


    public boolean delete(Qytag qytag) {
        JSONObject retObj = WxApiUtils.tagDelete(qyTokenUtil.getToken(qytag.getAccountsId()), qytag.getWxtagId());
        return retObj.getIntValue("errcode") == 0;
    }


    public JSONObject sync(Long accountId) {
        JSONObject retObj = new JSONObject();
        int successCreateCount = 0;
        int successUpdateCount = 0;
        int failureUpdateCount = 0;

        JSONObject tagRetObj = WxApiUtils.tagList(qyTokenUtil.getToken(accountId));
        if (tagRetObj.getIntValue("errcode") == 0) {
            clearStatus(accountId);
            //获取成功
            JSONArray taglist = tagRetObj.getJSONArray("taglist");
            for (int i = 0, j = taglist.size(); i < j; i++) {
                JSONObject tagObj = taglist.getJSONObject(i);
                String tagId = tagObj.getString("tagid");
                Qytag qytag = findByXxtagId(accountId, tagId);
                if (qytag == null) {
                    //新增
                    qytag = new Qytag();
                    qytag.setAccountsId(accountId);
                    qytag.setName(tagObj.getString("tagname"));
                    qytag.setWxtagId(tagId);
                    qytagService.save(qytag);
                    successCreateCount++;
                } else {
                    //更新
                    qytag.setName(tagObj.getString("tagname"));
                    qytag.setStatus("0");
                    qytagService.update(qytag);
                    successUpdateCount++;
                }
            }
            failureUpdateCount = getSyncCount(accountId);
        }


        retObj.put("successCreateCount", successCreateCount);
        retObj.put("successUpdateCount", successUpdateCount);
        retObj.put("failureUpdateCount", failureUpdateCount);
        return retObj;
    }

    public void clearStatus(Long accountId) {
        Conds conds = new Conds();
        conds.equal("del_flag", 0);
        conds.equal("accounts_id", accountId);
        String status = "3"; //同步中
        qytagService.changeStatus(status, conds);
    }

    /**
     * 获取还有多少个正在同步中的状态
     *
     * @param accountId
     * @return
     */
    public int getSyncCount(Long accountId) {
        Conds conds = new Conds();
        conds.equal("del_flag", 0);
        conds.equal("accounts_id", accountId);
        conds.equal("status", "3");
        Integer counts = qytagService.count(conds);
        return counts;
    }

    /**
     * 返回是否存在标签
     *
     * @param accountId 微信账号
     * @param wxtagId   微信的标签Id
     * @return Qyuser
     */
    public Qytag findByXxtagId(Long accountId, String wxtagId) {
        Conds conds = new Conds();
        conds.equal("del_flag", 0);
        conds.equal("accounts_id", accountId);
        conds.equal("wxtag_id", wxtagId);
        return qytagService.fetchSearchByConds(conds);
    }


    public void clearUserTagIds(Long accountId) {
        Conds conds = new Conds();
        conds.equal("del_flag", 0);
        conds.equal("accounts_id", accountId);
        String tagIds = ""; //同步中
        qyuserService.changeTagIds(tagIds, conds);
    }

    public List<Qytag> findAllByAccountsId(Long accountId) {
        Sort sort = new Sort("create_time", OrderType.DESC);
        Conds conds = new Conds();
        conds.equal("del_flag", 0);
        conds.equal("accounts_id", accountId);
        return qytagService.fetchSearchByPage(conds, sort, 0, 0);
    }

    /**
     * 填加微信标签至用户
     *
     * @param accountId 微信账号
     * @param tagId     需要添加的标签Id
     * @param wxuserIds 需要添加标签的wxuserid， 注意不是user的id
     */
    public void appendTagUsers(Long accountId, Long tagId, List<String> wxuserIds) {
        Conds conds = new Conds();
        conds.equal("del_flag", 0);
        conds.equal("accounts_id", accountId);
        conds.in("wxuser_id", wxuserIds.toArray());
        qyuserService.appendTagids(tagId + ",", conds);
    }

    /**
     * 同步微信中的标签用户
     *
     * @param accountId
     * @return
     */
    public JSONObject syncUsers(Long accountId) {
        JSONObject retObj = new JSONObject();
        int tagCount = 0;
        JSONArray successListObj = new JSONArray();

        List<Qytag> qytagList = findAllByAccountsId(accountId);
        tagCount = qytagList.size();
        if (qytagList.size() > 0) {
            clearUserTagIds(accountId);
            for (Qytag qytag : qytagList) {
                int userWxCount = 0;
                JSONObject successObj = new JSONObject();
                successObj.put("tag", qytag.getName());

                String wxTagId = qytag.getWxtagId();
                JSONObject retTagUserObj = WxApiUtils.tagUserList(qyTokenUtil.getToken(qytag.getAccountsId()), wxTagId);
                if (retTagUserObj.getIntValue("errcode") == 0) {
                    JSONArray tagUserList = retTagUserObj.getJSONArray("userlist");
                    userWxCount = tagUserList.size();
                    List<String> wxUserids = Lists.newArrayList();
                    for (int i = 0, j = userWxCount; i < j; i++) {
                        JSONObject userObj = tagUserList.getJSONObject(i);
                        wxUserids.add(userObj.getString("userid"));
                    }

                    appendTagUsers(accountId, qytag.getId(), wxUserids);

                    successObj.put("userWxCount", userWxCount);
                }
                successListObj.add(successObj);
            }
        }


        retObj.put("tagCount", tagCount);
        retObj.put("message", successListObj);
        return retObj;

    }

    public static boolean useLoop(String[] arr, String targetValue) {
        for (String s : arr) {
            if (s.equals(targetValue))
                return true;
        }
        return false;
    }

    /**
     * 传入用户，同步微信的标签定义
     *
     * @param qyuser
     */
    public void syncTag(Qyuser qyuser) {
        List<Qytag> qytagList = findAllByAccountsId(qyuser.getAccountsId());
        String[] tagIds = qyuser.getTagIds().split(",");
        JSONArray userList = new JSONArray();
        userList.add(qyuser.getWxuserId());
        if (qytagList.size() > 0) {
            for (Qytag qytag : qytagList) {
                JSONObject postObj = new JSONObject();
                postObj.put("tagid", qytag.getWxtagId());
                postObj.put("userlist", userList);
                WxApiUtils.tagDeleteUsers(qyTokenUtil.getToken(qytag.getAccountsId()), postObj);

                if (useLoop(tagIds, "" + qytag.getId())) {
                    WxApiUtils.tagAddUsers(qyTokenUtil.getToken(qytag.getAccountsId()), postObj);
                }
            }
        }
    }
}
