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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.AlarmConfig;
import com.jpsoft.shinestar.modules.base.entity.CompanyInfo;
import com.jpsoft.shinestar.modules.base.service.AlarmConfigService;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.base.entity.WarningPusher;
import com.jpsoft.shinestar.modules.base.service.WarningPusherService;
import com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@RestController
@RequestMapping("/warningPusher")
@Api(description = "warningPusher")
@Slf4j
public class WarningPusherController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private WarningPusherService warningPusherService;

    @Autowired
    private UserService userService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private AlarmConfigService alarmConfigService;

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

        WarningPusher warningPusher = new WarningPusher();

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

        return msgResult;
    }

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

        try {
            warningPusher.setId(UUID.randomUUID().toString());
            warningPusher.setDelFlag(false);
            warningPusher.setCreateBy(subject);
            warningPusher.setCreateTime(new Date());

            int affectCount = warningPusherService.insert(warningPusher);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(warningPusher);
            } 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<WarningPusher> edit(@PathVariable("id") String id){
        MessageResult<WarningPusher> msgResult = new MessageResult<>();

        try {
            WarningPusher warningPusher = warningPusherService.get(id);

            if (warningPusher != null) {
                msgResult.setResult(true);
                msgResult.setData(warningPusher);
            } 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<WarningPusher> update(@RequestBody WarningPusher warningPusher,@RequestAttribute String subject){
        MessageResult<WarningPusher> msgResult = new MessageResult<>();

        try {
            warningPusher.setUpdateBy(subject);
            warningPusher.setUpdateTime(new Date());

            int affectCount = warningPusherService.update(warningPusher);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(warningPusher);
            } 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 {
            WarningPusher warningPusher = warningPusherService.get(id);
            warningPusher.setDelFlag(true);
            warningPusher.setUpdateBy(subject);
            warningPusher.setUpdateTime(new Date());

            int affectCount = warningPusherService.update(warningPusher);

            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) {
                WarningPusher warningPusher = warningPusherService.get(id);
                warningPusher.setDelFlag(true);
                warningPusher.setUpdateBy(subject);
                warningPusher.setUpdateTime(new Date());

                affectCount += warningPusherService.update(warningPusher);
            }

            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)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name",value = "姓名", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "phone",value = "手机号", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "companyId",value = "企业id", required = false, paramType = "form",dataType = "String")
    })
    public MessageResult<Map> pageList(
            String id,
            @RequestParam(value="name",defaultValue="") String name,
            @RequestParam(value="companyId",defaultValue="") String companyId,
            @RequestParam(value="phone",defaultValue="") String phone,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){

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

        User user = userService.get(subject);
        CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());

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

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

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("b.sort_no","asc"));

        if (StringUtils.isNotEmpty(id)) {
            searchParams.put("id","%" + id + "%");
        }
        if (StringUtils.isNotEmpty(name)) {
            searchParams.put("name","%" + name + "%");
        }
        if (StringUtils.isNotEmpty(phone)) {
            searchParams.put("phone","%" + phone + "%");
        }
        if (StringUtils.isNotEmpty(companyId)) {
            searchParams.put("companyId",companyId);
        }
        else{
            if (!userService.hasRole(subject,"SYSADMIN")) {
                searchParams.put("companyId",companyInfo.getId());
            }
        }

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

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

        return msgResult;
    }

    @ApiOperation(value="绑定微信")
    @PostMapping("bindWeChat")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "编号", required = true, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "openId",value = "微信id", required = true, paramType = "form",dataType = "String")
    })
    public MessageResult<WarningPusher> bindWeChat(@RequestParam(value="id",defaultValue="") String id,
                                                   @RequestParam(value="openId",defaultValue="") String openId,
                                                   @RequestAttribute String subject){
        MessageResult<WarningPusher> msgResult = new MessageResult<>();

        try {
            WarningPusher warningPusher = warningPusherService.get(id);
            warningPusher.setOpenId(openId);
            warningPusher.setUpdateBy(subject);
            warningPusher.setUpdateTime(new Date());

            int affectCount = warningPusherService.update(warningPusher);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(warningPusher);
            } 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="通知监管人")
    @ApiImplicitParams({
            @ApiImplicitParam(name="alarmConfigId",value = "考勤配置编号",required = true,paramType = "form"),
            @ApiImplicitParam(name = "startDate",value = "开始时间", required = true,paramType="form"),
            @ApiImplicitParam(name = "endDate",value = "截止时间", required = true,paramType="form"),
            @ApiImplicitParam(name = "subject",value = "subject", required = false,paramType="form")
    })
    @RequestMapping(value = "noticeManager",method = RequestMethod.POST)
    public MessageResult<String> noticeManager(
            String alarmConfigId,
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") Date startDate,
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") Date endDate,
            @RequestAttribute String subject){

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

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

        try {
            AlarmConfig alarmConfig = alarmConfigService.get(alarmConfigId);

            //小鹏管家配置消息模板
//            unmeasureTemperatureAlarmTask.noticeManager(alarmConfig,new DateTime(startDate),new DateTime(endDate));

            msgResult.setResult(true);
        }
        catch (Exception ex){
            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
            logger.error(ex.getMessage(),ex);
        }

        return msgResult;
    }
}
