package com.gic.haoban.manage.service.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.haoban.manage.api.dto.KeyDataDTO;
import com.gic.haoban.manage.api.enums.KeyDataEnum;
import com.gic.haoban.manage.service.dao.mapper.TabKeyDataMapper;
import com.gic.haoban.manage.service.entity.TabKeyData;
import com.gic.haoban.manage.service.pojo.bo.hm.KeyDataLinkBO;
import com.gic.haoban.manage.service.pojo.bo.hm.KeyDataMobileBO;
import com.gic.haoban.manage.service.service.KeyDataService;

@Service("keyDataService")
public class KeyDataServiceImpl implements KeyDataService {

    @Autowired
    private TabKeyDataMapper tabKeyDataMapper;

    @Override
    public KeyDataDTO saveData(String enterpriseId, String relationId, String data, KeyDataEnum dataEnum) {
        KeyDataDTO dto = new KeyDataDTO();
        dto.setRelationId(relationId);
        dto.setEnterpriseId(enterpriseId);
        dto.setDataKey(generateKey(dataEnum, data));
        dto.setCreateTime(new Date());
        dto.setId(UniqueIdUtils.uniqueLong());
        dto.setData(data);
        dto.setType(dataEnum.getType());
        TabKeyData entity = EntityUtil.changeEntityByJSON(TabKeyData.class, dto);
        this.tabKeyDataMapper.insert(entity);
        return dto;
    }

    @Override
    public String saveDataForLink(String enterpriseId, KeyDataLinkBO link) {
        KeyDataDTO data = this.saveData(enterpriseId, String.valueOf(link.getLinkId()), JSON.toJSONString(link),
                KeyDataEnum.DYNAMIC_HM);
        return data.getDataKey();
    }

    @Override
    public KeyDataLinkBO getDataForHmLink(String key) {
        TabKeyData tab = this.tabKeyDataMapper.selectByKey(key, KeyDataEnum.DYNAMIC_HM.getType(), null);
        if (null != tab) {
            KeyDataLinkBO bo = JSON.parseObject(tab.getData(), KeyDataLinkBO.class);
            return bo;
        }
        return null;
    }

    @Override
    public String getMobile(String key, String relationId) {
        TabKeyData tab = this.tabKeyDataMapper.selectByKey(key, KeyDataEnum.MOBILE.getType(), relationId);
        if (null != tab) {
            KeyDataMobileBO bo = JSON.parseObject(tab.getData(), KeyDataMobileBO.class);
            return bo.getMobile();
        }
        return null;
    }

    private static String generateKey(KeyDataEnum dataEnum, String data) {
        if (dataEnum.equals(KeyDataEnum.MOBILE)) {
            String phone = JSON.parseObject(data).getString("mobile");
            return Long.toHexString(Long.valueOf(phone));
        }
        return UniqueIdUtils.uniqueLongHex();
    }

}
