package com.testor.module.messageNotice.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.module.messageNotice.model.domain.TMsgNotice;
import com.testor.module.messageNotice.model.dto.TMsgNoticeDelParam;
import com.testor.module.messageNotice.model.dto.TMsgNoticeParam;
import com.testor.module.messageNotice.model.vo.TMsgVo;
import com.testor.module.messageNotice.service.TMsgNoticeService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import com.tongtech.tfw.workflow.apis.definition.service.ActReProcdefService;
import com.tongtech.tfw.workflow.apis.instance.service.ActHiProcinstService;
import com.tongtech.tfw.workflow.service.TfwCommonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RuntimeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 消息通知Controller
 *
 * @author testor-framework
 * @date 2022-05-18 19:38:47
 */
@RestController
@RequestMapping("/messageNotice/messageNotice")
@Api(value = "TMsgNotice", tags = "消息通知")
@Slf4j
public class TMsgNoticeController extends SuperController {
    @Autowired
    private TMsgNoticeService tMsgNoticeService;
	@Autowired
	private ActHiProcinstService actHiProcinstService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private TfwCommonService tfwCommonService;
	@Autowired
	private ActReProcdefService actReProcdefService;

//    /* Generated Method*/
//	@ApiOperation(value = "新增 消息通知", notes = "Add TMsgNotice")
//	@PostMapping(value = "/add")
//	public BaseResponse<TMsgNotice>addEntity(@RequestBody TMsgNotice addRequest) {
//		BaseResponse<TMsgNotice> baseResponse=new BaseResponse<>();
//		if(ObjectHelper.isNotEmpty(addRequest)){
//            TMsgNotice data=BeanHelper.beanToBean(addRequest,  TMsgNotice.class);
//			boolean result= tMsgNoticeService.save(data);
//			if(result){
//                TMsgNotice newEntity = new TMsgNotice();
//				newEntity.setId(id);
//				baseResponse.setData(newEntity);
//			}
//		}
//		return baseResponse;
//	}

    @ApiOperation(value = "获取 消息通知 ", notes = "Get TMsgNotice By Id")
    @GetMapping(value = "/get")
    public BaseResponse<TMsgNotice> getById(String id) {
        BaseResponse<TMsgNotice> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            TMsgNotice data = tMsgNoticeService.getById(id);
            baseResponse.setData(data);
        }
        return baseResponse;
    }

//	@ApiOperation(value = "修改 消息通知 ", notes = "Update TMsgNotice By Id")
//	@PutMapping(value = "/update")
//	public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TMsgNotice updateRequest){
//		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
//		if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId())){
//			// TODO 按需求添加数据去重，特殊值设定，业务异常
//            TMsgNotice data=BeanHelper.beanToBean(updateRequest, TMsgNotice.class);
//			boolean result= tMsgNoticeService.updateById(data);
//			baseResponse.setData(
//					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
//		}
//		return baseResponse;
//	}

    @ApiOperation(value = "删除 消息通知 ", notes = "delete TMsgNotice By Id")
    @PutMapping(value = "/delete")
    public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TMsgNoticeDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && StringHelper.isNotEmpty(deleteRequest.getId())) {
            TMsgNotice data = new TMsgNotice();
            data.setId(deleteRequest.getId());
            data.setStatus(BizConstants.STATUS_DELETE);
            boolean result = tMsgNoticeService.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "批量删除消息通知", notes = "delete TMsgNotice by batch Id")
    @PutMapping(value = "/batch_delete")
    public BaseResponse<BizGeneralResponse> deleteEntityBatch(
            @RequestBody TMsgNoticeDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
            List<TMsgNotice> tMsgNoticeList = new ArrayList<>();
            for (String id : deleteRequest.getIds()) {
                TMsgNotice data = new TMsgNotice();
                data.setId(id);
                data.setStatus(BizConstants.STATUS_DELETE);
                tMsgNoticeList.add(data);
            }
            boolean result = tMsgNoticeService.updateBatchById(tMsgNoticeList);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "获取 消息通知 分页列表", notes = "List TMsgNotice with page")
    @GetMapping(value = "/list")
    public BaseResponse<BaseResponseList<TMsgVo>> listEntity(TMsgNoticeParam param) {
        BaseResponse<BaseResponseList<TMsgVo>> baseResponse = new BaseResponse<>();
        Long page =
                StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit =
                StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TMsgNotice> resultPage = new Page<>(page, limit);
        QueryWrapper<TMsgNotice> queryWrapper1 = this.createQuery(param);
        Page<TMsgNotice> resultList = tMsgNoticeService.page(resultPage, queryWrapper1);
        List<TMsgNotice> records = resultList.getRecords();
		List<TMsgVo> tmsg = new ArrayList<>();
        for (TMsgNotice record : records) {
            /*String businessId = record.getBusinessId();
            QueryWrapper<ActHiProcinst> queryWrapper = new QueryWrapper();
            queryWrapper.eq("START_USER_ID_", this.getUserId());
            queryWrapper.eq("BUSINESS_KEY_", businessId);
            List<ActHiProcinst> resultLists = this.actHiProcinstService.list( queryWrapper);
            List<MyApplicationsListResponse> result = new ArrayList(resultLists.size());
            MyApplicationsListResponse myApplicationsListResponse = null;
            for (Iterator var9 = resultLists.iterator(); var9.hasNext(); result.add(myApplicationsListResponse)) {
                ActHiProcinst actHiProcinst = (ActHiProcinst) var9.next();
                myApplicationsListResponse = new MyApplicationsListResponse(actHiProcinst);
                myApplicationsListResponse.setStartUser(this.tfwCommonService.queryUserName(myApplicationsListResponse.getStartUser()));
                ActReProcdef actReProcdef = (ActReProcdef) this.actReProcdefService.getOne((Wrapper) (new QueryWrapper()).eq("ID_", actHiProcinst.getProcDefId()));
                //myApplicationsListResponse.setProcessDefinitionName(actReProcdef.getName());
                myApplicationsListResponse.setProcessDefinitionDescription(actReProcdef.getDescription());
                if (ObjectHelper.isEmpty(actHiProcinst.getEndTime())) {
                    List<ActivityInstance> actList = ((ActivityInstanceQuery) this.runtimeService.createActivityInstanceQuery().processInstanceId(actHiProcinst.getProcInstId()).activityType("userTask").orderByActivityInstanceStartTime().desc()).list();
                    if (!actList.isEmpty()) {
                        ActivityInstance activityInstance = (ActivityInstance) actList.get(0);
                        myApplicationsListResponse.setExecutionId(activityInstance.getExecutionId());
                        myApplicationsListResponse.setCurrentTaskName(activityInstance.getActivityName());
                        if (StringHelper.isNotBlank(activityInstance.getAssignee())) {
                            myApplicationsListResponse.setAssigneeName(this.tfwCommonService.queryUserName(activityInstance.getAssignee()));
                        }
                    }
                }
            }*/
			TMsgVo tMsgVo = new TMsgVo();
			BeanUtils.copyProperties(record, tMsgVo);
            /*if (myApplicationsListResponse != null) {
                BeanUtils.copyProperties(myApplicationsListResponse, tMsgVo);
            }*/
			tmsg.add(tMsgVo);
		}
        BaseResponseList<TMsgVo> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(tmsg);
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    @ApiOperation(value = "获取 消息通知 列表", notes = "List TMsgNotice all")
    @GetMapping(value = "/datas")
    public BaseResponse<BaseResponseList<TMsgNotice>> listAllEntity(TMsgNoticeParam param) {
        BaseResponse<BaseResponseList<TMsgNotice>> baseResponse = new BaseResponse<>();
        QueryWrapper<TMsgNotice> queryWrapper = this.createQuery(param);
        List<TMsgNotice> resultList = tMsgNoticeService.list(queryWrapper);
        BaseResponseList<TMsgNotice> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList);
        baseResponseList.setTotal(resultList.size());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    /* Private Methods */

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TMsgNotice> createQuery(TMsgNoticeParam queryParam) {
        QueryWrapper<TMsgNotice> queryWrapper = new QueryWrapper<>();
        if (StringHelper.isNotEmpty(queryParam.getUserId())) {
            queryWrapper.eq(TMsgNotice.USER_ID, queryParam.getUserId());
        }
        if (StringHelper.isNotEmpty(queryParam.getBusinessKey())) {
            String[] split = queryParam.getBusinessKey().split(",");
            queryWrapper.in(TMsgNotice.BUSINESS_KEY, Arrays.asList(split));
        }
        if (StringHelper.isNotEmpty(queryParam.getBusinessId())) {
            queryWrapper.eq(TMsgNotice.BUSINESS_ID, queryParam.getBusinessId());
        }
        if (StringHelper.isNotEmpty(queryParam.getMsgType())) {
            queryWrapper.eq(TMsgNotice.MSG_TYPE, queryParam.getMsgType());
        }
        if (StringHelper.isNotEmpty(queryParam.getTitle())) {
            queryWrapper.eq(TMsgNotice.TITLE, queryParam.getTitle());
        }
        if (StringHelper.isNotEmpty(queryParam.getContent())) {
            queryWrapper.like(TMsgNotice.CONTENT, queryParam.getContent());
        }
        if (StringHelper.isNotEmpty(queryParam.getIsRead())) {
            queryWrapper.eq(TMsgNotice.IS_READ, queryParam.getIsRead());
        }
        if (StringHelper.isNotEmpty(queryParam.getTenantId())) {
            queryWrapper.eq(TMsgNotice.TENANT_ID, queryParam.getTenantId());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TMsgNotice.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TMsgNotice.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())) {
            if (StringHelper.isNotEmpty(queryParam.getOrderType())
                    && BizConstants.ASC.equals(queryParam.getOrderType())) {
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            } else {
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        } else {
            queryWrapper.orderByDesc(TMsgNotice.UPDATE_DATE);
        }
        return queryWrapper;
    }

    @ApiOperation(value = "测试 消息通知")
    @PostMapping(value = "/testProcessPassMsgHandle")
    public BaseResponse testProcessPassMsgHandle() {
        BaseResponse<TMsgNotice> baseResponse = new BaseResponse<>();

        // todo 调用消息通知 新增 的接口 创建 消息通知
        String startUserId = "1242684364872761344";
        String businessKey = "dutyUpdate";
        //String variablesMapStr = "{\"processStatus\":5,\"receiverObj\":[[\"32cdbb3a278944f1a83ca40dbcc93c0a\",\"20e3aa499cd24146a65db817b2e6362e\",\"09bde5f64f1f42fd80ce4255f21dea7a\"],[\"32cdbb3a278944f1a83ca40dbcc93c0a\",\"20e3aa499cd24146a65db817b2e6362e\",\"0a86f902017a4e11bd8d34b11d5d3204\"]],\"pass\":true,\"bizKeyId\":\"2022051862849d9c18b8000d648843fd\",\"remark\":\"打发打发\",\"title\":\"公告0517\",\"content\":\"<p>公告</p>\",\"INITIATOR\":\"1242684364872761344\",\"refArray\":\"\",\"executor\":\"1242684364872761344\",\"tenantId\":\"\",\"refId\":\"20220517628361b0c9c2ef09eb681341\",\"executorOrgId\":\"1242684364872761344\",\"createDate\":\"\",\"status\":\"0\"}";
        String variablesMapStr = "{\"processStatus\":5,\"receiverObj\":[[\"32cdbb3a278944f1a83ca40dbcc93c0a\",\"20e3aa499cd24146a65db817b2e6362e\",\"09bde5f64f1f42fd80ce4255f21dea7a\"],[\"32cdbb3a278944f1a83ca40dbcc93c0a\",\"20e3aa499cd24146a65db817b2e6362e\",\"0a86f902017a4e11bd8d34b11d5d3204\"]],\"pass\":true,\"bizKeyId\":\"2022051862849d9c18b8000d648843fd\",\"remark\":\"打发打发\",\"title\":\"公告0517\",\"content\":\"<p>公告</p>\",\"INITIATOR\":\"1242684364872761344\",\"refArray\":\"\",\"executor\":\"1242684364872761344\",\"tenantId\":\"\",\"refId\":\"20220517628361b0c9c2ef09eb681341\",\"executorOrgId\":\"1242684364872761344\",\"createDate\":\"\",\"status\":\"0\",\n" +
                "\"origPerson\": \"403c29fc154e4e0aa3901bf48a49d45c\",\n" +
                "\"nowPerson\":\"93fe70fa72224d0a8aab04efcad6ac77,1365cabd4cca4f64bbc8d168ee98cb44\"}";
        Map variablesMap = JSON.parseObject(variablesMapStr, Map.class);
        tMsgNoticeService.processPassMsgHandle(startUserId, businessKey, variablesMap);

        return baseResponse;
    }

    @ApiOperation(value = "标记已读(根据消息id)（全部已读）")
    @GetMapping(value = "/markReadById")
    public BaseResponse markReadById(@ApiParam("消息通知id,多个英文,分割；-1时标记全部已读") @RequestParam String msgNoticeIds) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (!StrUtil.isBlank(msgNoticeIds)) {
            boolean result = tMsgNoticeService.readByArr(msgNoticeIds);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "标记已读(根据业务id)")
    @GetMapping(value = "/markReadByKey")
    public BaseResponse markReadByKey(@ApiParam("业务模块key") @RequestParam String businessKey, @ApiParam("业务id,多个英文,分割") @RequestParam String businessIds) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (!StrUtil.isBlank(businessKey) && !StrUtil.isBlank(businessIds)) {
            boolean result = tMsgNoticeService.readByArr(businessKey, businessIds);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "统计用户 每个流程定义中 未读的个数", notes = "统计用户 每个流程定义中 未处理的个数")
    @GetMapping(value = "/countUnRead")
    public BaseResponse<List<Map>> countUnRead() {
        BaseResponse<List<Map>> baseResponse = new BaseResponse<>();
        List<Map> countList = tMsgNoticeService.countUnRead(ContextUtils.getLoginUserId());
        baseResponse.setData(countList);
        return baseResponse;
    }
}
