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.model.Position;
import com.cftech.base.org.model.Qyuser;
import com.cftech.base.org.service.OrgUnitService;
import com.cftech.base.org.service.PositionService;
import com.cftech.base.org.service.QyuserService;
import com.cftech.core.sql.Conds;
import com.cftech.core.util.QyTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

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


    @Autowired
    private QyTokenUtil qyTokenUtil;
    @Autowired
    private PositionService positionService;
    @Autowired
    private OrgUnitService orgUnitService;
    @Autowired
    private QyuserService qyuserService;


    public Qyuser getUser(Long userId) {
        return qyuserService.fetchById(userId);
    }

    /**
     * 根据code获取企业用户信息
     *
     * @param code
     * @return
     */
    public Qyuser getUserInfo(Long accountsId, String code) {
        JSONObject retObj = WxApiUtils.getUserInfo(qyTokenUtil.getToken(accountsId), code);
        if (retObj.containsKey("UserId")) {
            String userId = retObj.getString("UserId");
            Conds conds = new Conds();
            conds.equal("t.del_flag", 0);
            conds.equal("t.accounts_id", accountsId);
            conds.equal("t.wxuser_id", userId);
            return qyuserService.fetchSearchByConds(conds);
        } else {
            return null;
        }
    }

    public boolean exist(Qyuser qyuser) {
        if (StringUtils.isEmpty(qyuser.getWxuserId()))
            return false;

        JSONObject retObj = WxApiUtils.userGet(qyTokenUtil.getToken(qyuser.getAccountsId()), qyuser.getWxuserId());
        return retObj.getIntValue("errcode") == 0;
    }

    public JSONObject getUser(Qyuser qyuser) {
        return WxApiUtils.userGet(qyTokenUtil.getToken(qyuser.getAccountsId()), qyuser.getWxuserId());
    }

    public Qyuser updateQyUser(Qyuser qyuser) {
        if (!exist(qyuser)) {
            if (!create(qyuser)) {
                log.error("user create 同步微信端失败，{}", qyuser.toString());
            } else {
                log.info("user create 更新微信端成功，{}", qyuser.toString());
            }
        }
        if (!update(qyuser)) {
            log.error("user update更新微信端失败，{}", qyuser.toString());
        } else {
            log.info("user update更新微信端成功，{}", qyuser.toString());
        }
        JSONObject userInfo = getUser(qyuser);
        if (userInfo.getIntValue("errcode") == 0) {
            qyuser.setAvatar(userInfo.getString("avatar"));
            qyuser.setStatus(userInfo.getString("status"));
            qyuser.setWxno(userInfo.getString("weixinid"));
        }
        return qyuser;
    }

    public boolean create(Qyuser qyuser) {
        JSONObject postObj = new JSONObject();
        postObj.put("userid", qyuser.getWxuserId());
        postObj.put("name", qyuser.getName());
        postObj.put("mobile", qyuser.getMobile());
        if (!StringUtils.isEmpty(qyuser.getOrgId())) {
            OrgUnit orgUnit = orgUnitService.fetchById(qyuser.getOrgId());
            JSONArray departments = new JSONArray();
            departments.add(orgUnit.getWxorgId());
            postObj.put("department", departments);
        }
//        if (!StringUtils.isEmpty(qyuser.getPositionId())) {
//            Position position = positionService.fetchById(qyuser.getPositionId());
//            postObj.put("position", position.getName());
//        }
        if (!StringUtils.isEmpty(qyuser.getGender())) {
            postObj.put("gender", qyuser.getGender().equals("男") ? "1" : "2");
        }

        if (!StringUtils.isEmpty(qyuser.getEmail()))
            postObj.put("email", qyuser.getEmail());
        if (!StringUtils.isEmpty(qyuser.getWxno()))
            postObj.put("weixinid", qyuser.getWxno());

        if (!StringUtils.isEmpty(qyuser.getUserType())) {
            switch (qyuser.getUserType()) {
                case "0":
                    postObj.put("position", "其他");
                    break;
                case "1":
                    postObj.put("position", "药师");
                    break;
                case "2":
                    postObj.put("position", "客服");
                    break;
                case "3":
                    postObj.put("position", "医生");
                    break;
                case "4":
                    postObj.put("position", "订单员");
                    break;
            }
        }


        JSONObject retObj = WxApiUtils.userCreate(qyTokenUtil.getToken(qyuser.getAccountsId()), postObj);

        return retObj.getIntValue("errcode") == 0;
    }

    public boolean update(Qyuser qyuser) {
        JSONObject postObj = new JSONObject();
        postObj.put("userid", qyuser.getWxuserId());
        postObj.put("name", qyuser.getName());
        postObj.put("mobile", qyuser.getMobile());
        if (!StringUtils.isEmpty(qyuser.getOrgId())) {
            OrgUnit orgUnit = orgUnitService.fetchById(qyuser.getOrgId());
            JSONArray departments = new JSONArray();
            departments.add(orgUnit.getWxorgId());
            postObj.put("department", departments);
        }
//        if (!StringUtils.isEmpty(qyuser.getPositionId())) {
//            Position position = positionService.fetchById(qyuser.getPositionId());
//            postObj.put("position", position.getName());
//        }
        if (!StringUtils.isEmpty(qyuser.getGender())) {
            postObj.put("gender", qyuser.getGender().equals("男") ? "1" : "2");
        }

        if (!StringUtils.isEmpty(qyuser.getEmail()))
            postObj.put("email", qyuser.getEmail());
        if (!StringUtils.isEmpty(qyuser.getWxno()))
            postObj.put("weixinid", qyuser.getWxno());

        if (!StringUtils.isEmpty(qyuser.getUserType())) {
            switch (qyuser.getUserType()) {
                case "0":
                    postObj.put("position", "其他");
                    break;
                case "1":
                    postObj.put("position", "药师");
                    break;
                case "2":
                    postObj.put("position", "客服");
                    break;
                case "3":
                    postObj.put("position", "医生");
                    break;
                case "4":
                    postObj.put("position", "订单员");
                    break;
            }
        }


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


    public boolean delete(Qyuser qyuser) {
        JSONObject retObj = WxApiUtils.userDelete(qyTokenUtil.getToken(qyuser.getAccountsId()), qyuser.getWxuserId());
        return retObj.getIntValue("errcode") == 0;
    }

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

        //微信端的所有人员
        JSONObject userRetObj = WxApiUtils.userlist(qyTokenUtil.getToken(accountId), "1", "1", "0");
        if (userRetObj.getIntValue("errcode") == 0) {
            clearStatus(accountId);
            //获取成功
            JSONArray userList = userRetObj.getJSONArray("userlist");
            for (int i = 0, j = userList.size(); i < j; i++) {
                JSONObject userObj = userList.getJSONObject(i);
                String userid = userObj.getString("userid");

                Qyuser qyuser = findByWxuserId(accountId, userid);
                Position position = null;
                OrgUnit orgUnit = null;
                if (!StringUtils.isEmpty(userObj.getString("position"))) {
                    position = findByPositionName(accountId, userObj.getString("position"));
                }
                JSONArray orgList = userObj.getJSONArray("department");

                if (orgList.size() > 0) {
                    orgUnit = findByWxorgId(accountId, orgList.get(0).toString());
                }

                if (qyuser == null) {
                    // 新增
                    qyuser = new Qyuser();
                    qyuser.setAccountsId(accountId);
                    qyuser.setName(userObj.getString("name"));
                    qyuser.setAvatar(userObj.getString("avatar"));
                    qyuser.setMobile(userObj.getString("mobile"));
                    qyuser.setEmail(userObj.getString("email"));
                    qyuser.setWxno(userObj.getString("weixinid"));
                    qyuser.setGender(userObj.getString("gender").equals("1") ? "男" : "女");
                    if (position != null) {
                        qyuser.setPositionId(position.getId());
                    }
                    qyuser.setStatus(userObj.getString("status"));
                    qyuser.setWxuserId(userid);
                    if (orgUnit != null) {
                        qyuser.setOrgId(orgUnit.getId());
                    } else {
                        qyuser.setOrgId(new Long(0));
                    }
                    qyuserService.save(qyuser);
                    successCreateCount++;
                } else {
                    // 更新
                    qyuser.setName(userObj.getString("name"));
                    qyuser.setAvatar(userObj.getString("avatar"));
                    qyuser.setMobile(userObj.getString("mobile"));
                    qyuser.setEmail(userObj.getString("email"));
                    qyuser.setWxno(userObj.getString("weixinid"));
                    qyuser.setGender(userObj.getString("gender").equals("1") ? "男" : "女");
                    if (position != null) {
                        qyuser.setPositionId(position.getId());
                    }
                    qyuser.setStatus(userObj.getString("status"));
                    qyuser.setWxuserId(userid);
                    if (orgUnit != null) {
                        qyuser.setOrgId(orgUnit.getId());
                    } else {
                        qyuser.setOrgId(new Long(0));
                    }
                    qyuserService.update(qyuser);
                    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"; //同步中
        qyuserService.changeStatus(status, conds);
    }

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

    /**
     * 返回是否存在人员
     *
     * @param accountId 微信账号
     * @param wxuserId  微信的人员userId
     * @return Qyuser
     */
    public Qyuser findByWxuserId(Long accountId, String wxuserId) {
        Conds conds = new Conds();
        conds.equal("t.del_flag", 0);
        conds.equal("t.accounts_id", accountId);
        conds.equal("t.wxuser_id", wxuserId);
        return qyuserService.fetchSearchByConds(conds);
    }


    /**
     * 返回是否职位
     *
     * @param accountId 微信账号
     * @param name      职位的名称
     * @return Qyuser
     */
    public Position findByPositionName(Long accountId, String name) {
        Conds conds = new Conds();
        conds.equal("del_flag", 0);
        conds.equal("accounts_id", accountId);
        conds.equal("name", name);
        return positionService.fetchSearchByConds(conds);
    }

    /**
     * 返回是否存在这个组织
     *
     * @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);
    }

}
