package cn.iocoder.yudao.server.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.notice.NoticeDO;
import cn.iocoder.yudao.module.system.dal.dataobject.oa.IotOaPersonDO;
import cn.iocoder.yudao.module.system.dal.mysql.oa.IotOaPersonMapper;
import cn.iocoder.yudao.module.system.oa.OaFlow;
import cn.iocoder.yudao.module.system.util.DingtalkUtil;
import cn.iocoder.yudao.server.dal.dataobject.CrmNoticeDO;
import cn.iocoder.yudao.server.dal.dataobject.CrmPersonDO;
import cn.iocoder.yudao.server.dal.dataobject.OaNoticeDO;
import cn.iocoder.yudao.server.dal.mysql.CrmNoticeMapper;
import cn.iocoder.yudao.server.dal.mysql.CrmPersonMapper;
import cn.iocoder.yudao.server.dal.mysql.OaNoticeMapper;
import cn.iocoder.yudao.server.dal.mysql.PmsMapper;
import cn.iocoder.yudao.server.rest.CrmRest;
import cn.iocoder.yudao.server.service.PortalOaFlow;
import com.google.common.collect.ImmutableMap;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Tag(name = "管理后台 - 待办接口")
@RestController
@RequestMapping("/portal/todo")
@Validated
public class TodoController {
    @Resource
    private PortalOaFlow portalOaFlow;
    @Resource
    private PmsMapper pmsMapper;
    @Resource
    private CrmRest crmRest;
    @Autowired
    private AdminUserApi adminUserApi;
    @Autowired
    private OaFlow oaFlow;
    @Autowired
    private CrmNoticeMapper crmNoticeMapper;
    @Autowired
    private IotOaPersonMapper iotOaPersonMapper;
    @Autowired
    private OaNoticeMapper oaNoticeMapper;
    @Autowired
    private CrmPersonMapper crmPersonMapper;

    @GetMapping("/oa")
    @PermitAll
    public CommonResult<ImmutableMap> oaTodo(String workcode, Integer pageNo, Integer pageSize) throws Exception {
        List<IotOaPersonDO> workcode1 = iotOaPersonMapper.selectList("workcode", workcode);
        if (CollUtil.isEmpty(workcode1)) {
            oaFlow.getPerson();
            workcode1 = iotOaPersonMapper.selectList("workcode", workcode);
            if (CollUtil.isEmpty(workcode1)) {
                throw new ServiceException(new ErrorCode(1,"不存在OA用户"));
            }
        }
        ImmutableMap<String, Object> oaTodo = portalOaFlow.getOaTodo(workcode1.get(0).getOaId(), pageNo, pageSize);
        return CommonResult.success(oaTodo);

//        List<IotOaPersonRespVO> iotOaPersonRespVOS = pmsMapper.selectOaPersonByCode(workcode);
//        if (CollUtil.isEmpty(iotOaPersonRespVOS)) {
//            throw new ServiceException(new ErrorCode(1,"不存在OA用户"));
//        }
//        ImmutableMap<String, Object> oaTodo = portalOaFlow.getOaTodo(iotOaPersonRespVOS.get(0).getOaId());
//        return CommonResult.success(oaTodo);
    }

    @GetMapping("/oa/done")
    @PermitAll
    public CommonResult<ImmutableMap> oaDone(String workcode, Integer pageNo, Integer pageSize) throws Exception {
        List<IotOaPersonDO> workcode1 = iotOaPersonMapper.selectList("workcode", workcode);
        if (CollUtil.isEmpty(workcode1)) {
            oaFlow.getPerson();
            workcode1 = iotOaPersonMapper.selectList("workcode", workcode);
            if (CollUtil.isEmpty(workcode1)) {
                throw new ServiceException(new ErrorCode(1,"不存在OA用户"));
            }
        }
        ImmutableMap<String, Object> oaTodo = portalOaFlow.getOaTodo(workcode1.get(0).getOaId(), pageNo, pageSize);
        return CommonResult.success(oaTodo);

//        List<IotOaPersonRespVO> iotOaPersonRespVOS = pmsMapper.selectOaPersonByCode(workcode);
//        if (CollUtil.isEmpty(iotOaPersonRespVOS)) {
//            throw new ServiceException(new ErrorCode(1,"不存在OA用户"));
//        }
//        ImmutableMap<String, Object> oaTodo = portalOaFlow.getOaTodo(iotOaPersonRespVOS.get(0).getOaId());
//        return CommonResult.success(oaTodo);
    }

    @GetMapping("/crm")
    @PermitAll
    public CommonResult<ImmutableMap<String, Object>> crmTodo(String workcode, String type, Integer pageNo, Integer pageSize) throws Exception {
        ImmutableMap<String, String> stringStringImmutableMap = crmRest.refreshToken("ec301168-d9d7-4f0c-a73c-03f50e952a3a");
        AdminUserRespDTO userByUsername = adminUserApi.getUserByUsername(workcode);
        if (userByUsername == null) {throw new ServiceException(new ErrorCode(1,"门户系统中不存在该用户"));}

        String dingUserId = DingtalkUtil.getUserInfoByMobile(userByUsername.getMobile());
        List<CrmPersonDO> crmPersonDOS = crmPersonMapper.selectList("crm_user_unionid", dingUserId);
        String crmUserId="";
        if (CollUtil.isNotEmpty(crmPersonDOS)) {
            crmUserId = crmPersonDOS.get(0).getCrmUserId();
        }
        if (StringUtils.isBlank(crmUserId)) {
            return CommonResult.success(ImmutableMap.of("todoCount",0,"todoList", new ArrayList<>()));
        }
        ImmutableMap<String, Object> access = crmRest.getCrmTodoList(String.valueOf(stringStringImmutableMap.get("access")), crmUserId, type, pageNo, pageSize);
        return CommonResult.success(access);
    }

    @GetMapping("/crm/notice")
    @PermitAll
    public CommonResult<List> crmNotice(String workcode) throws Exception {
        List<CrmNoticeDO> workCode = crmNoticeMapper.selectList("work_code", workcode);
        if (CollUtil.isNotEmpty(workCode)) {
            return CommonResult.success(workCode);
        } else {
            ImmutableMap<String, String> stringStringImmutableMap = crmRest.refreshToken("ec301168-d9d7-4f0c-a73c-03f50e952a3a");
            AdminUserRespDTO userByUsername = adminUserApi.getUserByUsername(workcode);
            if (userByUsername == null) {throw new ServiceException(new ErrorCode(1,"门户系统中不存在该用户"));}

            String dingUserId = null;
            try {
                dingUserId = DingtalkUtil.getUserInfoByMobile(userByUsername.getMobile());
            } catch (Exception e) {
                return CommonResult.success(new ArrayList<>());
            }
            List<CrmPersonDO> crmPersonDOS = crmPersonMapper.selectList("crm_user_unionid", dingUserId);
            String crmUserId="";
            if (CollUtil.isNotEmpty(crmPersonDOS)) {
                crmUserId = crmPersonDOS.get(0).getCrmUserId();
            }
            if (StringUtils.isBlank(crmUserId)) {
                return CommonResult.success(new ArrayList());
            }
            List access = crmRest.getCrmNotice(String.valueOf(stringStringImmutableMap.get("access")), crmUserId, workcode);
            return CommonResult.success(access);
        }
    }

    @GetMapping("/oa/notice")
    @PermitAll
    public CommonResult<List> oaNotice(String workcode) throws Exception {
        List<IotOaPersonDO> workcode1 = iotOaPersonMapper.selectList("workcode", workcode);
        if (CollUtil.isEmpty(workcode1)) {
            oaFlow.getPerson();
            workcode1 = iotOaPersonMapper.selectList("workcode", workcode);
            if (CollUtil.isEmpty(workcode1)) {
                throw new ServiceException(new ErrorCode(1,"不存在OA用户"));
            }
        }
        OaNoticeDO workcode2 = oaNoticeMapper.selectList("work_code", workcode).stream().max(Comparator.comparing(OaNoticeDO::getOaCreateTime))
                .orElse(null);
        List oaNotice = portalOaFlow.getOaNotice(workcode1.get(0).getOaId(), workcode2, workcode);
        return CommonResult.success(oaNotice);

    }


    @GetMapping("/crm/notice/self")
    @PermitAll
    public CommonResult<List> crmNoticeSelfSystem(String workcode) throws Exception {
        List<CrmNoticeDO> workCode = crmNoticeMapper.selectList("work_code", workcode);
        return CommonResult.success(workCode.stream().sorted(Comparator.comparing(CrmNoticeDO::getCreatedAt).reversed()).collect(Collectors.toList()));
    }

    @GetMapping("/oa/notice/self")
    @PermitAll
    public CommonResult<List> oaNoticeSelfSystem(String workcode) throws Exception {
        List<OaNoticeDO> workCode = oaNoticeMapper.selectList("work_code", workcode);
        return CommonResult.success(workCode.stream().sorted(Comparator.comparing(OaNoticeDO::getOaCreateTime).reversed()).collect(Collectors.toList()));
    }

    @GetMapping("/crm/notice/readed")
    @PermitAll
    public CommonResult<String> crmNoticeReaded(String workcode) throws Exception {
        List<CrmNoticeDO> workCode = crmNoticeMapper.selectList("work_code", workcode);
        workCode.forEach(item -> {
            //设置为已读
            item.setStatus("1");
            crmNoticeMapper.updateById(item);
        });
        return CommonResult.success("完成已读");
    }

    @GetMapping("/oa/notice/readed")
    @PermitAll
    public CommonResult<String> oaNoticeReaded(String workcode) throws Exception {
        List<OaNoticeDO> workCode = oaNoticeMapper.selectList("work_code", workcode);
        workCode.forEach(item -> {
            //设置为已读
            item.setStatus("1");
            oaNoticeMapper.updateById(item);
        });
        return CommonResult.success("完成已读");
    }
}
