package com.jpsoft.shinestar.modules.base.controller;

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.WxConfig;
import com.jpsoft.shinestar.modules.base.entity.AlarmInfo;
import com.jpsoft.shinestar.modules.base.entity.OwnerInfo;
import com.jpsoft.shinestar.modules.base.entity.PersonInfo;
import com.jpsoft.shinestar.modules.base.entity.PersonPopedom;
import com.jpsoft.shinestar.modules.base.service.AlarmInfoService;
import com.jpsoft.shinestar.modules.base.service.OwnerInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonPopedomService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.JwtUtil2;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.common.utils.WechatMessageUtil;
import com.jpsoft.shinestar.modules.wechat.entity.AccessControl;
import com.jpsoft.shinestar.modules.wechat.service.IAccessControlService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.*;

@RestController
@RequestMapping("/base/alarmInfo")
public class AlarmInfoController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private AlarmInfoService alarmInfoService;

    @Autowired
    private OwnerInfoService ownerInfoService;

    @Autowired
    private IAccessControlService accessControlService;

    @Autowired
    private WxConfig wxConfig;

    @Value("${jwt.secret}")
    private String jwtSecret;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private PersonPopedomService personPopedomService;

    @PostMapping("alarmNotify")
    public MessageResult<String> alarmNotify(String channelName,String message,String openId){
        MessageResult<String> msgResult = new MessageResult<>();
        logger.info(message);
        try {
            AlarmInfo alarmInfo = new AlarmInfo();
            alarmInfo.setId(UUID.randomUUID().toString());
            alarmInfo.setDelFlag(false);
            //alarmInfo.setCreateBy(subject);
            alarmInfo.setIsRead(false);
            //2019-12-07 11:04:04.322  INFO 11000 --- [nio-8080-exec-5] c.j.s.m.b.c.AlarmInfoController          : 周界入侵，目标ID：13974，区域范围：(0.327,0.698)(0.674,0.936)(0.67,0.985)(0.352,0.973)

            /*int zjIndex = message.indexOf("周界入侵");
            int bjIndex = message.indexOf("报警主机CID报告");
            if(zjIndex >= 0){
                message = message.substring(zjIndex,message.length());
            }else if(bjIndex >= 0){
                int index = message.indexOf("报告类型");
                if(index >= 0) {
                    message = "报警主机CID报告，" + message.substring(index, message.length());
                }
            }*/

            alarmInfo.setChannelName(channelName);
            alarmInfo.setMessage(message);
            alarmInfo.setType("2");
            alarmInfo.setCreateTime(new Date());
            int affectCount = alarmInfoService.insert(alarmInfo);

            if (affectCount > 0) {
                PersonInfo personInfo = personInfoService.findByOpenId(openId);

                if(personInfo!=null){
                    String token = JwtUtil2.createToken(jwtSecret, String.valueOf(personInfo.getId()), DateTime.now().plusMonths(1).toDate());

                    String url = MessageFormat.format(wxConfig.getPortalUrl() + "master/electronicFence/alarm?exchange=1&token={0}&role_id={1}",
                            URLEncoder.encode(token,"UTF-8"), personInfo.getPopedom());

                    WechatMessageUtil.sendAlarmNoticeMessage(message,alarmInfo.getCreateTime(),url, openId,wxConfig.getAppId(),wxConfig.getAppSecret());
                }

                msgResult.setResult(true);
                msgResult.setData("成功");
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("添加失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }
        return msgResult;
    }

    @ApiOperation(value="创建空记录")
    @GetMapping("create")
    public MessageResult<AlarmInfo> create(){
        MessageResult<AlarmInfo> msgResult = new MessageResult<>();

        AlarmInfo alarmInfo = new AlarmInfo();

        msgResult.setData(alarmInfo);
        msgResult.setResult(true);

        return msgResult;
    }
    
    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<AlarmInfo> add(@RequestBody AlarmInfo alarmInfo,@RequestAttribute String subject){
        MessageResult<AlarmInfo> msgResult = new MessageResult<>();

        try {
            alarmInfo.setId(UUID.randomUUID().toString());
            alarmInfo.setDelFlag(false);
            alarmInfo.setCreateBy(subject);
            alarmInfo.setCreateTime(new Date());
            
            int affectCount = alarmInfoService.insert(alarmInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(alarmInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="获取信息")
    @GetMapping("edit/{id}")
    public MessageResult<AlarmInfo> edit(@PathVariable("id") String id){
        MessageResult<AlarmInfo> msgResult = new MessageResult<>();

        try {
            AlarmInfo alarmInfo = alarmInfoService.get(id);

            if (alarmInfo != null) {
                msgResult.setResult(true);
                msgResult.setData(alarmInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="更新用户")
    @PostMapping("update")
    public MessageResult<AlarmInfo> update(@RequestBody AlarmInfo alarmInfo,@RequestAttribute String subject){
        MessageResult<AlarmInfo> msgResult = new MessageResult<>();

        try {
            alarmInfo.setUpdateBy(subject);
            alarmInfo.setUpdateTime(new Date());
            
            int affectCount = alarmInfoService.update(alarmInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(alarmInfo);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库更新失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

	@ApiOperation(value="删除")
    @PostMapping("delete/{id}")
    public MessageResult<Integer> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            AlarmInfo alarmInfo = alarmInfoService.get(id);
            alarmInfo.setDelFlag(true);
            alarmInfo.setUpdateBy(subject);
            alarmInfo.setUpdateTime(new Date());

            int affectCount = alarmInfoService.update(alarmInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value="批量删除")
    @PostMapping("batchDelete")
    public MessageResult<Integer> batchDelete(@RequestBody List<String> idList,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            for (String id : idList) {
                AlarmInfo alarmInfo = alarmInfoService.get(id);
                alarmInfo.setDelFlag(true);
                alarmInfo.setUpdateBy(subject);
                alarmInfo.setUpdateTime(new Date());

                affectCount += alarmInfoService.update(alarmInfo);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String id,
            @RequestParam(value="type",defaultValue="") String type,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date queryStartTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date queryEndTime,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);

        MessageResult<Map> msgResult = new MessageResult<>();

        Map<String,Object> searchParams = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("create_time","desc"));

        if (StringUtils.isNotEmpty(id)) {
            searchParams.put("id","%" + id + "%");
        }

        if (StringUtils.isNotEmpty(type)) {
            //searchParams.put("type",type);
        }

        if(queryStartTime != null){
            searchParams.put("queryStartTime",queryStartTime);
        }

        if(queryEndTime != null){
            searchParams.put("queryEndTime",queryEndTime);
        }

        Page<AlarmInfo> page = alarmInfoService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;
    }

    @ApiOperation(value="查询报警信息")
    @RequestMapping(value = "queryNotify",method = RequestMethod.POST)
    public MessageResult<String> queryNotify(
            String type,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);

        MessageResult<String> msgResult = new MessageResult<>();

        AlarmInfo alarmInfo = alarmInfoService.queryLatestAlarm(type);

        if(alarmInfo == null){
            msgResult.setResult(false);
        }else {
            msgResult.setResult(true);
            msgResult.setData(alarmInfo.getMessage());

            String content = alarmInfo.getMessage();

            //报警主机CID报告，sCIDCode：1401，sCIDDescribe：����，报告类型：6，防区号：65535，报警触发时间：2019-12-17 10:21:36
            //周界入侵，目标ID：761，区域范围：(0.327,0.698)(0.674,0.936)(0.67,0.985)(0.352,0.973)
            /*int zjIndex = content.indexOf("区域范围");
            int cidIndex = content.indexOf("报警主机CID报告");
            if(zjIndex >= 0){
                //周界入侵
//                int index = content.lastIndexOf("：");
//                if(index >= 0){
//                    content = content.substring(index+1,content.length());
//                }
                content = content;
            }else if(cidIndex >= 0){
                //报警主机CID报告
                int startIndex = content.lastIndexOf("报告类型");
                int endIndex = content.lastIndexOf("报警触发时间");
                if(startIndex >= 0){
                    content = content.substring(0,endIndex-1);
                }
            }*/

            //发送通知
            //String openId = "oHjCawgwCGen5k1-hAsimdEX5lZo";
//            String openId = "";
//            List<OwnerInfo> lstOwner = ownerInfoService.list();
//            for(OwnerInfo owner : lstOwner) {
//                AccessControl accessControl = accessControlService.findByOwnerId(owner.getId());
//                if(accessControl != null){
//                    openId = accessControl.getOpenId();
//                    boolean result = WechatMessageUtil.sendAlarmNoticeMessage("报警警报", content,alarmInfo.getCreateTime(), openId, "","8dpP8XM1XaiiIByXiuAeFIZeNjEow1AleG_h8O2xyVA","wx7e70eb62a8459869","909d17e353268da57c4f18cc09798049");
//                    if(result) {
//                        //修改阅读状态
//                        alarmInfo.setIsRead(true);
//                    }
//                }
//            }
            alarmInfoService.update(alarmInfo);

        }
        return msgResult;
    }

}
