package com.xueyi.system.staff.controller.api;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xueyi.common.cache.utils.DictUtil;
import com.xueyi.common.core.constant.basic.SqlConstants;
import com.xueyi.common.core.web.result.AjaxResult;
import com.xueyi.common.core.web.result.R;
import com.xueyi.common.security.annotation.InnerAuth;
import com.xueyi.common.sms.configure.SmsProperties;
import com.xueyi.common.web.constant.ResponseCode;
import com.xueyi.common.web.utils.DateUtils;
import com.xueyi.file.api.domain.SysFile;
import com.xueyi.file.api.feign.RemoteFileService;
import com.xueyi.system.api.dict.domain.dto.SysDictDataDto;
import com.xueyi.system.api.dict.domain.po.SysDictDataPo;
import com.xueyi.system.api.digitalmans.domain.dto.DmVisitRecordsDto;
import com.xueyi.system.api.digitalmans.domain.dto.DmVisitorsDto;
import com.xueyi.system.api.digitalmans.domain.po.DmDigitalmanExtPo;
import com.xueyi.system.api.digitalmans.domain.po.DmDigitalmanPo;
import com.xueyi.system.api.digitalmans.domain.po.DmVisitRecordsPo;
import com.xueyi.system.api.digitalmans.domain.po.DmVisitorsPo;
import com.xueyi.system.api.sms.domain.vo.SmsReqEntity;
import com.xueyi.system.api.sms.feign.RemoteSmsService;
import com.xueyi.system.api.staff.domain.dto.DmVisitCommonDto;
import com.xueyi.system.api.staff.domain.po.DmStaffPo;
import com.xueyi.system.digitalmans.mapper.DmDigitalmanExtMapper;
import com.xueyi.system.digitalmans.mapper.DmDigitalmanMapper;
import com.xueyi.system.meeting.constant.VisitRecordStatus;
import com.xueyi.system.receiver.domain.po.DmTenantReceiverPo;
import com.xueyi.system.receiver.mapper.DmTenantReceiverMapper;
import com.xueyi.system.resource.controller.api.BaseApiController;
import com.xueyi.system.resource.domain.dto.DmResourcesDto;
import com.xueyi.system.resource.service.impl.DmResourcesServiceImpl;
import com.xueyi.system.resource.service.impl.FaceServiceImpl;
import com.xueyi.system.staff.domain.model.DmVisitRecordsConverter;
import com.xueyi.system.staff.domain.model.DmVisitorSmsConfigConverter;
import com.xueyi.system.staff.domain.po.DmVisitorSmsConfigPo;
import com.xueyi.system.staff.mapper.DmStaffMapper;
import com.xueyi.system.staff.mapper.DmVisitRecordsMapper;
import com.xueyi.system.staff.mapper.DmVisitorSmsConfigMapper;
import com.xueyi.system.staff.mapper.DmVisitorsMapper;
import com.xueyi.system.staff.service.impl.DmVisitRecordsServiceImpl;
import com.xueyi.system.utils.common.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 访客管理 API业务处理
 *
 * @author xueyi
 */
@RestController
@RequestMapping("/visit/inner-api")
public class DmVisitorInnerApiController extends BaseApiController {


    @Autowired
    private DmVisitRecordsMapper dmVisitRecordsMapper;

    @Autowired
    private DmStaffMapper dmStaffMapper;

    @Autowired
    private DmVisitorsMapper dmVisitorsMapper;

    @Autowired
    private DmDigitalmanMapper digitalmanMapper;

    @Autowired
    private DmDigitalmanExtMapper digitalmanExtMapper;

    @Autowired
    private DmVisitRecordsConverter recordsConverter;

    @Autowired
    private DmVisitorSmsConfigConverter visitorSmsConfigConverter;


    @Autowired
    private DmVisitorSmsConfigMapper visitorSmsConfigMapper;

    @Autowired
    DmVisitRecordsServiceImpl visitRecordsService;

    @Autowired
    DmTenantReceiverMapper receiverMapper;

    @Autowired
    private RemoteFileService fileService;

    @Autowired
    private FaceServiceImpl faceService;

    @Autowired
    private DmResourcesServiceImpl iDmResourcesService;

    @Autowired
    private ImageUtil imageUtil;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @InnerAuth
    @PostMapping(value = "confirm-visitor")
    public com.alibaba.fastjson2.JSONObject  queryVisit(String visitorName/*, Long empId*/){

        DmVisitRecordsPo v = dmVisitRecordsMapper.findByName(visitorName/*, empId*/);

        JSONObject json = new JSONObject();
        if (null == v) {
            return output(ResponseCode.NOT_FOUND_VISITOR).toJSON();
        } else {

            json.put("empId", v.getUserId());
            DmVisitorsPo visitorsPo = dmVisitorsMapper.selectById(v.getVisitorId());
            if (visitorsPo!= null) {
                json.put("visitorName", visitorsPo.getName());
            }

//            DmStaffPo e = dmStaffMapper.selectById(v.getUserId());
            if (v.getReceiverPhone() != null){
                json.put("phone", v.getReceiverPhone());
                json.put("visitorId", v.getVisitorId());
                //给访问对象发送短信
                SmsReqEntity send = new SmsReqEntity();
                try {
                    send.setPhone(v.getReceiverPhone());
                    send.setTemplate(smsProperties.getDefaultRemindTemplate());
                    remoteSmsService.sendSms(send);
                } catch (Exception ee) {
                    ee.printStackTrace();
                }
            }

            v.setRecordStatus(DmVisitRecordsDto.STATUS_VISITED);
            v.setUpdateTime(DateUtils.dateToLocalDateTime(new Date()));
            dmVisitRecordsMapper.updateById(v);

            return outputSuccess(json).toJSON();
        }

    }

    @InnerAuth
    @PostMapping(value = "new-visitor")
    public com.alibaba.fastjson2.JSONObject newVisit(@RequestBody  DmVisitCommonDto commonDto){
        DmVisitorsPo v = null;
        if (StringUtils.isNotEmpty(commonDto.getVisitorTel())) {
            v = dmVisitorsMapper.selectOne(
                    Wrappers.<DmVisitorsPo>query().lambda()
                            .eq(DmVisitorsPo::getPhone, commonDto.getVisitorTel()).last(SqlConstants.LIMIT_ONE));
        }
        if (v == null) {
            v = new DmVisitorsPo();
            v.setName(commonDto.getVisitorName());
            v.setNickname(commonDto.getVisitorNickName());
            v.setVisitorCompany(commonDto.getVisitCompany());
            v.setPhone(commonDto.getVisitorTel());
            v.setType(DmVisitorsDto.TYPE_NORMAL_VISITOR);

            //兼容熟人介绍生人，传递访客照片
            if (StringUtils.isNotEmpty(commonDto.getVisitorBase64Img())) {
                String imgBase64 = commonDto.getVisitorBase64Img();
                R<SysFile> fileResult = fileService.uploadFace(imageUtil.base64ToMultipartFile(imgBase64));
                if (ObjectUtil.isNull(fileResult) || ObjectUtil.isNull(fileResult.getData()))
                    return output(ResponseCode.FILE_SERVICE_ERROR).toJSON();
                String url = fileResult.getData().getUrl();
                DmResourcesDto dmResourcesDto = new DmResourcesDto();
                dmResourcesDto.setType(DmResourcesDto.TYPE_PIC);
                dmResourcesDto.setUrl(url);
                dmResourcesDto.setName("stranger");

                com.alibaba.fastjson.JSONObject json = faceService.getFaceExtraction("", "", imgBase64);

                if (0!=json.getInteger("status")) {
                    return output(-1, json.getString("errMsg")).toJSON();
                } else {
                    JSONArray obj = json.getJSONArray("result").getJSONObject(0).getJSONArray("faces").getJSONObject(0).getJSONArray("feature");
                    dmResourcesDto.setFeature(obj.toJSONString());
                }

                iDmResourcesService.addOne(dmResourcesDto);
                v.setAvatar(dmResourcesDto.getUrl());
                v.setResourceId(dmResourcesDto.getId());
            }
            dmVisitorsMapper.addOne(v);
        } else {
            v.setName(commonDto.getVisitorName());
            v.setNickname(commonDto.getVisitorNickName());
            v.setVisitorCompany(commonDto.getVisitCompany());
            dmVisitorsMapper.updateById(v);
        }
        DmVisitRecordsPo visitRecords = new DmVisitRecordsPo();
        try {
            DmStaffPo emp = dmStaffMapper.selectOne(
                    Wrappers.<DmStaffPo>query().lambda()
                            .eq(DmStaffPo::getId, commonDto.getEmpId()).last(SqlConstants.LIMIT_ONE));
            if (ObjectUtils.isNotEmpty(emp)) {
                visitRecords.setDeptId(emp.getDeptId());
                visitRecords.setVisitorId(v.getId());
                if (StringUtils.isNotEmpty(commonDto.getVisitDate())) {
                    visitRecords.setVisitDate(DateUtils.parseStrToDate(commonDto.getVisitDate(), "yyyy-MM-dd"));
                }
                visitRecords.setUserId(commonDto.getEmpId());
                visitRecords.setRecordStatus(VisitRecordStatus.getRecordStatusStart());
                String code = visitRecordsService.genVisitorCode();
                visitRecords.setVisitorCode(code);
                visitRecords.setReceiverName(commonDto.getEmpName());
                visitRecords.setReceiverPhone(commonDto.getEmpTel());
                dmVisitRecordsMapper.insert(visitRecords);
                redisTemplate.opsForValue().increment("dashboard:create_visitor_info", 1);
                JSONObject json = new JSONObject();
                if (null != commonDto.getVisitorTel()){

                    DmVisitorSmsConfigPo dmVisitorSmsConfigPo = visitorSmsConfigMapper.selectOne(Wrappers.<DmVisitorSmsConfigPo>query().lambda().last(SqlConstants.LIMIT_ONE));

                    DmDigitalmanPo dmDigitalmanPo = digitalmanMapper.selectByCode(digitalmanExtMapper.selectOne(Wrappers.<DmDigitalmanExtPo>query().lambda().eq(DmDigitalmanExtPo::getDeviceId, commonDto.getDevId()).last(SqlConstants.LIMIT_ONE)).getManCode());

                    json.put("code", code);
                    json.put("nickName", commonDto.getVisitorName());
                    json.put("robotName", dmDigitalmanPo.getName());
                    json.put("dateTime", commonDto.getVisitDate());
                    json.put("companyName", dmVisitorSmsConfigPo!=null?dmVisitorSmsConfigPo.getCompanyName():"");
                    json.put("companyAddr", dmVisitorSmsConfigPo!=null?dmVisitorSmsConfigPo.getCompanyAddress():"");
                    json.put("receiverName", commonDto.getEmpName());
                    json.put("receiverPhone", commonDto.getEmpTel());
                    json.put("parkInfo", dmVisitorSmsConfigPo!=null?dmVisitorSmsConfigPo.getParkPrompt():"");
                    //给访客发送短信
                    SmsReqEntity send = new SmsReqEntity();

                    send.setPhone(commonDto.getVisitorTel());
                    send.setTemplate(smsProperties.getVisitorTemplate());
                    send.setDataMap(json.toJSONString());
                    remoteSmsService.sendSms(send);

                }

            } else {
                System.err.println("emp not exist");
                return output(ResponseCode.DATA_NOT_EXISTS, "员工").toJSON();
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        }


        return outputSuccess().toJSON();
    }


    @InnerAuth
    @DeleteMapping(value = "del-visitor")
    public com.alibaba.fastjson2.JSONObject delVisit(@RequestBody  DmVisitCommonDto commonDto){
        if (null != commonDto && null != commonDto.getRecordId()){
            DmVisitRecordsDto recordsDto = visitRecordsService.selectById(commonDto.getRecordId());
            if (null!= recordsDto){
                visitRecordsService.deleteById(commonDto.getRecordId());
                return outputSuccess("邀约记录删除成功").toJSON();
            } else {
                return  output(ResponseCode.DATA_NOT_EXISTS, "邀约记录").toJSON();
            }
        } else {
            return  output(ResponseCode.ILLEGAL_PARAMETER, "recordId").toJSON();
        }
    }

    @InnerAuth
    @GetMapping(value = "sms-config")
    public com.alibaba.fastjson2.JSONObject smsConfig(@RequestParam(value = "devId") String devId){

        DmVisitorSmsConfigPo dmVisitorSmsConfigPo = visitorSmsConfigMapper.selectOne(Wrappers.<DmVisitorSmsConfigPo>query().lambda().last(SqlConstants.LIMIT_ONE));

        DmDigitalmanPo dmDigitalmanPo = digitalmanMapper.selectByCode(digitalmanExtMapper.selectOne(Wrappers.<DmDigitalmanExtPo>query().lambda().eq(DmDigitalmanExtPo::getDeviceId, devId).last(SqlConstants.LIMIT_ONE)).getManCode());

        com.alibaba.fastjson2.JSONObject  output = outputSuccess(dmVisitorSmsConfigPo).toJSON();
        output.put("robotName", dmDigitalmanPo.getName());

        return output;
    }

    @InnerAuth
    @GetMapping(value = "list")
    public com.alibaba.fastjson2.JSONObject  visitList(@RequestParam(value = "empId") Long empId){
        List<DmVisitRecordsPo> v = dmVisitRecordsMapper.findByEmp(empId);

        JSONObject json = new JSONObject();

        /*json.put("empId", empId);
        DmStaffPo e = dmStaffMapper.selectById(v.getUserId());
        json.put("phone", e.getPhone());
        json.put("visitorName", visitorName);
        json.put("visitorId", v.getVisitorId());*/
        List<DmVisitRecordsDto> dtos = new ArrayList<>();

        v.forEach(item->{
            DmStaffPo e = dmStaffMapper.selectById(item.getUserId());
            DmVisitRecordsDto d = recordsConverter.mapperDto(item);
            if (null != e) {
                d.setUserPhone(e.getPhone());
                d.setUserName(e.getUserName());
            }

            DmVisitorsPo visitorsPo = dmVisitorsMapper.selectById(item.getVisitorId());
            if (null != visitorsPo) {
                d.setVisitorName(visitorsPo.getName());
            }
            if (null != item.getVisitDate()) {
                d.setVisitDateStr(DateUtils.formatDate(item.getVisitDate(), "yyyy-MM-dd"));
            }
            dtos.add(d);
        });
        json.put("data", dtos);

        return outputSuccess(json).toJSON();
    }

    @InnerAuth
    @GetMapping(value = "list-all")
    public com.alibaba.fastjson2.JSONObject  visitListAll(){
        List<DmVisitRecordsPo> v = dmVisitRecordsMapper.findList();
        JSONObject json = new JSONObject();
        List<DmVisitRecordsDto> dtos = new ArrayList<>();

        v.forEach(item->{
            if (null != item && null!=item.getUserId()) {
                DmStaffPo e = dmStaffMapper.selectById(item.getUserId());
                DmVisitRecordsDto d = recordsConverter.mapperDto(item);
                if (null != e) {
                    d.setUserPhone(e.getPhone());
                    d.setUserName(e.getUserName());
                }

                DmVisitorsPo visitorsPo = dmVisitorsMapper.selectById(item.getVisitorId());
                if (null != visitorsPo) {
                    d.setVisitorName(visitorsPo.getName());
                }
                if (null != item.getVisitDate()) {
                    d.setVisitDateStr(DateUtils.formatDate(item.getVisitDate(), "yyyy-MM-dd"));
                }
                dtos.add(d);
            }
        });
        json.put("data", dtos);

        return outputSuccess(json).toJSON();
    }


    @Autowired
    private SmsProperties smsProperties;
    @Autowired
    private RemoteSmsService remoteSmsService;
    @InnerAuth
    @PostMapping(value = "send-sms")
    public com.alibaba.fastjson2.JSONObject sendSms(@RequestParam(value = "type") Integer type){
        List<SysDictDataDto> dictDataDtos = DictUtil.getDictCache("dm_allpeople_type");
        List<String> vals = dictDataDtos.stream().map(SysDictDataPo::getValue).collect(Collectors.toList());

        if (!vals.contains(type.toString())) {
            return AjaxResult.error("传入的参数可能有误").toJson();
        }

        List<Integer> ll = new ArrayList<Integer>();
        ll.add(type);
        ll.add(DmTenantReceiverPo.ALL_TYPE);
        List<DmTenantReceiverPo> list = receiverMapper.selectList(Wrappers.<DmTenantReceiverPo>query().lambda().in(DmTenantReceiverPo::getPersonType, ll.toArray())).stream().toList();
        if (!list.isEmpty()) {
            for (DmTenantReceiverPo po : list) {
                SmsReqEntity send = new SmsReqEntity();
                try {
                    if (StringUtils.isNotEmpty(po.getReceiverPhone())) {
                        send.setPhone(po.getReceiverPhone());
                        send.setTemplate(smsProperties.getDefaultRemindTemplate());
                        remoteSmsService.sendSms(send);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        } else {
            return AjaxResult.error("请检查发送短信的配置").toJson();
        }
        return AjaxResult.success().toJson();
    }


    @InnerAuth
    @GetMapping(value = "sms-users")
    public com.alibaba.fastjson2.JSONObject smsUsers(){

        List<DmTenantReceiverPo> dmTenantReceiverPo = receiverMapper.selectList(new LambdaQueryWrapper<>());
        return outputSuccess(dmTenantReceiverPo).toJSON();
    }
}
