package com.uas.platform.b2b.publicapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uas.platform.b2b.model.Enterprise;
import com.uas.platform.b2b.model.EnterpriseBaseInfo;
import com.uas.platform.b2b.model.InvitationRecord;
import com.uas.platform.b2b.search.SearchService;
import com.uas.platform.b2b.service.EnterpriseService;
import com.uas.platform.b2b.service.UserService;
import com.uas.platform.b2b.support.CommBufferedLogger;
import com.uas.platform.b2b.publicapi.model.Invitation;
import com.uas.platform.b2b.publicapi.service.InviteRecordService;
import com.uas.platform.core.exception.IllegalOperatorException;
import com.uas.platform.core.logging.BufferedLoggerManager;
import com.uas.platform.core.model.Constant;
import com.uas.platform.core.model.PageParams;
import com.uas.platform.core.web.bind.RequestState;
import com.uas.ps.core.util.StringUtils;
import com.uas.search.b2b.model.SPage;
import com.uas.search.b2b.model.Sort;
import com.uas.search.b2b.util.SearchConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.AccessException;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户邀请记录公共接口
 *
 * Created by hejq on 2018-03-22.
 */
@RestController
@RequestMapping("/public/invitation")
public class InviteRecordController {

    @Autowired
    private InviteRecordService inviteRecordService;

    private final static CommBufferedLogger logger = BufferedLoggerManager.getLogger(CommBufferedLogger.class);

    @Autowired
    private SearchService searchService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private UserService userService;

    /**
     * 通过传入的企业名称检验企业注册情况
     *
     * @param name 需要校验的企业名称
     * @param enUU 访问的企业UU
     * @param userUU 访问的用户UU
     * @param userTel 访问的用户电话
     * @param businessCode 访问的企业营业执照
     * @return
     */
    @RequestMapping(value = "/checkEnName", method = RequestMethod.GET)
    private List<EnterpriseBaseInfo> checkByName(String name, Long enUU, Long userUU, String userTel, String businessCode) {
        enUU = checkByBusinessCode(enUU, businessCode);
        userUU = checkByUserTel(userUU, userTel);
        logger.log("邀请注册", "校验企业名称", name, userUU, enUU);
        return inviteRecordService.checkByName(name);
    }

    /**
     * 获取邀请记录
     *
     * @param params 分页参数
     * @param keyword 搜索关键词
     * @param enUU 企业UU
     * @param userUU 用户UU
     * @param businessCode 企业营业执照
     * @param userTel 用户电话
     * @return
     */
    @RequestMapping(value = "/records", method = RequestMethod.GET)
    private SPage<InvitationRecord> getInviteRecords(Long enUU, Long userUU, PageParams params, String keyword, String userTel, String businessCode) {
        enUU = checkByBusinessCode(enUU, businessCode);
        userUU = checkByUserTel(userUU, userTel);
        logger.log("邀请注册", "查询邀请记录", "关键字：" + keyword, userUU, enUU);
        com.uas.search.b2b.model.PageParams pageParams = searchService.convertPageParams(params, null);
        pageParams.getFilters().put("in_useruu", userUU);
        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("in_date", false, Sort.Type.LONG, new Long(1)));
        pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
        return inviteRecordService.getInviteRecords(enUU, userUU, pageParams, keyword);
    }

    /**
     * 获取邀请记录(已注册)
     *
     * @param params 分页参数
     * @param keyword 搜索关键词
     * @param enUU 企业UU
     * @param userUU 用户UU
     * @param businessCode 营业执照
     * @param userTel 用户电话
     * @return
     */
    @RequestMapping(value = "/records", params = RequestState.DONE, method = RequestMethod.GET)
    private SPage<InvitationRecord> getInviteRecordsDone(Long enUU, Long userUU, PageParams params, String keyword, String businessCode, String userTel) {
        enUU = checkByBusinessCode(enUU, businessCode);
        userUU = checkByUserTel(userUU, userTel);
        logger.log("邀请注册", "查询邀请记录(已注册)", "关键字：" + keyword, userUU, enUU);
        com.uas.search.b2b.model.PageParams pageParams = searchService.convertPageParams(params, null);
        pageParams.getFilters().put("in_useruu", userUU);
        pageParams.getFilters().put("in_active", Constant.YES);
        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("in_date", false, Sort.Type.LONG, new Long(1)));
        pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
        return inviteRecordService.getInviteRecords(enUU, userUU, pageParams, keyword);
    }

    /**
     * 获取邀请记录(未注册)
     *
     * @param params 分页参数
     * @param keyword 搜索关键词
     * @param enUU 企业UU
     * @param userUU 用户UU
     * @param userTel 用户电话
     * @param businessCode 营业执照
     * @return
     */
    @RequestMapping(value = "/records", params = RequestState.TODO, method = RequestMethod.GET)
    private SPage<InvitationRecord> getInviteRecordsTodo(Long enUU, Long userUU, PageParams params, String keyword, String businessCode, String userTel) {
        enUU = checkByBusinessCode(enUU, businessCode);
        userUU = checkByUserTel(userUU, userTel);
        logger.log("邀请注册", "查询邀请记录(未注册)", "关键字：" + keyword, userUU, enUU);
        com.uas.search.b2b.model.PageParams pageParams = searchService.convertPageParams(params, null);
        pageParams.getFilters().put("in_useruu", userUU);
        pageParams.getFilters().put("in_active", Constant.NO);
        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("in_date", false, Sort.Type.LONG, new Long(1)));
        pageParams.getFilters().put(SearchConstants.SORT_KEY, sortList);
        return inviteRecordService.getInviteRecords(enUU, userUU, pageParams, keyword);
    }

    /**
     * 新增邀请记录
     *
     * @param jsonStr 封装的数据
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    private ModelMap addInvitation(String jsonStr) throws UnsupportedEncodingException {
        System.out.println(jsonStr);
        String str = URLDecoder.decode(jsonStr, "UTF-8");
        str = str.replaceAll(" ", "");
        str = str.replaceAll("\\\\n", "");
        InvitationRecord record = JSONObject.parseObject(str, InvitationRecord.class);
        Long enUU = checkByBusinessCode(record.getEnuu(), record.getBussinesscode());
        Long userUU = checkByUserTel(record.getUseruu(), record.getUserTel());
        record.setEnuu(enUU);
        record.setUseruu(userUU);
        if (null == record.getEnuu() || null == record.getUseruu()) {
            throw new IllegalAccessError("企业UU和用户UU不能为空");
        }
        record.setDate(new Date(System.currentTimeMillis()));
        record.setActive(Constant.NO);
        logger.log("邀请注册", "新增邀请", record.getVendname(), record.getUseruu(), record.getEnuu());
        return inviteRecordService.invite(record);
    }

    /**
     * 按分类获取统计总数
     *
     * @param userUU 用户UU
     * @param enUU 企业UU
     * @param businessCode 企业营业执照
     * @param userTel 用户电话
     * @return
     */
    @RequestMapping(value = "/count", method = RequestMethod.GET)
    private ModelMap getInvationCount(Long userUU, Long enUU, String businessCode, String userTel) {
        enUU = checkByBusinessCode(enUU, businessCode);
        userUU = checkByUserTel(userUU, userTel);
        logger.log("邀请注册", "分类获取邀请总数", null, userUU, enUU);
        return inviteRecordService.getInvationCount(userUU, enUU);
    }

    /**
     * 分月获取数据统计
     *
     * @param userUU 用户UU
     * @param enUU 企业UU
     * @param year 年份
     * @return
     */
    @RequestMapping(value = "/count/groupBydate", method = RequestMethod.GET)
    private List<Invitation> getCountGroupByDate(Long userUU, Long enUU, String year, String businessCode, String userTel) throws IllegalAccessException {
        enUU = checkByBusinessCode(enUU, businessCode);
        userUU = checkByUserTel(userUU, userTel);
        if (StringUtils.isEmpty(enUU)) {
            throw new IllegalAccessException("企业UU号不能为空");
        }
        if (StringUtils.isEmpty(year)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            year = sdf.format(new Date());
        }
        logger.log("邀请注册", "分月获取邀请数量", null, userUU, enUU);
        return inviteRecordService.getCountGroupByDate(userUU, enUU, year);
    }

    /**
     * 添加合作伙伴
     *
     * @param userUU 用户UU
     * @param enUU 企业UU
     * @param inviteEnUU 邀请的企业UU号
     * @param inviteUserName 邀请的用户姓名
     * @param inviteUserTel 邀请的用户电话
     * @param app 应用来来源
     * @param businessCode 营业执照
     * @param userTel 用户电话
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addpartner", method = RequestMethod.POST)
    private ModelMap addPartner(Long userUU, Long enUU, Long inviteEnUU, String inviteUserName, String inviteUserTel, String app, String businessCode, String userTel) throws Exception {
        enUU = checkByBusinessCode(enUU, businessCode);
        userUU = checkByUserTel(userUU, userTel);
        if (StringUtils.isEmpty(userUU) || StringUtils.isEmpty(enUU) || StringUtils.isEmpty(inviteEnUU) || StringUtils.isEmpty(app)) {
            throw new IllegalOperatorException("参数异常");
        }
        if (enUU.equals(inviteEnUU)) {
            throw new IllegalOperatorException("不能添加自己企业为合作伙伴");
        }
        logger.log("邀请注册", "添加合作伙伴", "添加企业UU：" + inviteEnUU + ",用户:" + inviteUserName, userUU, enUU);
        return inviteRecordService.addPartner(userUU, enUU, inviteEnUU, inviteUserName, inviteUserTel, app);
    }

    /**
     * UAS批量邀请功能
     *
     * @param enUU 企业UU
     * @param userUU 用户UU
     * @param invitations 邀请信息
     * @param source 信息来源
     * @return
     */
    @RequestMapping(value = "/invite/batch", method = RequestMethod.POST)
    private ModelMap inviteByBatch(Long enUU, Long userUU, String invitations, String source, String userTel, String businessCode) throws UnsupportedEncodingException {
        enUU = checkByBusinessCode(enUU, businessCode);
        userUU = checkByUserTel(userUU, userTel);
        if (StringUtils.isEmpty(enUU) || StringUtils.isEmpty(userUU)) {
            throw new IllegalAccessError("企业UU或用户UU不能为空");
        }
        String str = URLDecoder.decode(invitations, "UTF-8");
        List<InvitationRecord> records = JSON.parseArray(str, InvitationRecord.class);
        logger.log("邀请注册", "批量新增邀请，来源" + source, invitations.length() > 1000 ? invitations.substring(0, 1000).concat("...") : invitations, userUU, enUU);
        return inviteRecordService.inviteByBatch(enUU, userUU, records, source);
    }


    /**
     * 通过手机号校验用户信息
     *
     * @param userUU 用户UU
     * @param userTel 用户手机号
     * @return
     */
    private Long checkByUserTel(Long userUU, String userTel) {
        if (StringUtils.isEmpty(userUU)) {
            try {
                throw new AccessException("userUU不能为空");
            } catch (AccessException e) {
                e.printStackTrace();
            }
        }
        return userUU;
    }

    /**
     * 通过营业执照校验企业信息
     *
     * @param enUU 企业UU
     * @param businessCode 营业执照
     * @return
     */
    private Long checkByBusinessCode(Long enUU, String businessCode) {
        if (null != businessCode) {
            Enterprise enterprise = enterpriseService.findByenBussinessCode(businessCode);
            enUU = enterprise.getUu();
        }
        return enUU;
    }

}
