package com.kingtom.shengtai.app.affair.service;

import java.text.MessageFormat;
import java.util.Collections;
import java.util.List;

import com.kingtom.kirin.app.affair.AffairConst;
import com.kingtom.kirin.app.affair.base.AbstractAffairOneHandler;
import com.kingtom.kirin.app.affair.model.AffairInfo;
import com.kingtom.kirin.app.affair.model.AffairMember;
import com.kingtom.kirin.app.affair.model.AffairTarget;
import com.kingtom.kirin.app.affair.service.IAffairService;
import com.kingtom.kirin.app.org.OrgConst;
import com.kingtom.kirin.app.org.bo.OrgPersonBO;
import com.kingtom.kirin.app.org.model.OrgIdentity;
import com.kingtom.kirin.app.org.model.OrgPerson;
import com.kingtom.kirin.app.org.model.OrgUnit;
import com.kingtom.kirin.app.org.service.IOrgIdentityService;
import com.kingtom.kirin.app.org.service.IOrgMemberService;
import com.kingtom.kirin.app.org.service.IOrgService;
import com.kingtom.kirin.app.system.model.SystemUser;
import com.kingtom.kirin.app.system.service.ISystemService;
import com.kingtom.kirin.core.common.CommonConst;
import com.kingtom.kirin.core.common.exception.AppException;
import com.kingtom.kirin.core.common.utils.CollectionUtils;
import com.kingtom.kirin.core.common.utils.IDUtils;
import com.kingtom.kirin.core.common.utils.JsonUtils;
import com.kingtom.kirin.core.resource.ResourceConst;
import com.kingtom.shengtai.app.message.model.MsgSummary;
import com.kingtom.shengtai.app.message.service.IMsgSummaryService;
import com.kingtom.shengtai.app.message.ws.WsSendService;
import jakarta.annotation.PostConstruct;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 应用模块名称</p>
 * 代码描述</p>
 * Copyright: Copyright (C) 2024 , Inc. All rights reserved. <p>
 * Company: 成都诚唐科技有限责任公司</p>
 *
 * @author wany
 * @since 2024/1/2
 */
@Slf4j
@Component
public class UserJoinOrgHandler extends AbstractAffairOneHandler{

    public static final String NAME = "UserJoinOrg";

    @Autowired
    private IAffairService affairService;

    @Autowired
    private ISystemService systemService;

    @Autowired
    private IOrgService orgService;

    @Autowired
    private IOrgMemberService orgMemberService;

    @Autowired
    private IOrgIdentityService orgIdentityService;

    @Autowired
    private IMsgSummaryService msgSummaryService;

    @Autowired
    private WsSendService wsSendService;

    @PostConstruct
    public void init(){
        affairService.registerAffairHandler(UserJoinOrgHandler.this);
    }

    @Override
    public String type(){
        return NAME;
    }

    @Override
    public void createBefore(AffairInfo info){
        Data data = JsonUtils.toObject(info.getData(), Data.class);
        SystemUser systemUser = systemService.findSystemUserById(data.getUserId());
        if(systemUser == null){
            throw new AppException("用户不存在！");
        }
        OrgUnit defaultUnit = orgService.findDefaultUnit();
        List<String> orgAdminPersonIds = orgMemberService.findOrgAdminPersonIds(defaultUnit.getId());
        if(CollectionUtils.isEmpty(orgAdminPersonIds)){
            throw new AppException("未设置组织管理员。不能创建事项！");
        }
        OrgIdentity identity =
                orgIdentityService.findByTypeAndSourceId(OrgConst.OrgIdentityTypeEnum.OrgAdmin, defaultUnit.getId());
        AffairTarget target = AffairTarget.builder().resType(ResourceConst.ResourceTypeEnum.AuthRole.getKey())
                .resId(identity.getRoleId()).build();
        info.setTarget(JsonUtils.toJson(List.of(target)));
        info.setTitle(MessageFormat.format("用户（{0}）申请加入组织【{1}】", systemUser.getName(), defaultUnit.getName()));
        info.setSummary(info.getTitle());
        info.setEffectModel(AffairConst.AffairEffectModelEnum.GenerateNow.getKey());
        info.setActionModel(AffairConst.AffairActionModelEnum.One.getKey());
        info.setEffectCondition(CommonConst.EMPTY_OBJECT_STRING);
        data.setOrgId(defaultUnit.getId());
        info.setData(JsonUtils.toJson(data));
    }

    @Override
    public void doAgree(AffairInfo info, AffairMember member){
        Data data = JsonUtils.toObject(member.getData(), Data.class);
        SystemUser systemUser = systemService.findSystemUserById(data.getUserId());
        String personId = null;
        boolean hasPerson = false;
        if(ResourceConst.ResourceTypeEnum.OrgPerson.getKey().equals(systemUser.getResType())){
            OrgPersonBO person = orgService.findPersonById(data.getOrgId(), systemUser.getResId());
            if(person != null){
                boolean isOrgMember = orgMemberService.isOrgMember(data.getOrgId(), person.getPerson().getId());
                if(isOrgMember){
                    throw new AppException("用户已经加入组织，不能重复操作！");
                }
                hasPerson = true;
                personId = person.getPerson().getId();
            }
        }
        if(hasPerson){
            orgMemberService.addOrgMember(data.getOrgId(), Collections.singletonList(personId));
            //todo 加入部门岗位
        } else{
            OrgPerson person = new OrgPerson();
            person.setUserId(data.getUserId());
            person.setName(data.getName());
            person.setPhone(data.getPhone());
            //todo 加入部门岗位,用户名写的UUID原因是指定了创建用户Id
            orgService.createPerson(person, IDUtils.newUUID(), data.getOrgId(), null);
        }

        MsgSummary msgSummary = new MsgSummary();
        msgSummary.setSender("系统");
        msgSummary.setTitle("用户加入组织审核结果通知");
        msgSummary.setType("审核结果通知");
        msgSummary.setContent("用户加入组织审核通过！");
        msgSummary.setExt1(info.getId());
        msgSummaryService.createMsg(msgSummary, List.of(info.getSourceId()));
        wsSendService.sendMsg(info.getSourceId(), JsonUtils.toJson(msgSummary));
    }

    @Override
    public void doRefuse(AffairInfo info, AffairMember member){
        MsgSummary msgSummary = new MsgSummary();
        msgSummary.setSender("系统");
        msgSummary.setTitle("用户加入组织审核结果通知");
        msgSummary.setType("审核结果通知");
        msgSummary.setContent("用户加入组织审核不通过！");
        msgSummary.setExt1(info.getId());
        msgSummaryService.createMsg(msgSummary, List.of(info.getSourceId()));
        wsSendService.sendMsg(info.getSourceId(), JsonUtils.toJson(msgSummary));
    }

    @lombok.Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    private static class Data{

        private String userId;

        private String orgId;

        private String depId;

        private String postId;

        private String name;

        private String phone;

    }

}
