package com.ruoyi.asset.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.asset.domain.TbLocation;
import com.ruoyi.asset.mapper.TbLocationMapper;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.ptxlib.domain.PTXLabelCode;
import com.ruoyi.ptxlib.domain.PTXLabelInfo;
import com.ruoyi.ptxlib.domain.PTXLabelText;
import com.ruoyi.utils.RecursionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.asset.mapper.TbAssetInformationMapper;
import com.ruoyi.asset.domain.TbAssetInformation;
import com.ruoyi.asset.service.ITbAssetInformationService;

import javax.annotation.Resource;
import javax.validation.Validator;

/**
 * 资产信息Service业务层处理
 * 
 * @author 原动力
 * @date 2023-05-15
 */
@Service
public class TbAssetInformationServiceImpl implements ITbAssetInformationService 
{
    @Autowired
    private TbAssetInformationMapper tbAssetInformationMapper;

    @Autowired
    private TbLocationMapper locationMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    protected Validator validator;

    /**
     * 查询资产信息
     * 
     * @param id 资产信息主键
     * @return 资产信息
     */
    @Override
    public TbAssetInformation selectTbAssetInformationById(Long id)
    {
        return tbAssetInformationMapper.selectTbAssetInformationById(id);
    }

    @Override
    public List<TbAssetInformation> selectTbAssetInformationByIds(List<Long> ids) {
        return tbAssetInformationMapper.selectTbAssetInformationByIds(ids);
    }

    @Override
    public TbAssetInformation selectTbAssetAdjustmentByAssetNumber(String assetNumber) {
        return tbAssetInformationMapper.selectTbAssetInformationByAssetNumber(assetNumber);
    }

    /**
     * 查询资产信息列表
     * 
     * @param tbAssetInformation 资产信息
     * @return 资产信息
     */
    @Override
    public List<TbAssetInformation> selectTbAssetInformationList(TbAssetInformation tbAssetInformation)
    {
        String locationNumber = tbAssetInformation.getLocationNumber();
        List<String> childrens = new RecursionUtil().getNumberWithChildren(locationMapper, locationNumber);
        tbAssetInformation.setNlist(childrens);

        PageUtils.startPage();
        return tbAssetInformationMapper.selectTbAssetInformationList(tbAssetInformation);
    }

    @Override
    public List<TbAssetInformation> selectTbAssetInformationList2(TbAssetInformation tbAssetInformation) {
        String locationNumber = tbAssetInformation.getLocationNumber();
        List<String> childrens = new RecursionUtil().getNumberWithChildren(locationMapper, locationNumber);
        tbAssetInformation.setNlist(childrens);
        return tbAssetInformationMapper.selectTbAssetInformationList(tbAssetInformation);
    }

    @Override
    public List<TbAssetInformation> selectInfoList(TbAssetInformation tbAssetInformation){
        String locationNumber = tbAssetInformation.getLocationNumber();
        List<String> childrens = new RecursionUtil().getNumberWithChildren(locationMapper, locationNumber);
        tbAssetInformation.setNlist(childrens);
        return tbAssetInformationMapper.selectInfoList(tbAssetInformation);
    }


    /**
     * 新增资产信息
     * 
     * @param tbAssetInformation 资产信息
     * @return 结果
     */
    @Override
    public int insertTbAssetInformation(TbAssetInformation tbAssetInformation)
    {
        tbAssetInformation.setCreateTime(DateUtils.getNowDate());
        tbAssetInformation.setCreateBy(SecurityUtils.getUsername());

        setEpc(tbAssetInformation);

        return tbAssetInformationMapper.insertTbAssetInformation(tbAssetInformation);
    }

    /**
     * 修改资产信息
     * 
     * @param tbAssetInformation 资产信息
     * @return 结果
     */
    @Override
    public int updateTbAssetInformation(TbAssetInformation tbAssetInformation)
    {
        setEpc(tbAssetInformation);

        tbAssetInformation.setUpdateTime(DateUtils.getNowDate());
        return tbAssetInformationMapper.updateTbAssetInformation(tbAssetInformation);
    }

    private void setEpc(TbAssetInformation tbAssetInformation) {
        String number = tbAssetInformation.getNumber();
        tbAssetInformation.setCode(number);

        String locationNumber = tbAssetInformation.getLocationNumber();
        if (StrUtil.isBlank(locationNumber)) {
            tbAssetInformation.setLocationNumber(null);
        }

        // 将编码转为16进制
        String epc = HexUtil.encodeHexStr(number, CharsetUtil.CHARSET_UTF_8);
        // epc补充位
        int epcReplenishLength = epc.length() % 4;
        int remainder = epcReplenishLength % 4;
        if (remainder != 0) {
            int padding = 4 - remainder;
            epc = epc + "0".repeat(padding);
        }
        // 将epc大写
        epc = epc.toUpperCase();

        tbAssetInformation.setEpc(epc);
        tbAssetInformation.setEpcReplenishLength(epcReplenishLength);
    }

    /**
     * 判断是否为16进制，并将传入编号所有英文大写
     *
     * @param number 编号
     * @return 返回值
     */
    private String checkHNumber(String number) {
        String regex="^[A-Fa-f0-9]+$";

        if (StrUtil.isBlank(number)) {
            throw new RuntimeException("编号不能为空");
        }

        // 删除字符串中前导的零
        number = number.replaceFirst("^0+", "");

        if (number.length() % 4 != 0) {
            throw new RuntimeException("编号的长度必须为4的倍数");
        }

        // 大写英文
        number = number.toUpperCase();

        if (!number.matches(regex)) {
            throw new RuntimeException("非正则表达式");
        }

        return number;
    }

    /**
     * 批量删除资产信息
     * 
     * @param ids 需要删除的资产信息主键
     * @return 结果
     */
    @Override
    public int deleteTbAssetInformationByIds(Long[] ids)
    {
        return tbAssetInformationMapper.deleteTbAssetInformationByIds(ids);
    }

    /**
     * 删除资产信息信息
     * 
     * @param id 资产信息主键
     * @return 结果
     */
    @Override
    public int deleteTbAssetInformationById(Long id)
    {
        return tbAssetInformationMapper.deleteTbAssetInformationById(id);
    }

    @Override
    public boolean setDiy(List<String> labels) {
        String key = "func:assetInfo:" + SecurityUtils.getUserId();
        String jsonStr = JSONUtil.toJsonStr(labels);
        stringRedisTemplate.opsForValue().set(key, jsonStr);
        return true;
    }

    @Override
    public List<String> getDiy(){
        String json = stringRedisTemplate.opsForValue().get("func:assetInfo:" + SecurityUtils.getUserId());
        List<String> labels = JSONUtil.toList(json, String.class);
        return labels;
    }

    @Override
    public boolean updateProperty(TbAssetInformation information) {
        return tbAssetInformationMapper.updateProperty(information);
    }

    @Override
    public String importCon(List<TbAssetInformation> stuList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(stuList) || stuList.size() == 0)
        {
            throw new ServiceException("导入资产信息数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TbAssetInformation con : stuList)
        {
            try
            {
                // 验证是否存在这个用户
                TbAssetInformation u = tbAssetInformationMapper.selectTbAssetInformationById(con.getId());
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, con);
                    con.setCreateBy(operName);
                    this.insertTbAssetInformation(con);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、编码 " + con.getNumber() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, con);
                    con.setUpdateBy(operName);
                    this.updateTbAssetInformation(con);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、编码 " + con.getNumber() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、编码 " + con.getNumber() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、编码 " + con.getNumber() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

}
