package com.usky.iot.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
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.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.core.util.DateUtils;
import com.usky.common.redis.core.RedisHelper;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.iot.domain.CrmDeviceRepair;
import com.usky.iot.mapper.CrmDeviceRepairMapper;
import com.usky.iot.service.CrmDeviceRepairService;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.iot.service.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 设备报修记录表 服务实现类
 * </p>
 *
 * @author han
 * @since 2023-09-06
 */
@Service
public class CrmDeviceRepairServiceImpl extends AbstractCrudService<CrmDeviceRepairMapper, CrmDeviceRepair> implements CrmDeviceRepairService {
    @Autowired
    private RedisHelper redisHelper;

    @Override
    public void add(CrmDeviceRepair crmDeviceRepair){
        crmDeviceRepair.setRepairCode("bx-"+System.currentTimeMillis());
        crmDeviceRepair.setCreateTime(LocalDateTime.now());
        crmDeviceRepair.setRepairStatus(1);
        crmDeviceRepair.setTenantId(SecurityUtils.getTenantId());

        this.save(crmDeviceRepair);


        //发送短信
        StringBuffer sendStatus = new StringBuffer();
        StringBuffer sendContext = new StringBuffer();
        DefaultProfile profile = DefaultProfile.getProfile("cn-beijing", "LTAI5tH3VvRL5BUkovCokHJX", "SaaWUouNqvcA0C746gcNOH9m6SRYN4");
        IAcsClient client = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(crmDeviceRepair.getReflectPhone());//接收短信的手机号码
        request.setSignName("售后服务");//短信签名名称
        request.setTemplateCode("SMS_463225651");//短信模板CODE

        request.setTemplateParam("{\"name\":\""+crmDeviceRepair.getReflectName()+"\"}");//短信模板变量对应的实际值

        try {
            SendSmsResponse response = client.getAcsResponse(request);
            if(response.getCode() != null){
                if(response.getCode().equals("OK")){
//                    sendStatus.append("1");
//                    //查询发送短信内容
//
//                    try {
//                        Thread.sleep(3000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//
//                    QuerySendDetailsRequest request1 = new QuerySendDetailsRequest();
//                    request1.setPhoneNumber(crmDeviceRepair.getReflectPhone());
//                    request1.setSendDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
//                    request1.setPageSize((long)10);
//                    request1.setCurrentPage((long)1);
//                    QuerySendDetailsResponse response1 = client.getAcsResponse(request1);
//                    if(response1.getCode() != null){
//                        if(response1.getCode().equals("OK")){
//                            sendContext.append(response1.getSmsSendDetailDTOs().get(0).getContent());
//                        }
//
//                    }

                }else{
//                    sendStatus.append("2");
                }
            }
            System.out.println(new Gson().toJson(response));
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }

    }

    @Override
    public CommonPage<CrmDeviceRepair> page(CrmDeviceRepairVO crmDeviceRepairVO){
        IPage<CrmDeviceRepair> page = new Page<>(crmDeviceRepairVO.getCurrent(),crmDeviceRepairVO.getSize());
        LambdaQueryWrapper<CrmDeviceRepair> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(StringUtils.isNotBlank(crmDeviceRepairVO.getRepairCode()),CrmDeviceRepair::getRepairCode,crmDeviceRepairVO.getRepairCode())
                .like(StringUtils.isNotBlank(crmDeviceRepairVO.getProjectName()),CrmDeviceRepair::getProjectName,crmDeviceRepairVO.getProjectName())
                .like(StringUtils.isNotBlank(crmDeviceRepairVO.getReflectName()),CrmDeviceRepair::getReflectName,crmDeviceRepairVO.getReflectName())
                .eq(crmDeviceRepairVO.getRepairStatus() != null,CrmDeviceRepair::getRepairStatus,crmDeviceRepairVO.getRepairStatus())
                .between(StringUtils.isNotBlank(crmDeviceRepairVO.getStartTime()) && StringUtils.isNotBlank(crmDeviceRepairVO.getEndTime()),CrmDeviceRepair::getCreateTime,crmDeviceRepairVO.getStartTime(),crmDeviceRepairVO.getEndTime())
                .orderByDesc(CrmDeviceRepair::getId);
        page = this.page(page,queryWrapper);

        return new CommonPage<>(page.getRecords(),page.getTotal(),page.getSize(),page.getCurrent());

    }

    @Override
    public List<CrmDeviceRepairStatisticVO> statistic(CrmDeviceRepairVO crmDeviceRepairVO){
        List<CrmDeviceRepairStatisticVO> list = new ArrayList<>();
        QueryWrapper<CrmDeviceRepair> queryWrapper = Wrappers.query();
        queryWrapper.select("COUNT(*) as repairNum","AVG(CASE WHEN score IS NOT NULL THEN score END) as averageScore","SUM(repair_status=1) as processingNum","SUM(repair_status=2) as processedNum")
                .between("create_time",crmDeviceRepairVO.getStartTime(),crmDeviceRepairVO.getEndTime());
        List<Map<String,Object>> maps = this.listMaps(queryWrapper);
        if(maps.size() > 0){
            for (int i = 0; i < maps.size(); i++) {
                CrmDeviceRepairStatisticVO statisticVO = new CrmDeviceRepairStatisticVO();
                statisticVO.setRepairNum(Integer.parseInt(maps.get(i).get("repairNum").toString()));

                if(Objects.nonNull(maps.get(i).get("averageScore"))){
                    statisticVO.setAverageScore(Double.parseDouble(maps.get(i).get("averageScore").toString()));
                }else{
                    statisticVO.setAverageScore(Double.parseDouble("0"));
                }
                if(Objects.nonNull(maps.get(i).get("processingNum"))){
                    statisticVO.setProcessingNum(Integer.parseInt(maps.get(i).get("processingNum").toString()));
                }else{
                    statisticVO.setProcessingNum(0);
                }
                if(Objects.nonNull(maps.get(i).get("processedNum"))){
                    statisticVO.setProcessedNum(Integer.parseInt(maps.get(i).get("processedNum").toString()));
                }else{
                    statisticVO.setProcessedNum(0);
                }

                list.add(statisticVO);
            }
        }

        return list;
    }

    @Override
    public List<CrmDeviceRepairAddVO> getAddHistoryInfo(String projectName){

        QueryWrapper<CrmDeviceRepair> wrapper = Wrappers.query();
        wrapper.select("project_name as projectName","concat(Max(create_time),'') as createTime")
                .groupBy("project_name");
        List<Map<String,Object>> mapList = this.listMaps(wrapper);

        List<CrmDeviceRepairAddVO> list = new ArrayList<>();
        LambdaQueryWrapper<CrmDeviceRepair> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(StringUtils.isNotBlank(projectName),CrmDeviceRepair::getProjectName,projectName)
                .orderByDesc(CrmDeviceRepair::getId);
        List<CrmDeviceRepair> repairList = this.list(queryWrapper);
        int n = 0;
        if(CollectionUtils.isNotEmpty(repairList)){
            if(mapList.size() > 0){
                for (int i = 0; i < repairList.size(); i++) {
                    for (int j = 0; j < mapList.size(); j++) {
                        if(repairList.get(i).getProjectName().equals(mapList.get(j).get("projectName").toString()) && repairList.get(i).getCreateTime().equals(LocalDateTime.parse(mapList.get(j).get("createTime").toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))){
                            n++;
                            if(n > 10){
                                break;
                            }

                            CrmDeviceRepairAddVO addVO = new CrmDeviceRepairAddVO();
                            addVO.setProjectName(repairList.get(i).getProjectName());
                            addVO.setProjectAddress(repairList.get(i).getProjectAddress());
                            addVO.setReflectName(repairList.get(i).getReflectName());
                            addVO.setReflectPhone(repairList.get(i).getReflectPhone());
                            addVO.setRepairContent(repairList.get(i).getRepairContent());
                            addVO.setRepairPicture(repairList.get(i).getRepairPicture());
                            list.add(addVO);
                        }
                    }
                }
            }

        }

        return list;
    }

    @Override
    public void remove(Integer id){
        CrmDeviceRepair one = this.getById(id);
        Optional.ofNullable(one).orElseThrow(() -> new BusinessException("报修记录不存在"));
        this.removeById(id);
    }

    @Override
    public void fill(CrmDeviceRepair crmDeviceRepair1){
        crmDeviceRepair1.setRepairStatus(2);
        crmDeviceRepair1.setHandleTime(LocalDateTime.now());
        this.updateById(crmDeviceRepair1);

//        CrmDeviceRepair crmDeviceRepair = this.getById(crmDeviceRepair1.getId());

//        //发送短信
//        StringBuffer sendStatus = new StringBuffer();
//        StringBuffer sendContext = new StringBuffer();
//        DefaultProfile profile = DefaultProfile.getProfile("cn-beijing", "LTAI5tH3VvRL5BUkovCokHJX", "SaaWUouNqvcA0C746gcNOH9m6SRYN4");
//        IAcsClient client = new DefaultAcsClient(profile);
//        SendSmsRequest request = new SendSmsRequest();
//        request.setPhoneNumbers(crmDeviceRepair.getReflectPhone());//接收短信的手机号码
//        request.setSignName("上海永天科技股份有限公司");//短信签名名称
//        request.setTemplateCode("SMS_463206001");//短信模板CODE
//
//        String custom = "#/pages/common/evaluate/index?statusBool=true&repairCode="+crmDeviceRepair.getRepairCode();
//        request.setTemplateParam("{\"name\":\""+crmDeviceRepair.getReflectName()+"\","+"\"date\":\""+crmDeviceRepair.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))+"\","+"\"custom\":\""+custom+"\"}");//短信模板变量对应的实际值
//
//        try {
//            SendSmsResponse response = client.getAcsResponse(request);
//            if(response.getCode() != null){
//                if(response.getCode().equals("OK")){
////                    sendStatus.append("1");
////                    //查询发送短信内容
////
////                    try {
////                        Thread.sleep(3000);
////                    } catch (InterruptedException e) {
////                        e.printStackTrace();
////                    }
////
////                    QuerySendDetailsRequest request1 = new QuerySendDetailsRequest();
////                    request1.setPhoneNumber(crmDeviceRepair.getReflectPhone());
////                    request1.setSendDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
////                    request1.setPageSize((long)10);
////                    request1.setCurrentPage((long)1);
////                    QuerySendDetailsResponse response1 = client.getAcsResponse(request1);
////                    if(response1.getCode() != null){
////                        if(response1.getCode().equals("OK")){
////                            sendContext.append(response1.getSmsSendDetailDTOs().get(0).getContent());
////                        }
////
////                    }
//
//                }else{
////                    sendStatus.append("2");
//                }
//            }
//            System.out.println(new Gson().toJson(response));
//        } catch (ClientException e) {
//            System.out.println("ErrCode:" + e.getErrCode());
//            System.out.println("ErrMsg:" + e.getErrMsg());
//            System.out.println("RequestId:" + e.getRequestId());
//        }

    }

    @Override
    public void score(CrmDeviceRepairScoreVO scoreVO){

        LambdaQueryWrapper<CrmDeviceRepair> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(CrmDeviceRepair::getRepairCode,scoreVO.getRepairCode());
        CrmDeviceRepair crmDeviceRepair = this.getOne(queryWrapper);
        if(Objects.isNull(crmDeviceRepair.getScore())){

        }else{
            throw new BusinessException("您已参与评分，谢谢！");
        }

        crmDeviceRepair.setScore(scoreVO.getScore());
        crmDeviceRepair.setAppraiseContent(scoreVO.getAppraiseContent());
        this.updateById(crmDeviceRepair);
    }

    @Override
    public void phoneVerify(PhoneVerifyVO phoneVerifyVO){
        String phone = phoneVerifyVO.getPhone();
        String verify = phoneVerifyVO.getVerify();
        if(!com.usky.common.core.util.StringUtils.isBlank(phone) && !com.usky.common.core.util.StringUtils.isBlank(verify)) {
            //手机验证码登录
            if (com.usky.common.core.util.StringUtils.isBlank(verify)) {
                throw new BusinessException("验证码不能为空");
            }
            if (!verify.equals(redisHelper.get(phone))) {
                throw new BusinessException("验证码错误");
            }
            if (com.usky.common.core.util.StringUtils.isBlank(phone)) {
                throw new BusinessException("用户名或手机号不能为空");
            }
        }
    }

    @Override
    public CommonPage<CrmDeviceRepair> getHistory(PhoneVerifyVO phoneVerifyVO){
        String phone = phoneVerifyVO.getPhone();

        IPage<CrmDeviceRepair> page = new Page<>(phoneVerifyVO.getCurrent(), phoneVerifyVO.getSize());
        LambdaQueryWrapper<CrmDeviceRepair> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(CrmDeviceRepair::getReflectPhone,phone)
                .orderByDesc(CrmDeviceRepair::getId);
        page = this.page(page,queryWrapper);

        return new CommonPage<>(page.getRecords(),page.getTotal(),page.getSize(),page.getCurrent());
    }
}
