/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.unis.basic.info.modular.pricemonitor.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fhs.common.utils.StringUtil;
import com.unis.auth.core.util.StpClientUtil;
import com.unis.basic.info.modular.pricemonitor.enums.PriceMonitorEnum;
import com.unis.basic.info.modular.pricemonitor.param.PriceMonitorAddParam;
import com.unis.basic.info.modular.pricemonitor.service.PriceMonitorService;

import com.unis.basic.info.modular.pricemonitor.vo.PriceMonitorVO;
import com.unis.common.pojo.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.unis.common.enums.CommonSortOrderEnum;
import com.unis.common.exception.CommonException;
import com.unis.common.page.CommonPageRequest;
import com.unis.basic.info.modular.pricemonitor.entity.PriceMonitor;
import com.unis.basic.info.modular.pricemonitor.mapper.PriceMonitorMapper;
import com.unis.basic.info.modular.pricemonitor.param.PriceMonitorAddParam;
import com.unis.basic.info.modular.pricemonitor.param.PriceMonitorEditParam;
import com.unis.basic.info.modular.pricemonitor.param.PriceMonitorIdParam;
import com.unis.basic.info.modular.pricemonitor.param.PriceMonitorPageParam;
import com.unis.basic.info.modular.pricemonitor.service.PriceMonitorService;
import org.springframework.util.CollectionUtils;
import com.unis.common.geo.GeoPoint;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 价格监测Service接口实现类
 *
 * @author weiyinbin
 * @date 2024/04/02 15:09
 **/
@Service
@Slf4j
public class PriceMonitorServiceImpl extends ServiceImpl<PriceMonitorMapper, PriceMonitor> implements PriceMonitorService {

    @Autowired
    private PriceMonitorMapper priceMonitorMapper;

    @Override
    public IPage<PriceMonitorVO> page(PriceMonitorPageParam priceMonitorPageParam) {
     /*   QueryWrapper<PriceMonitorVO> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(priceMonitorPageParam.getName())){
            queryWrapper.like("name",priceMonitorPageParam.getName());
        }
        if (StringUtils.isNotEmpty(priceMonitorPageParam.getSysOrgId())){
            queryWrapper.eq("sys_org_id",priceMonitorPageParam.getSysOrgId());
        }*/
/*
        if (ObjectUtil.isAllNotEmpty(priceMonitorPageParam.getSortField(), priceMonitorPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(priceMonitorPageParam.getSortOrder());
            queryWrapper.orderBy(true, priceMonitorPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(priceMonitorPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(PriceMonitor::getId);
        }*/
        Page<PriceMonitorVO> page = new Page<>(priceMonitorPageParam.getCurrent(), priceMonitorPageParam.getSize());
        IPage<PriceMonitorVO> p= priceMonitorMapper.selectPriceMonitor(page,priceMonitorPageParam.getName(),priceMonitorPageParam.getCityAddress());

        return p;
    }

    /**
     * @author: hujianchun
     * @Description: 添加价格监测
     * @param:
     * @return: void
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public CommonResult<String> add(PriceMonitorAddParam priceMonitorAddParam) {
        //构建条件
        LambdaQueryWrapper<PriceMonitor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PriceMonitor::getName, priceMonitorAddParam.getName());
        List<PriceMonitor> priceMonitors = priceMonitorMapper.selectList(wrapper);
        //根据name判断是否有重复的监测点名称
        if (!CollectionUtils.isEmpty(priceMonitors)) {
            //名称有重复的抛出名称重复异常
            throw new CommonException("监测站点名称重复");
        }
        //属性拷贝
        PriceMonitor priceMonitor = new PriceMonitor();
        BeanUtils.copyProperties(priceMonitorAddParam, priceMonitor);

        GeoPoint gp = new GeoPoint();
        gp.setLat(priceMonitorAddParam.getLatitude());
        gp.setLng(priceMonitorAddParam.getLongitude());


        priceMonitor.setGeoPoint(gp);
        //设值
        priceMonitor.setName(priceMonitorAddParam.getName());
        //TODO GEO

        priceMonitor.setCreateTime(new DateTime());
        priceMonitor.setUpdateTime(new DateTime());

        try {
            priceMonitorMapper.insert(priceMonitor);
        } catch (Exception e) {
            log.error("新增价格检测站点失败,站点ID[{}],站点名[{}]", priceMonitor.getId(), priceMonitor.getName());
            throw new CommonException("新增价格检测站点失败,站点ID[{}],站点名[{}]", priceMonitor.getId(), priceMonitor.getName());
        }
        return CommonResult.ok();
    }

    /**
     * @author: hujianchun
     * @Description:
     * @param:
     * @return: 编辑价格监测点信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(PriceMonitorEditParam priceMonitorEditParam) {
/*        PriceMonitor priceMonitor = this.queryEntity(priceMonitorEditParam.getId());
        BeanUtil.copyProperties(priceMonitorEditParam, priceMonitor);
        this.updateById(priceMonitor);*/
        PriceMonitor DBpriceMonitor = priceMonitorMapper.selectOne(Wrappers.lambdaQuery(PriceMonitor.class)
                .eq(PriceMonitor::getName, priceMonitorEditParam.getName()));
        if (DBpriceMonitor != null && !Objects.equals(DBpriceMonitor.getId(), priceMonitorEditParam.getId())) {
            throw new CommonException("监测名称：" + priceMonitorEditParam.getName() + "已存在");
        }
        PriceMonitor priceMonitor = new PriceMonitor();

        //为实体赋值
        BeanUtils.copyProperties(priceMonitorEditParam, priceMonitor);
        //处理经纬度
        GeoPoint geoPoint = new GeoPoint();
        geoPoint.setLat(priceMonitorEditParam.getLatitude());
        geoPoint.setLng(priceMonitorEditParam.getLongitude());
        priceMonitor.setGeoPoint(geoPoint);
        priceMonitor.setId(priceMonitorEditParam.getId());
        priceMonitor.setUpdateTime(new Date());

        try {
            priceMonitorMapper.updateById(priceMonitor);
        } catch (Exception e) {
            log.error("修改价格检测站点失败,站点ID[{}],站点名[{}]", priceMonitor.getId(), priceMonitor.getName());
            throw new CommonException("修改价格检测站点失败,站点ID[{}],站点名[{}]", priceMonitor.getId(), priceMonitor.getName());


        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<PriceMonitorIdParam> priceMonitorIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(priceMonitorIdParamList, PriceMonitorIdParam::getId));
    }

    @Override
    public PriceMonitor detail(PriceMonitorIdParam priceMonitorIdParam) {
        return this.queryEntity(priceMonitorIdParam.getId());
    }

    @Override
    public PriceMonitor queryEntity(String id) {
        PriceMonitor priceMonitor = this.getById(id);
        if (ObjectUtil.isEmpty(priceMonitor)) {
            throw new CommonException("价格监测不存在，id值为：{}", id);
        }
        return priceMonitor;
    }

/*
    //正常打包处理
    public CommonResult<String> pack(String msg) {
        return CommonResult.ok(msg);
    }


    //异常打包处理
    public CommonResult<String> errPack(String code, String msg) {
        return CommonResult.error(Integer.valueOf(code), msg);
    }*/

}
