package com.yeejoin.amos.boot.module.jcs.biz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yeejoin.amos.boot.module.jcs.api.dto.SinStaticDto;
import com.yeejoin.amos.boot.module.jcs.api.entity.Sign;
import com.yeejoin.amos.boot.module.jcs.api.mapper.SignMapper;
import com.yeejoin.amos.boot.module.jcs.api.service.ISignService;
import com.yeejoin.amos.boot.module.jcs.api.dto.SignDto;
import com.yeejoin.amos.component.rule.config.RuleConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;

/**
 * 打卡记录服务实现类
 *
 * @author system_generator
 * @date 2022-08-15
 */
@Slf4j
@Service
public class SignServiceImpl extends BaseService<SignDto,Sign,SignMapper> implements ISignService {

    @Autowired
    private EmqKeeper emqKeeper;

    @Value("${mqtt.topic.person.sign}")
    private String personSign;

    @Value("${mqtt.topic.person.sign.zxj:sign/data/synZxj}")
    private String personSignZxj;

    /**
     * 分页查询
     */
    public Page<SignDto> queryForSignPage(Page<SignDto> page)   {
        return this.queryForPage(page, null, false);
    }

    /**
     * 分页查询
     */
    public IPage<SignDto> queryForSignPageByMapper(IPage<SignDto> page, SignDto dto)   {
        return this.baseMapper.queryForPage(page,dto);
    }

    /**
     * 分页查询
     */
    public IPage<SinStaticDto> queryForSignStaticPageByMapper(IPage<SinStaticDto> page, SinStaticDto dto)   {
        IPage<SinStaticDto> sinStaticDtoIPage = this.baseMapper.queryStaticForPage(page, dto);
        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        numberFormat.setMaximumFractionDigits(2);

        sinStaticDtoIPage.getRecords().stream().forEach(e->{
//            int num = this.baseMapper.queryPersonNum(e.getBizOrgCode());
//            int signNum ;
//            if((Integer.parseInt(e.getSignNum()) & 1) != 0) {
//                signNum =  (Integer.parseInt(e.getSignNum()) + 1) / 2;
//            } else {
//                signNum = (Integer.parseInt(e.getSignNum())) / 2;
//            }

//            if(num != 0) {
//                e.setAttendance(numberFormat.format((float) Integer.valueOf(signNum)/(float) num * 100) + "%");
//            }  else {
//                e.setAttendance("0%");
//            }
            e.setAttendance(e.getSignNum() + "/" + e.getPersonOfDay());
        });

        return sinStaticDtoIPage;
    }

    /**
     * 列表查询 示例
     */
    public List<SignDto> queryForSignList()   {
        return this.queryForList("" , false);
    }

    @Override
    public Boolean hasSign(String type, String date,String userId) {
        QueryWrapper<Sign> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("date",date);
        if(StringUtils.isNotEmpty(type)) {
            queryWrapper.eq("type",type);
        }
        if(StringUtils.isNotEmpty(userId)) {
            queryWrapper.eq("user_id",userId);
        }
        List<Sign> signs = this.baseMapper.selectList(queryWrapper);

        if (StringUtils.isEmpty(type) && signs.size() != 2) {
            return true;
        } else {
            if(StringUtils.isNotEmpty(type) && signs.size() == 1) {
                return true;
            }
            return false;
        }
    }

    @Override
    public Boolean saveSign(SignDto dot) {
        Sign sign = new Sign();
        int num = this.baseMapper.queryPersonNum(dot.getBizOrgCode());
        Bean.copyExistPropertis(dot,sign);
        sign.setPersonOfDay(String.valueOf(num));
        boolean save = this.save(sign);
        // 发送mqtt 消息 同步人员打卡数据
        if (save){
            HashMap<String, Object> map = new HashMap<>();
            map.put("bizOrgName", ObjectUtils.isEmpty(sign.getBizOrgName())?"":sign.getBizOrgName());
            map.put("bizOrgCode", ObjectUtils.isEmpty(sign.getBizOrgCode())?"":sign.getBizOrgCode());
            map.put("orgCode", ObjectUtils.isEmpty(sign.getOrgCode())?"":sign.getOrgCode());
            map.put("signUserName", ObjectUtils.isEmpty(sign.getName())?"":sign.getName());
            map.put("jobTitle", ObjectUtils.isEmpty(sign.getJobTitle())?"":sign.getJobTitle());
            map.put("userId", ObjectUtils.isEmpty(sign.getSignUserId())?"":sign.getSignUserId());
            map.put("signDate", ObjectUtils.isEmpty(sign.getSignTime())?"":sign.getSignTime());
            map.put("recUserId", ObjectUtils.isEmpty(sign.getRecUserId())?"":sign.getRecUserId());
            map.put("recUserName", ObjectUtils.isEmpty(sign.getRecUserName())?"":sign.getRecUserName());
            map.put("sequenceNbr", ObjectUtils.isEmpty(sign.getRecUserName())?"":sign.getSequenceNbr());
            String json=JSONObject.toJSONString(map, SerializerFeature.PrettyFormat,
                    SerializerFeature.WriteMapNullValue);
            try {
                emqKeeper.getMqttClient().publish(personSign, json.getBytes(), RuleConfig.DEFAULT_QOS, false);
                map.put("personOfDay", ObjectUtils.isEmpty(sign.getPersonOfDay())?"":sign.getPersonOfDay());
                map.put("type", ObjectUtils.isEmpty(sign.getType())?"":sign.getType());
                map.put("photos", ObjectUtils.isEmpty(sign.getPhotos())?"":sign.getPhotos());
                map.put("remarks", ObjectUtils.isEmpty(sign.getRemarks())?"":sign.getRemarks());
                map.put("date", ObjectUtils.isEmpty(sign.getDate())?"":sign.getDate());
                map.put("recDate", ObjectUtils.isEmpty(sign.getRecDate())?"":sign.getRecDate());
                map.put("isDelete", ObjectUtils.isEmpty(sign.getIsDelete())?"":sign.getIsDelete());
                map.put("source", ObjectUtils.isEmpty(sign.getSource())?"":sign.getSource());
                String json1=JSONObject.toJSONString(map, SerializerFeature.PrettyFormat,
                        SerializerFeature.WriteMapNullValue);
                // 发送emq消息转kafka
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("topic", personSign);
                jsonObject.put("data",json);
                emqKeeper.getMqttClient().publish("emq.sign.created",jsonObject.toString().getBytes(),1,false);

                // 发送emq消息转kafka 同步业务库打卡表
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("topic", personSignZxj);
                jsonObject1.put("data",json1);
                emqKeeper.getMqttClient().publish("emq.bussSign.created",jsonObject1.toString().getBytes(),1,false);

            } catch (MqttException e) {
                log.info(String.format("发送eqm打卡消息失败：%s", e.getMessage()));
            }
        }
        return save;
    }
}