package com.tofly.xrtygis.custom.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.xrtygis.config.CallCenterFeign;
import com.tofly.xrtygis.custom.entity.dto.QualityDto;
import com.tofly.xrtygis.custom.entity.gs.NoteSearch;
import com.tofly.xrtygis.custom.mapper.NewHotlineMapper;
import com.tofly.xrtygis.custom.service.EmergencyService;
import com.tofly.xrtygis.custom.service.NewHotlineService;
import com.tofly.xrtygis.custom.service.SendNoteService;
import com.tofly.xrtygis.custom.service.export.ExportCommonCodeService;
import com.tofly.xrtygis.entity.Dyyh;
import com.tofly.xrtygis.entity.Rxgdbzinfo;
import com.tofly.xrtygis.entity.Rxgdzjlr;
import com.tofly.xrtygis.service.DyyhService;
import com.tofly.xrtygis.service.RxgdbzinfoService;
import com.tofly.xrtygis.service.RxgdzjlrService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 泡泡
 */
@Service
@AllArgsConstructor
public class NewHotlineServiceImpl implements NewHotlineService {

    private final NewHotlineMapper newHotlineMapper;
    private final RxgdzjlrService rxgdzjlrService;
    private final RxgdbzinfoService rxgdbzinfoService;
    private final CallCenterFeign callCenterFeign;
    private final SendNoteService sendNoteService;
    private final DyyhService dyyhService;
    private final ExportCommonCodeService exportCommonCodeService;
    private final EmergencyService emergencyService;

    /**
     * 获取联系人消息
     *
     * @param dto  查询条件 为0：编码、姓名、地址、电话  为1：部门、姓名、电话
     * @param code 0：客户消息   1：员工信息
     * @return page
     */
    @Override
    public Page<Map> getContactsInfo(Page page, String dto, String code) {
        if (StringUtils.isEmpty(code)) {
            throw new ToflyDeniedException("未明确查询对象");
        }
        Page<Map> result;
        if ("0".equals(code)) {
            result = newHotlineMapper.getClientInfo(page, dto);
        } else {
            result = newHotlineMapper.getEmployeeInfo(page, dto);
        }
        return result;
    }

    /**
     * 呼叫转移-信息查询
     *
     * @param dept 部门
     * @param dto  人员名字/电话
     * @return list
     */
    @Override
    public List<Map> callShiftQuery(String dept, String dto) {
        return newHotlineMapper.callShiftQuery(dept, dto);
    }

    /**
     * 获取工单登记人员信息
     *
     * @return list
     */
    @Override
    public List<Map> getCrewInfo() {
        return newHotlineMapper.getCrewInfo();
    }

    /**
     * 获取工单类型信息
     *
     * @return list
     */
    @Override
    public List<Map> getworkOrderType() {
        return newHotlineMapper.getworkOrderType();
    }

    /**
     * 录音评分统计
     *
     * @param page  page
     * @param crew  人员
     * @param start 开始时间
     * @param end   结束时间
     * @return page
     */
    @Override
    public Page<Map> recordingStatistics(HttpServletResponse response, Page page, String crew, String start, String end, Long dept) {
        //录音总数
        Map<String, Integer> map = callCenterFeign.queryRecordNum(crew, start, end);
        Page<Map> recordGrade1 = newHotlineMapper.getRecordGrade(page, crew, start, end, dept);
        List<Map> recordGrade = recordGrade1.getRecords();
        recordGrade.forEach(m -> {
            Object pfZxry = m.get("pfZxry");
            if (map.containsKey(pfZxry)) {
                m.put("sumNum", map.get(pfZxry));
            }
        });

//        if (export == 1){
//            exportCommonCodeService.exportCode(response,"recordingStatisticsService",recordGrade1.getRecords());
//        }
        return recordGrade1;
    }

    /**
     * 坐席人员详细信息
     *
     * @param page  page
     * @param crew  人员
     * @param start 开始时间
     * @param end   结束时间
     * @param code  0：不导出  1：导出
     * @return page
     */
    @Override
    public Page getRecordInfo(HttpServletResponse response, Page page, String crew, String start, String end, String code) {
        if (StringUtils.isEmpty(code)) {
            throw new ToflyDeniedException("请选择查看方式");
        }
        if ("0".equals(code)) {
            return newHotlineMapper.getRecordInfo(page, crew, start, end);
        } else {
            exportCommonCodeService.exportCode(response, "pfrecordExcelService", newHotlineMapper.getRecordInfo(crew, start, end));
            return null;
        }
    }

    /**
     * 工单统计
     *
     * @return page
     */
    @Override
    public Page workOrderStatistics(Page page, String start, String end, String gdlx, String gdzt, String djry) {
        return newHotlineMapper.workOrderStatistics(page, start, end, gdlx, gdzt, djry);
    }

    /**
     * 查询数据统计工单详情
     *
     * @param page  page
     * @param gdlx  工单类型
     * @param start 开始时间
     * @param end   结束时间
     * @param type  0：接单/派单 1：已处理  2：终止  3：超时  4：未处理
     * @param code  0：不导出  1：导出
     * @return page
     */
    @Override
    public Page workOrderInfo(HttpServletResponse response, Page page, String gdlx, String start, String end, String type, String code, String gdzt, String djry) {
        if ("0".equals(code)) {
            return newHotlineMapper.workOrderInfo(page, gdlx, start, end, type, gdzt, djry);
        } else {
            exportCommonCodeService.exportCode(response, "workOrderInfoService", newHotlineMapper.workOrderInfo(gdlx, start, end, type, gdzt, djry));
            return null;
        }
    }

    /**
     * 查询回访工单详情
     *
     * @param response response
     * @param page     page
     * @param gdlx     工单类型
     * @param start    开始时间
     * @param end      结束时间
     * @param code     0：不导出  1：导出
     * @return page
     */
    @Override
    public Page returnVisitInfo(HttpServletResponse response, Page page, String gdlx, String start, String end, String code, String pass, String gdzt, String djry, String state) {
        if ("0".equals(code)) {
            Page<Map> mapPage;
            if ("0".equals(state)) {
                mapPage = newHotlineMapper.payAReturnVisitInfo(page, gdlx, start, end, pass, gdzt, djry);
            } else {
                mapPage = newHotlineMapper.payAReturnVisitInfoTwo(page, start, end, pass, gdzt, djry);
            }
            return mapPage;
        } else {
            List<Map> maps;
            if ("0".equals(state)) {
                maps = newHotlineMapper.payAReturnVisitInfo(gdlx, start, end, pass, gdzt, djry);
            } else {
                maps = newHotlineMapper.payAReturnVisitInfoTwo(start, end, pass, gdzt, djry);
            }
            exportCommonCodeService.exportCode(response, "returnVisitService", maps);
            return null;
        }

    }

    /**
     * 回访统计
     *
     * @param page  page
     * @param start 开始时间
     * @param end   结束时间
     * @return page
     */
    @Override
    public Page returnVisitCount(Page page, String start, String end, String gdlx, String gdzt, String djry, String state) {
        if (StringUtils.isEmpty(state)) {
            throw new ToflyDeniedException("未选择统计方式");
        }
        Page<Map> mapPage;
        if ("0".equals(state)) {
            mapPage = newHotlineMapper.returnVisitCount(page, start, end, gdlx, gdzt, djry);
        } else {
            mapPage = newHotlineMapper.returnUserCount(page, start, end, gdlx, gdzt, djry);
        }
        return mapPage;
    }


    /**
     * 客户查询
     *
     * @param dto 查询条件 编号、姓名、地址、电话
     * @return list
     */
    @Override
    public Page<Map> selectClientInfo(Page page, String dto) {
        return newHotlineMapper.selectClientInfo(page, dto);
    }

    /**
     * 热线工单质检
     *
     * @param page  page
     * @param start 开始时间
     * @param end   结束时间
     * @return page
     */
    @Override
    public Page<Map> orderQualityCount(Page page, String start, String end, String gdlx, String gdzt, String djry) {
        return newHotlineMapper.orderQualityCount(page, start, end, gdlx, gdzt, djry);
    }

    /**
     * 未质检工单详情
     *
     * @param page  page
     * @param type  工单类型
     * @param start 开始时间
     * @param end   结束时间
     * @return page
     */
    @Override
    public Page<Map> notTheQualityInfo(Page page, String type, String start, String end, String gdzt, String djry, String code) {
        return newHotlineMapper.notTheQualityInfo(page, type, start, end, gdzt, djry, code);
    }

    /**
     * 热线工单质检录入
     *
     * @param rxgdzjlr entity
     * @return boolean
     */
    @Override
    public boolean theQuality(Rxgdzjlr rxgdzjlr) {
        if (StringUtils.isEmpty(rxgdzjlr.getGdbh())) {
            throw new ToflyDeniedException("工单编号不允许为空");
        }
        rxgdzjlr.setZjsj(new Date());
        if (rxgdzjlrService.save(rxgdzjlr)) {
            newHotlineMapper.updateGdInfo(rxgdzjlr.getGdbh());
        }
        return true;
    }

    /**
     * 添加热线工单备注
     *
     * @param rxgdbzinfo rxgdbzinfo
     * @return boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertOrderNote(Rxgdbzinfo rxgdbzinfo) {
        if (StringUtils.isEmpty(rxgdbzinfo.getGdbh())) {
            throw new ToflyDeniedException("工单编号不允许为空");
        }
        Rxgdbzinfo serviceOne = rxgdbzinfoService.getOne(Wrappers.<Rxgdbzinfo>lambdaQuery()
                .eq(Rxgdbzinfo::getGdbh, rxgdbzinfo.getGdbh()));
        if (serviceOne == null) {
            return rxgdbzinfoService.save(rxgdbzinfo);
        } else {
            return rxgdbzinfoService.update(Wrappers.<Rxgdbzinfo>lambdaUpdate()
                    .eq(Rxgdbzinfo::getGdbh, rxgdbzinfo.getGdbh())
                    .set(Rxgdbzinfo::getGdbz, rxgdbzinfo.getGdbz())
                    .set(Rxgdbzinfo::getCreateUser, SecurityUtils.getUserId())
                    .set(Rxgdbzinfo::getCreateTime, new Date()));
        }
    }

    /**
     * 获取班长角色的信息
     *
     * @return list
     */
    @Override
    public List<Map<String, Object>> getRoleInfo() {
        return newHotlineMapper.getRoleInfo(SecurityUtils.getUserId());
    }

    /**
     * 通过电话获取客户信息
     *
     * @param tel 电话
     * @return list
     */
    @Override
    public List<Map> telGetInfo(String tel) {
        return newHotlineMapper.telGetInfo(tel);
    }

    @Override
    public Page<Map> allocation(Page page, String str, String qybm, String qydbm) {
        return newHotlineMapper.allocation(page, str, qybm, qydbm);
    }

    @Override
    public String getDeptNameById(Long deptId) {
        return newHotlineMapper.getDeptNameById(deptId);
    }

    @Override
    public String getRealNameById(String empcode) {
        return newHotlineMapper.getRealNameById(empcode);
    }

    @Override
    public List<Map> getHisTable() {
        return newHotlineMapper.getHisTable();
    }

    /**
     * 统计报表-获取工单质检统计
     */
    @Override
    public Page<Map> getQualityInfo(Page page, Long gdlx, String start, String end, String gdbh) {
        return newHotlineMapper.getQualityInfo(page, gdlx, start, end, gdbh);
    }

    @Override
    public List<Map> qualityCount(HttpServletResponse response, QualityDto dto) {
        List<Map> maps = newHotlineMapper.qualityCount(dto);
        if (dto.getExport() == 1) {
            exportCommonCodeService.exportCode(response, "qualityCountService", maps);
        }
        return maps;
    }

    @Override
    public Page<Map> qualityInfo(HttpServletResponse response, Page page, QualityDto dto) {
        if (dto.getExport() == 1) {
            exportCommonCodeService.exportCode(response, "qualityInfoService", newHotlineMapper.qualityInfo(dto));
        }
        return newHotlineMapper.qualityInfo(page, dto);
    }

    /**
     * 查询低压用户信息
     *
     * @param input 姓名、地址、电话、编号模糊查询
     * @param start 开始时间
     * @param end   结束数据
     * @return lsit
     */
    @Override
    public Page getDyYh(Page page, String input, String start, String end) {
        return newHotlineMapper.getDyYh(page, input, start, end);
    }

    /**
     * 发送短信给低压用户
     *
     * @param noteSearch noteSearch
     * @return Boolean
     */
    @Override
    public boolean sendNodeDyYh(NoteSearch noteSearch) {
        String clientId = noteSearch.getClientId();
        String temp = noteSearch.getTemp();
        String tempId = noteSearch.getId().toString();
        sendNoteService.sendNoteTemplate(clientId, temp, tempId);

        List<String> clientIdList = Arrays.asList(clientId.split(","));

        for (String yhbh : clientIdList) {
            Dyyh dyyh = dyyhService.getOne(Wrappers.<Dyyh>lambdaQuery()
                    .eq(Dyyh::getYhbh, yhbh));
            dyyh.setDxnum(dyyh.getDxnum() == null ? 1 : dyyh.getDxnum() + 1);
            dyyh.setNewtime(new Date());
            newHotlineMapper.updateDyyh(dyyh);
        }
        return true;
    }

    @Override
    public Map<String, Object> queryNoticeInfo(Long code) {
        String typeStr = null;
        if (code == 0) {
            typeStr = "临时停水";
        } else if (code == 1) {
            typeStr = "计划停水";
        }
        return StringUtils.isEmpty(typeStr) ? null : newHotlineMapper.queryNoticeInfo(typeStr);
    }

    /**
     * 查询用户信息
     *
     * @param code code
     * @return map
     */
    @Override
    public Map<String, Object> queryUserBalance(String code) {
        return newHotlineMapper.queryUserBalance(code);
    }

}
