package com.community.huiju.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.community.commom.constant.Constant;
import com.community.commom.mode.ResponseBean;
import com.community.commom.session.UserElement;
import com.community.commom.hk.HKOpenApi;
import com.community.huiju.dao.TaUserMapper;
import com.community.huiju.dao.TaVisitorLicenseMapper;
import com.community.huiju.dao.TaVisitorMapper;
import com.community.huiju.dao.TpEquipmentTreeMapper;
import com.community.huiju.model.TaUser;
import com.community.huiju.model.TaVisitor;
import com.community.huiju.model.TaVisitorLicense;
import com.community.huiju.model.TpEquipmentTree;
import com.community.huiju.service.TaVistorServiceI;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author weichaochao
 * @Title: TaVistorServiceImpl
 * @Description: 访客实现类
 * @date 2018/11/1
 */
@Service("TaVistorServiceImpl")
@Slf4j
public class TaVistorServiceImpl implements TaVistorServiceI {

    @Autowired
    private TaVisitorMapper taVisitorMapper;

    @Autowired
    private TaVisitorLicenseMapper taVisitorLicenseMapper;

    @Autowired
    private TaUserMapper taUserMapper;

    @Autowired
    private TpEquipmentTreeMapper tpEquipmentTreeMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean insertTaVistor(TaVisitor taVisitor, UserElement userElement) {
        ResponseBean response = new ResponseBean();

        taVisitor.setTaUserId(userElement.getId());
        taVisitor.setUpdateUser(userElement.getId());
        taVisitor.setCreateUser(userElement.getId());
        taVisitor.setCreateDate(new Date());
        taVisitor.setUpdateDate(new Date());
        taVisitor.setCommunityId(userElement.getCommunityId());

        if (taVisitor.getVisitorStartTime().getTime() >= taVisitor.getVisitorEndTime().getTime()) {
            response.addError("开始时间不能大于等于离开时间!");
            return response;
        }

        if (Constant.EFFECTIVE.equals(taVisitor.getDrivingStatus())){
            taVisitorMapper.insertSelective(taVisitor);

            for (String taCarLicense : taVisitor.getCarLicense()){
                TaVisitorLicense taVisitorLicense = new TaVisitorLicense();
                taVisitorLicense.setCommunityId(userElement.getCommunityId());
                taVisitorLicense.setVisitorId(taVisitor.getId());
                taVisitorLicense.setLicense(taCarLicense);
                taVisitorLicense.setCreateUser(userElement.getId());
                taVisitorLicense.setCreateDate(new Date());
                taVisitorLicense.setUpdateUser(userElement.getId());
                taVisitorLicense.setUpdateDate(new Date());
                taVisitorLicenseMapper.insertSelective(taVisitorLicense);
            }
        } else{
            taVisitorMapper.insertSelective(taVisitor);
        }

        // 推送海康
        temporaryRegister(userElement.getId(),taVisitor, userElement.getCommunityId(), response);

        return response;
    }

    @Override
    public ResponseBean invateHis(Integer communityId, Integer userId) {
        ResponseBean responseBean = new ResponseBean();
        List<TaVisitor> taVisitors = taVisitorMapper.findAllVistors(communityId, userId);

        for (TaVisitor taVisitor : taVisitors){
            if (Constant.EFFECTIVE.equals(taVisitor.getDrivingStatus())){
                List<String> taVisitorLicenses = taVisitorLicenseMapper.findTaVistorLicenseById(taVisitor.getId());
                taVisitor.setCarLicense(taVisitorLicenses);
            }
        }
        responseBean.addSuccess(taVisitors);
        return responseBean;
    }

    /**
     * 推送海康
     *
     * 未预约登记（临时登记）【V2.8.2】
     * @param userId 被访人ID
     * @param visitor
     */
    private void temporaryRegister(Integer userId,TaVisitor visitor, Integer communityId ,ResponseBean response){

        // 获取设备树，里面有 opUserId
        TpEquipmentTree tpEquipmentTree = tpEquipmentTreeMapper.selectByCommunityId(communityId);

        TaUser taUser = taUserMapper.selectByPrimaryKey(userId);
        String result = HKOpenApi.temporaryRegister(visitor.getVisitorName(),visitor.getVisitorTel(),
                Integer.valueOf(visitor.getVisitorNum()),visitor.getVisitorStartTime().getTime(),
                visitor.getVisitorEndTime().getTime(),taUser.getHkUserId(), tpEquipmentTree.getOpUserUuid(), tpEquipmentTree.getAppkey(), tpEquipmentTree.getSecret(), tpEquipmentTree.getHttpServer());

        JSONObject resultJSON = JSONObject.parseObject(result);
        int errorCode = resultJSON.getInteger("errorCode");
        if (errorCode == 0) {
            String visitorCode = resultJSON.getJSONObject("data").getString("QRCode");
            Map<String,Object> map = Maps.newHashMap();
            map.put("message","创建访问登记成功!");
            map.put("visitorCode",resultJSON.getJSONObject("data").getString("QRCode"));
            map.put("visitorStartTime",visitor.getVisitorStartTime());
            map.put("visitorEndTime",visitor.getVisitorEndTime());
            map.put("drivingStatus",visitor.getDrivingStatus());
            map.put("payEntity",visitor.getPayEntity());

            // 把访问码存入
            visitor.setVisitorCode(visitorCode);
            taVisitorMapper.updateByPrimaryKeySelective(visitor);

            response.addSuccess(map);
            return;
        }

        String errorMessage = resultJSON.getString("errorMessage");
        response.addError("创建访问登记失败!");
        log.error("创建访问登记失败! 错误信息: {}",errorMessage);
        throw new RuntimeException("创建访问登记失败!" + errorMessage);

    }
}
