package com.cftech.mp.custservice.web;

import com.cftech.core.sql.Conds;
import com.cftech.core.util.MpTokenUtil;
import com.cftech.mp.custservice.Utils.CustserviceWXAPIUtils;
import com.cftech.mp.custservice.model.MultiCustservice;
import com.cftech.mp.custservice.service.MultiCustserviceService;
import net.sf.json.JSONObject;
import org.mp.api.custservice.multicustservice.JwMultiCustomerAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Strive on 2017/4/20.
 */
@RestController
@RequestMapping("/a/custservice")
public class MobileMultiCustserviceController {

    @Autowired
    private MpTokenUtil tokenUtils;

    @Autowired
    private CustserviceWXAPIUtils custserviceWXAPIUtils;

    @Autowired
    private MultiCustserviceService multiCustserviceService;

    /**
     * 获取所有客服列表
     * @param accountId
     * @return
     */
    @RequestMapping(value = "findCustserviceList",
            method = RequestMethod.GET,
            produces = {"application/xml; application/json; charset=UTF-8"})
    public String findCustserviceList(@RequestParam Long accountId) {
        return custserviceWXAPIUtils.byWXAPIFindCustserviceListInfo(findToken(accountId));
    }

    /**
     * 判断指定客服是否可用
     * @param accountId
     * @return
     */
    @RequestMapping(value = "findOnlineCustServiceList",
            method = RequestMethod.GET,
            produces = {"application/xml; application/json; charset=UTF-8"})
    public String findOnlineCustServiceList(@RequestParam Long accountId,
                                            @RequestParam String kfAccount) {
        JwMultiCustomerAPI multiCustomerAPI = new JwMultiCustomerAPI();
        boolean isAllow = multiCustomerAPI.isOnlineCustServiceAvailable(findToken(accountId), kfAccount);

        JSONObject retObj = new JSONObject();
        if (isAllow) {
            retObj.put("errcode", 0);
            retObj.put("errMsg", "ok");
            return String.valueOf(retObj);
        }
        retObj.put("errcode", 1);
        retObj.put("errMsg", "custom service offline!");
        return String.valueOf(retObj);
    }

    /**
     * 创建或更新客服账号
     * @param accountId
     * @param kfAccount 客服账号
     * @param nickName 客服昵称
     * @param password 客服密码
     * @param kfAvatar 客服头像 图片不为空时，上传头像
     * @return
     */
    @RequestMapping(value = "createOrUpdateCustService",
            method = RequestMethod.POST,
            produces = {"application/xml; application/json; charset=UTF-8"})
    public String createOrUpdateCustService(HttpServletRequest request,
                                    @RequestParam Long accountId,
                                    @RequestParam String kfAccount,
                                    @RequestParam String nickName,
                                    @RequestParam String password,
                                    @RequestParam(required = false) MultipartFile kfAvatar) {
        JSONObject retObj = new JSONObject();

        //查询数据库是否记录该客服
        Conds conds = new Conds();
        conds.equal("kf_account", kfAccount);
        MultiCustservice custService = multiCustserviceService.fetchSearchByConds(conds);
        //获取token
        String token = findToken(accountId);
        if (custService == null) {
            boolean isSuc = custserviceWXAPIUtils.byWXAPICreateCustservice(token, kfAccount, nickName, password);
            //创建失败直接返回
            if (!isSuc) {
                retObj.put("errcode", 1);
                retObj.put("errMsg", "create failed!");
                return String.valueOf(retObj);
            }
            //上传客服头像
            updateAvatar(kfAccount, kfAvatar, token);
            //保存客服信息
            custService = new MultiCustservice();
            custService.setAccountsId(accountId);
            custService.setKf_account(kfAccount);
            custService.setKf_nick(nickName);
            custService.setPassword(password);
            multiCustserviceService.save(custService);
        } else {
            boolean isSuc = custserviceWXAPIUtils.byWXAPIUpdateCustservice(token, kfAccount, nickName, password);
            //创建失败直接返回
            if (!isSuc) {
                retObj.put("errcode", 1);
                retObj.put("errMsg", "create failed!");
                return String.valueOf(retObj);
            }
            //上传客户头像
            updateAvatar(kfAccount, kfAvatar, token);
            //更新客户信息
            custService.setKf_nick(nickName);
            custService.setPassword(password);
            multiCustserviceService.update(custService);
        }
        retObj.put("errcode", 0);
        retObj.put("errMsg", "ok!");
        return String.valueOf(retObj);
    }

    /**
     * 删除客服
     * @param accountId
     * @param kf_account 微信客服账号
     * @return
     */
    @RequestMapping(value = "deleteCustomService",
            method = RequestMethod.GET,
            produces = {"application/xml; application/json; charset=UTF-8"})
    public String deleteCustomService(@RequestParam Long accountId,
                                      @RequestParam String kf_account) {
        JSONObject retObj = new JSONObject();
        boolean isSuc = custserviceWXAPIUtils.byWXAPIDelCustservice(findToken(accountId), kf_account);
        if (!isSuc) {
            retObj.put("errcode", 1);
            retObj.put("errMsg", "delete failed!");
            return String.valueOf(retObj);
        }
        multiCustserviceService.byKf_accountDel(kf_account);
        retObj.put("errcode", 0);
        retObj.put("errMsg", "ok!");
        return String.valueOf(retObj);
    }

    /**
     * 创建客服会话
     * @param accountId
     * @param kfAccount
     * @param openid
     * @param text
     * @return
     */
    @RequestMapping(value = "createSession",
            method = RequestMethod.GET,
            produces = {"application/xml; application/json; charset=UTF-8"})
    public String createSession(@RequestParam Long accountId,
                                @RequestParam String kfAccount,
                                @RequestParam String openid,
                                @RequestParam(required = false) String text) {
        JSONObject retObj = new JSONObject();
        boolean isSuc = custserviceWXAPIUtils.byWXAPICreateSession(findToken(accountId), kfAccount, openid, text);
        if (!isSuc) {
            retObj.put("errcode", 1);
            retObj.put("errMsg", "create failed!");
            return String.valueOf(retObj);
        }
        retObj.put("errcode", 0);
        retObj.put("errMsg", "ok!");
        return String.valueOf(retObj);
    }

    /**
     * 关闭客服会话
     * @param accountId
     * @param kfAccount
     * @param openid
     * @param text
     * @return
     */
    @RequestMapping(value = "closeSession",
            method = RequestMethod.GET,
            produces = {"application/xml; application/json; charset=UTF-8"})
    public String closeSession(@RequestParam Long accountId,
                               @RequestParam String kfAccount,
                               @RequestParam String openid,
                               @RequestParam(required = false) String text) {
        JSONObject retObj = new JSONObject();
        boolean isSuc = custserviceWXAPIUtils.byWXAPICloseSession(findToken(accountId), kfAccount, openid, text);
        if (!isSuc) {
            retObj.put("errcode", 1);
            retObj.put("errMsg", "create failed!");
            return String.valueOf(retObj);
        }
        retObj.put("errcode", 0);
        retObj.put("errMsg", "ok!");
        return String.valueOf(retObj);
    }

    /**
     * 获取客服会话状态
     * @param accountId
     * @param openid
     * @return
     */
    @RequestMapping(value = "findCustServiceSessionStatus",
            method = RequestMethod.GET,
            produces = {"application/xml; application/json; charset=UTF-8"})
    public String findCustServiceSessionStatus(@RequestParam Long accountId,
                                               @RequestParam String openid) {
        return custserviceWXAPIUtils.byWXAPIFindSessionStatus(findToken(accountId), openid);
    }

    /**
     * 获取客服会话列表
     * @param accountId
     * @param kf_account
     * @return
     */
    @RequestMapping(value = "findCustserviceSessionList",
            method = RequestMethod.GET,
            produces = {"application/xml; application/json; charset=UTF-8"})
    public String findCustserviceSessionList(@RequestParam Long accountId,
                                             @RequestParam  String kf_account) {
        return custserviceWXAPIUtils.byWXAPIFindSessionList(findToken(accountId), kf_account);
    }

    /**
     * 获取未接入会话列表
     * @param accountId
     * @return
     */
    @RequestMapping(value = "findNotJoinSessionList",
            method = RequestMethod.GET,
            produces = {"application/xml; application/json; charset=UTF-8"})
    public String findNotJoinSessionList(@RequestParam Long accountId) {
        return custserviceWXAPIUtils.byWXAPIFindSessionWaitcase(findToken(accountId));
    }

    /**
     * 获取token票据
     * @param accountId
     * @return
     */
    private String findToken(Long accountId) {
        return tokenUtils.getToken(accountId);
    }

    /**
     * 上传客服头像
     * @param kfAccount
     * @param kfAvatar
     * @param token
     */
    private void updateAvatar(String kfAccount, MultipartFile kfAvatar, String token) {
        //上传客服头像
        if (kfAvatar != null && !kfAvatar.isEmpty()) {
            InputStream in = null;
            try {
                in = kfAvatar.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            custserviceWXAPIUtils.byWXAPIUploadCustserviceAvatar(token, kfAccount, kfAvatar.getName(), in);
        }
    }
}
