package com.fs.his.service.impl;

import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.http.HttpUtil;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.his.config.FsSysConfig;
import com.fs.his.param.FsStoreOrderParam;
import com.fs.his.utils.ConfigUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.his.mapper.FsUserAddressMapper;
import com.fs.his.domain.FsUserAddress;
import com.fs.his.service.IFsUserAddressService;
import org.springframework.util.Base64Utils;

import static com.fs.his.utils.PhoneUtil.encryptPhone;

/**
 * 用户地址Service业务层处理
 *
 * @author fs
 * @date 2023-07-03
 */
@Service
public class FsUserAddressServiceImpl implements IFsUserAddressService
{
    @Autowired
    private FsUserAddressMapper fsUserAddressMapper;
    @Autowired
    private ConfigUtil ConfigUtil;
    /**
     * 查询用户地址
     *
     * @param addressId 用户地址主键
     * @return 用户地址
     */
    @Override
    public FsUserAddress selectFsUserAddressByAddressId(Long addressId)
    {
        return fsUserAddressMapper.selectFsUserAddressByAddressId(addressId);
    }

    /**
     * 查询用户地址列表
     *
     * @param fsUserAddress 用户地址
     * @return 用户地址
     */
    @Override
    public List<FsUserAddress> selectFsUserAddressList(FsUserAddress fsUserAddress)
    {
        return fsUserAddressMapper.selectFsUserAddressList(fsUserAddress);
    }

    /**
     * 新增用户地址
     *
     * @param fsUserAddress 用户地址
     * @return 结果
     */
    @Override
    public int insertFsUserAddress(FsUserAddress fsUserAddress)
    {
        fsUserAddress.setCreateTime(DateUtils.getNowDate());
        fsUserAddress.setPhone(encryptPhone(fsUserAddress.getPhone()));
        return fsUserAddressMapper.insertFsUserAddress(fsUserAddress);
    }

    /**
     * 修改用户地址
     *
     * @param fsUserAddress 用户地址
     * @return 结果
     */
    @Override
    public int updateFsUserAddress(FsUserAddress fsUserAddress)
    {
        fsUserAddress.setUpdateTime(DateUtils.getNowDate());
        if (fsUserAddress.getPhone()!=null&&fsUserAddress.getPhone().length()==11&&fsUserAddress.getPhone().matches("\\d+")){
            fsUserAddress.setPhone(encryptPhone(fsUserAddress.getPhone()));
        }else {
            fsUserAddress.setPhone(null);
        }
        return fsUserAddressMapper.updateFsUserAddress(fsUserAddress);
    }

    /**
     * 批量删除用户地址
     *
     * @param addressIds 需要删除的用户地址主键
     * @return 结果
     */
    @Override
    public int deleteFsUserAddressByAddressIds(Long[] addressIds)
    {
        return fsUserAddressMapper.deleteFsUserAddressByAddressIds(addressIds);
    }

    /**
     * 删除用户地址信息
     *
     * @param addressId 用户地址主键
     * @return 结果
     */
    @Override
    public int deleteFsUserAddressByAddressId(Long addressId)
    {
        return fsUserAddressMapper.deleteFsUserAddressByAddressId(addressId);
    }

    @Override
    public Integer selectFsUserAddressCountsByUserId(long userId) {
        return fsUserAddressMapper.selectFsUserAddressCountsByUserId(userId);
    }

    @Override
    public int clearIsDefalut(long userId) {
        return fsUserAddressMapper.clearIsDefalut(userId);
    }

    @Override
    public String getKdnAddress(String address) {
        String   requestData = "{'Content':'" + address + "'}";
        Map<String, Object> params = new HashMap<>();
        FsSysConfig sysConfig = ConfigUtil.getSysConfig();
        try {
            params.put("RequestData", URLEncoder.encode(requestData, "UTF-8"));
            params.put("EBusinessID",sysConfig.getKdnId().trim());
            params.put("RequestType", "6001");
            String dataSign = encrypt(requestData, sysConfig.getKdnKeyId().trim(), "UTF-8");
            params.put("DataSign", URLEncoder.encode(dataSign, "UTF-8"));
            params.put("DataType", "2");
            String result = HttpUtil.post(sysConfig.getKdnAddressUrl().trim(), params);

            return result;
        } catch (Exception e) {
            throw  new CustomException(e.getMessage());
        }

    }

    @Override
    public FsUserAddress selectFsUserAddressByDefault(long userId) {
        return fsUserAddressMapper.selectFsUserAddressByDefault(userId);
    }

    @Override
    public Boolean isEntityNull(FsUserAddress param) {
        if (param == null) {
            return true; // 整个实体对象为null
        }

        Class<? extends FsUserAddress> entityClass = param.getClass();
        Field[] fields = entityClass.getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                Object value = field.get(param);
                if (value != null) {
                    return false; // 实体对象中有字段不为null
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return true; // 实体对象内所有字段为null
    }

    @Override
    public Long selectFsUserAddressListCount(FsUserAddress fsUserAddress) {
        return fsUserAddressMapper.selectFsUserAddressListCount(fsUserAddress);
    }

    private String encrypt(String content, String keyValue, String charset) {
        if (keyValue != null) {
            content = content + keyValue;
        }
        byte[] src;
        try {
            src = MD5(content, charset).getBytes(charset);
            return Base64Utils.encodeToString(src);
        } catch (Exception e) {
        }

        return null;
    }
    private String MD5(String str, String charset) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes(charset));
        byte[] result = md.digest();
        StringBuilder sb = new StringBuilder(32);
        for (int i = 0; i < result.length; i++) {
            int val = result[i] & 0xff;
            if (val <= 0xf) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(val));
        }
        return sb.toString().toLowerCase();
    }
}
