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

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.IdUtil;
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.auth.model.AuthRole;
import com.kingtom.kirin.app.auth.service.IAuthRoleService;
import com.kingtom.kirin.app.auth.service.IAuthService;
import com.kingtom.kirin.app.org.OrgConst;
import com.kingtom.kirin.app.org.model.OrgIdentity;
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.space.service.ISpaceFileService;
import com.kingtom.kirin.app.system.model.SystemUser;
import com.kingtom.kirin.app.system.service.ISystemService;
import com.kingtom.kirin.app.system.utils.SystemUtils;
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 com.kingtom.shengtai.app.srm.model.SrmSupplier;
import com.kingtom.shengtai.app.srm.service.ISrmSupplierService;
import jakarta.annotation.PostConstruct;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
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
 */
@Component
public class SupplierJoinHandler extends AbstractAffairOneHandler{

    private static final String SUPPLIER_JOIN_IMAGES           = "SupplierJoinImages";
    private static final String SUPPLIER_JOIN_BUSINESS_LICENSE = "SupplierJoinBusinessLicense";
    private static final String SUPPLIER_JOIN_CERTIFICATES     = "SupplierJoinCertificates";

    public static final String NAME = "SupplierJoin";

    @Autowired
    private IAffairService affairService;

    @Autowired
    private ISystemService systemService;

    @Autowired
    private IAuthRoleService roleService;

    @Autowired
    private IAuthService authService;

    @Autowired
    private IOrgService orgService;

    @Autowired
    private IOrgMemberService orgMemberService;

    @Autowired
    private IOrgIdentityService orgIdentityService;

    @Autowired
    private ISrmSupplierService supplierService;

    @Autowired
    private IMsgSummaryService msgSummaryService;

    @Autowired
    private ISpaceFileService spaceFileService;

    @Autowired
    private WsSendService wsSendService;

    @PostConstruct
    public void init(){
        affairService.registerAffairHandler(SupplierJoinHandler.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(info.getSourceId());
        if(systemUser == null){
            throw new AppException("用户不存在！");
        }
        OrgUnit defaultUnit = orgService.findDefaultUnit();
        List<String> orgAdminPersonIds = orgMemberService.findOrgMemberPersonIds(defaultUnit.getId());
        if(CollectionUtils.isEmpty(orgAdminPersonIds)){
            throw new AppException("没有组织成员，不能创建事项！");
        }
        OrgIdentity identity =
                orgIdentityService.findByTypeAndSourceId(OrgConst.OrgIdentityTypeEnum.OrgMember, defaultUnit.getId());
        AffairTarget target = AffairTarget.builder().resType(ResourceConst.ResourceTypeEnum.AuthRole.getKey())
                .resId(identity.getRoleId()).build();
        info.setId(IDUtils.newUUID());
        info.setTarget(JsonUtils.toJson(List.of(target)));
        info.setTitle(MessageFormat.format("用户（{0}）申请成为供应商", systemUser.getName()));
        info.setSummary(info.getTitle());
        info.setEffectModel(AffairConst.AffairEffectModelEnum.GenerateNow.getKey());
        info.setActionModel(AffairConst.AffairActionModelEnum.One.getKey());
        info.setEffectCondition(CommonConst.EMPTY_OBJECT_STRING);
        //文件存储为正式文件
        List<String> imageFileIds = StringUtils.isEmpty(data.getImage()) ? null :
                List.of(data.getImage().split(CommonConst.COMMA_STRING));
        spaceFileService.doFormalOfReplace(imageFileIds,
                ResourceConst.ResourceTypeEnum.AffairInfo.getKey(), info.getId(), SUPPLIER_JOIN_IMAGES);
        spaceFileService.doFormalOfReplace(data.getBusinessLicense(),
                ResourceConst.ResourceTypeEnum.AffairInfo.getKey(), info.getId(), SUPPLIER_JOIN_BUSINESS_LICENSE);
        List<String> certificateFileIds = StringUtils.isEmpty(data.getCertificates()) ? null :
                List.of(data.getCertificates().split(CommonConst.COMMA_STRING));
        spaceFileService.doFormalOfReplace(certificateFileIds,
                ResourceConst.ResourceTypeEnum.AffairInfo.getKey(), info.getId(), SUPPLIER_JOIN_CERTIFICATES);
    }

    @Override
    public void doAgree(AffairInfo info, AffairMember member){
        Data data = JsonUtils.toObject(member.getData(), Data.class);
        SrmSupplier supplier = new SrmSupplier();
        supplier.setName(data.getName());
        supplier.setPerson(info.getSourceId());
        supplier.setPhone(data.getPhone());
        supplier.setAddress(data.getAddress());
        //supplier.setType(data.getType());
        supplier.setProduct(JsonUtils.toJson(data.getProduct()));
        List<String> imageIds = new ArrayList<>();
        if(StringUtils.isNotEmpty(data.getImage())){
            imageIds.addAll(Arrays.asList(data.getImage().split(CommonConst.COMMA_STRING)));
        }
        supplier.setImage(JsonUtils.toJson(imageIds));
        supplier.setIntro(data.getIntro());
        supplier.setSuperiorProduct(data.getSuperiorProduct());
        supplier.setBusinessLicense(data.getBusinessLicense());
        List<String> certificateIds = new ArrayList<>();
        if(StringUtils.isNotEmpty(data.getCertificates())){
            certificateIds.addAll(Arrays.asList(data.getCertificates().split(CommonConst.COMMA_STRING)));
        }
        supplier.setCertificates(JsonUtils.toJson(certificateIds));
        supplierService.create(supplier);

        MsgSummary msgSummary = new MsgSummary();
        msgSummary.setSender("系统");
        msgSummary.setTitle("成为供应商审核结果通知");
        msgSummary.setType("审核结果通知");
        msgSummary.setContent("成为供应商审核通过！");
        msgSummary.setExt1(info.getId());
        msgSummaryService.createMsg(msgSummary, List.of(info.getSourceId()));

        AuthRole role = roleService.findRoleByCode("supplier", SystemUtils.getCurrentSystemId());
        authService.updateRoleAddUsers(role.getId(), 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 name;

        /**
         * 手机号码
         */
        private String phone;

        /**
         * 地址
         */
        private String address;

        /**
         * 类型
         */
        private String type;

        /**
         * 产品
         */
        private List<String> product;

        /**
         * ,多个用逗号隔开
         */
        private String image;

        /**
         * 企业简介
         */
        private String intro;

        /**
         * 企业营业执照
         */
        private String businessLicense;

        /**
         * 国家权威认证机构颁发的证书,多个用逗号隔开
         */
        private String certificates;

        /**
         * 优势产品
         */
        private String superiorProduct;

    }

}
