package com.cftech.base.org.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cftech.base.org.model.OrgUnit;
import com.cftech.base.org.service.OrgUnitService;
import com.cftech.core.sql.Conds;
import com.cftech.core.util.QyTokenUtil;
import com.cftech.sys.security.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 企业号组织同步
 *
 * @author Neil
 */
@Slf4j
@Component
public class QyOrgUtil {


    private final QyTokenUtil qyTokenUtil;
    private final OrgUnitService orgUnitService;

    @Autowired
    public QyOrgUtil(QyTokenUtil qyTokenUtil, OrgUnitService orgUnitService) {
        this.qyTokenUtil = qyTokenUtil;
        this.orgUnitService = orgUnitService;
    }

    public int create(OrgUnit orgUnit, OrgUnit parentOrgUnit) {
        JSONObject postObj = new JSONObject();
        postObj.put("name", orgUnit.getOrgName());
        if (parentOrgUnit == null) {
            postObj.put("parentid", 1);
        } else {
            postObj.put("parentid", parentOrgUnit.getWxorgId());
        }
        JSONObject retObj = WxApiUtils.departmentCreate(qyTokenUtil.getToken(orgUnit.getAccountsId()), postObj);

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

    public boolean update(OrgUnit orgUnit) {

        JSONObject postObj = new JSONObject();

        postObj.put("id", orgUnit.getWxorgId());
        postObj.put("name", orgUnit.getOrgName());
        JSONObject retObj = WxApiUtils.departmentUpdate(qyTokenUtil.getToken(orgUnit.getAccountsId()), postObj);
        return retObj.getIntValue("errcode") == 0;
    }

    /**
     * 部门移动
     *
     * @param orgUnit       移动的部门
     * @param parentOrgUnit 移动至的部门
     * @return 移动是否成功
     */
    public boolean move(OrgUnit orgUnit, OrgUnit parentOrgUnit) {
        JSONObject postObj = new JSONObject();

        postObj.put("id", orgUnit.getWxorgId());
        postObj.put("parentid", parentOrgUnit.getWxorgId());
        JSONObject retObj = WxApiUtils.departmentUpdate(qyTokenUtil.getToken(orgUnit.getAccountsId()), postObj);
        return retObj.getIntValue("errcode") == 0;
    }

    public boolean delete(OrgUnit orgUnit) {
        JSONObject retObj = WxApiUtils.departmentDelete(qyTokenUtil.getToken(orgUnit.getAccountsId()), new Integer(orgUnit.getWxorgId()));
        return retObj.getIntValue("errcode") == 0;
    }

    /**
     * 同步微信部门
     *
     * @param accountId 微信账号
     * @return JSONObject
     */
    public JSONObject sync(Long accountId) {
        JSONObject retObj = new JSONObject();
        int successCreateCount = 0;
        int successUpdateCount = 0;
        int failureUpdateCount = 0;

        //微信端的所有部门
        JSONObject departRetObj = WxApiUtils.departmentList(qyTokenUtil.getToken(accountId), 1);
        if (departRetObj.getIntValue("errcode") == 0) {
            //将部门重置成同步中的状态
            clearStatus(accountId);
            //获取成功
            JSONArray departList = departRetObj.getJSONArray("department");
            for (int i = 0, j = departList.size(); i < j; i++) {
                JSONObject departObj = departList.getJSONObject(i);
                String wxorgId = departObj.getString("id");
                String orgName = departObj.getString("name");
                String parentWxOrgId = departObj.getString("parentid");

                OrgUnit orgUnit = findByWxorgId(accountId, wxorgId);
                OrgUnit parentOrgUnit = findByWxorgId(accountId, parentWxOrgId);
                if (orgUnit == null) {
                    // 新增
                    orgUnit = new OrgUnit();
                    orgUnit.setAccountsId(accountId);
                    orgUnit.setOrgName(orgName);
                    orgUnit.setWxorgId(wxorgId);
                    orgUnit.setParentId(parentOrgUnit == null ? 0 : parentOrgUnit.getId());
                    orgUnit.setParentIds(parentOrgUnit == null ? 0 + "," : parentOrgUnit.getParentIds());
                    orgUnit.setCreateBy(UserUtils.getUser().getId());
                    orgUnit.setUpdateBy(UserUtils.getUser().getId());
                    orgUnitService.saveCache(orgUnit);
                    orgUnit.setParentIds(orgUnit.getParentIds() + orgUnit.getId() + ",");
                    orgUnitService.updateCache(orgUnit);
                    successCreateCount++;
                } else {
                    // 更新
                    //状态更新回正常的0
                    orgUnit.setStatus("0");
                    orgUnit.setOrgName(orgName);
                    orgUnit.setParentId(parentOrgUnit == null ? 0 : parentOrgUnit.getId());
                    orgUnit.setParentIds(parentOrgUnit == null ? 0 + ","+orgUnit.getId()+"," : parentOrgUnit.getParentIds()+ orgUnit.getId() + ",");
                    orgUnit.setUpdateBy(UserUtils.getUser().getId());
                    orgUnitService.updateCache(orgUnit);
                    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"; //同步中
        orgUnitService.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 = orgUnitService.count(conds);
        return counts;
    }

    /**
     * 返回是否存在这个组织
     *
     * @param accountId 微信账号
     * @param wxorgId   微信的部门Id
     * @return OrgUnit
     */
    public OrgUnit findByWxorgId(Long accountId, String wxorgId) {
        Conds conds = new Conds();
        conds.equal("del_flag", 0);
        conds.equal("accounts_id", accountId);
        conds.equal("wxorg_id", wxorgId);
        return orgUnitService.fetchSearchByConds(conds);
    }
}
