/*
 * Author: wangjian
 * 生成controller
 */
package com.tofly.xrtygis.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.log.annotation.ToFlyAppLog;
import com.tofly.xrtygis.callCenterMapper.BusiAutocallData1000Mapper;
import com.tofly.xrtygis.custom.entity.message.SendMessage;
import com.tofly.xrtygis.custom.service.messge.SendMessageService;
import com.tofly.xrtygis.entity.TfMsgPersonManage;
import com.tofly.xrtygis.entity.TfMsgPushManage;
import com.tofly.xrtygis.entity.dto.TfMsgPushManageDto;
import com.tofly.xrtygis.entity.vo.TfMsgPersonManageVo;
import com.tofly.xrtygis.service.TfMsgPersonManageService;
import com.tofly.xrtygis.service.TfMsgPushManageService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 信息资讯推送管理
 *
 * @author JF
 * @date Sun Jul 03 00:00:00 CST 2022
 */
@RestController
@AllArgsConstructor
@RequestMapping("/tfmsgpushmanage")
@Api(tags="信息资讯推送管理接口")
public class TfMsgPushManageController {

    private final  TfMsgPushManageService tfMsgPushManageService;
    private final TfMsgPersonManageService tfMsgPersonManageService;
    private final SendMessageService sendMessageService;
    private final BusiAutocallData1000Mapper busiAutocallData1000Mapper;

    /**
    * 分页查询
    * @param page 分页对象
    * @param tfMsgPushManage 信息资讯推送管理
    * @return
    */
    @ToFlyAppLog(title="分页查询" )
    @GetMapping("/page" )
    @ApiOperation(value = "分页查询")
    public ResultRespone getTfMsgPushManagePage(Page page, @ModelAttribute TfMsgPushManage tfMsgPushManage) {
      return ResultRespone.success(tfMsgPushManageService.page(page, Wrappers.query(tfMsgPushManage)
              .ge(StringUtils.isNotBlank(tfMsgPushManage.getStartDate()),"TO_CHAR(SEND_TIME,'yyyy-mm-dd hh24-mm-ss')",tfMsgPushManage.getStartDate())
              .le(StringUtils.isNotBlank(tfMsgPushManage.getEndDate()),"TO_CHAR(SEND_TIME,'yyyy-mm-dd hh24-mm-ss')",tfMsgPushManage.getEndDate())
              .orderByDesc("SEND_TIME")));
    }


    /**
     * 通过id查询信息资讯推送管理
     * @param id id
     * @return ResultRespone
     */
    @ToFlyAppLog(title="通过ID查询" )
    @GetMapping("/{id}" )
    @ApiOperation(value = "通过ID查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long")
    })
    public ResultRespone getById(@PathVariable("id" ) Long id) {
      return ResultRespone.success(tfMsgPushManageService.getById(id));
    }

    /**
     * 新增信息资讯推送管理
     * @param tfMsgPushManage 信息资讯推送管理
     * @return ResultRespone
     */
    @ToFlyAppLog(title="新增信息资讯推送管理" )
    @ApiOperation(value = "新增信息资讯推送管理")
    @PostMapping
    public ResultRespone save(@Valid @RequestBody TfMsgPushManage tfMsgPushManage) {
        if(tfMsgPushManage == null){
            return ResultRespone.failed("推送信息不能为空");
        }
        if(tfMsgPushManage.getMsgPersonManages() == null || tfMsgPushManage.getMsgPersonManages().size() == 0){
            return ResultRespone.failed("推送人员列表不能为空");
        }
        //格式化消息内容
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        tfMsgPushManage.setContent(tfMsgPushManage.getContent() + "（编辑时间：" + sdf.format(new Date()) + "）");

        List<TfMsgPersonManage> personManageList = tfMsgPushManage.getMsgPersonManages();

        if(tfMsgPushManage.getIsSendNow().equals("1")){
            tfMsgPushManage.setSendTime(new Date());
        }
        tfMsgPushManage.setSendStatus("0");


        if(tfMsgPushManage.getIsSendNow().equals("1")){
            //推送呼叫
            if(tfMsgPushManage.getMsgType().equals("1")){
                for(TfMsgPersonManage personManage : personManageList){
                    Map<String,Object> callInfo = busiAutocallData1000Mapper.selectCallInfo(personManage.getPhone(),null);
                    if(callInfo == null){
                        busiAutocallData1000Mapper.insertBusiAutocallData(personManage.getPhone(),tfMsgPushManage.getContent());
                    }else {
                        busiAutocallData1000Mapper.updateBusiAutocallData(personManage.getPhone(),tfMsgPushManage.getContent());
                    }
                }
            //发送短信
            }else if(tfMsgPushManage.getMsgType().equals("2")){
                for(TfMsgPersonManage personManage : personManageList){
                    SendMessage msg = new SendMessage();
                    msg.setLxdh(personManage.getPhone());
                    msg.setTxnr(tfMsgPushManage.getContent());
                    msg.setTxlx(tfMsgPushManage.getMsgType());
                    sendMessageService.sendMessage(msg);
                }
            }
            tfMsgPushManage.setSendStatus("1");
        }

        tfMsgPushManageService.save(tfMsgPushManage);
        TfMsgPushManage msgPushManage = tfMsgPushManageService.getOne(new QueryWrapper<TfMsgPushManage>()
                .eq("CONTENT",tfMsgPushManage.getContent())
                .eq("CONTENT_TYPE",tfMsgPushManage.getContentType())
                .eq("MSG_TYPE",tfMsgPushManage.getMsgType()));
        if(msgPushManage == null){
            return ResultRespone.failed("推送人员新增失败");
        }
        for(TfMsgPersonManage msgPersonManage : personManageList){
            msgPersonManage.setMsgPushId(msgPushManage.getId());
            tfMsgPersonManageService.save(msgPersonManage);
        }
        return ResultRespone.success();
    }

    /**
     * 修改信息资讯推送管理
     * @param tfMsgPushManage 信息资讯推送管理
     * @return ResultRespone
     */
    @ToFlyAppLog(title="修改信息资讯推送管理" )
    @ApiOperation(value = "修改信息资讯推送管理")
    @PutMapping
    public ResultRespone updateById(TfMsgPushManage tfMsgPushManage) {
      return ResultRespone.success(tfMsgPushManageService.updateById(tfMsgPushManage));
    }

    /**
     * 通过id删除信息资讯推送管理
     * @param id id
     * @return ResultRespone
     */
    @ToFlyAppLog(title="通过id删除信息资讯推送管理" )
    @ApiOperation(value = "通过ID删除信息资讯推送管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long")
    })
    @DeleteMapping("/{id}" )
    public ResultRespone removeById(@PathVariable Long id) {
        tfMsgPushManageService.removeById(id);
        tfMsgPersonManageService.remove(new QueryWrapper<TfMsgPersonManage>().eq("MSG_PUSH_ID",id));
      return ResultRespone.success();
    }

    /**
     * 通过id批量删除信息资讯推送管理
     * @param ids id
     * @return ResultRespone
     */
    @ToFlyAppLog(title="通过id批量删除信息资讯推送管理" )
    @ApiOperation(value = "通过ID批量删除信息资讯推送管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "批量删除，多个id以逗号隔开", required = true, dataType = "String")
    })
    @DeleteMapping("/deleteByIds" )
    public ResultRespone removeById(String ids) {
        tfMsgPushManageService.removeByIds(Arrays.asList(ids.split(",")));
        List<String> idList = Arrays.asList(ids.split(","));
        idList.forEach(e->tfMsgPersonManageService.remove(new QueryWrapper<TfMsgPersonManage>().eq("MSG_PUSH_ID",e)));
        return ResultRespone.success();
    }
}
