package com.seeyon.apps.bip.aop;

import cn.hutool.core.convert.Convert;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.cap4.form.bean.FormFieldComEnum;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.organization.bo.*;
import com.seeyon.ctp.organization.manager.OrgManager;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 功能描述:<br>
 * <pre>
 *  处理数据
 *  转换相关参数
 *  部门编码--> 部门
 *  单位编码--> 单位
 *  人员编码--> 人员
 *  岗位编号--> 岗位
 * </pre>
 *
 * @Author: FanGaowei
 * @Date: 2021/9/17
 */
@Aspect
public class BpmProcessAop {

    @Inject
    private FormApi4Cap4 formApi4Cap4;
    @Inject
    private EnumManager enumManagerNew;
    @Inject
    private OrgManager orgManager;

    private static final Log log = LogFactory.getLog(BpmProcessAop.class);

    @Pointcut("execution(public * com.seeyon.apps.collaboration.manager.CollaborationBPMHandlerImpl.transPreStartProcess(..))")
    private void dealParam() {
    }

    @Around(value = "dealParam()")
    public Object dealFormData(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("处理数据问题！！");
        Object[] args = joinPoint.getArgs();
        try {
            Map<String, Object> params = (Map<String, Object>) args[0];
            Map<String, Object> data = (Map<String, Object>) params.get("data");
            // 开始处理表单数据
            FormBean formBean = formApi4Cap4.getFormByFormCode((String) params.get("templateCode"));;
            Map<String, Object> masterData = (Map<String, Object>) data.get("masterTable");
            Map<String, Object> record = (Map<String, Object>) masterData.get("record");
            List<Map<String, String>> fields = (List<Map<String, String>>) record.get("fields");
            List<Map<String, String>> fieldsClone = new ArrayList<>();
            for (Map<String, String> field : fields) {
                String val = field.get("value");
                if(StringUtils.isNotBlank(val)) {
                    FormFieldBean fieldBean = formBean.getFieldBeanByName(field.get("name"));
                    if(null != fieldBean) {
                        field.put("value", dealParams(fieldBean, val));
                    }
                }
                fieldsClone.add(field);
            }
            // 主表字段处理完成
            record.put("fields", fieldsClone);
            masterData.put("record", record);
            data.put("masterTable", masterData);
            // 处理明细表字段
            List<Map<String, Object>> subTables = (List<Map<String, Object>>) data.get("subTables");
            if(null != subTables) {
                log.info("开始处理明细表数据");
                try {
                    List<Map<String, Object>> subTablesClone = new ArrayList<>();
                    subTables.forEach(row -> {
                        List<Map<String, Object>> subRecords = (List<Map<String, Object>>) row.get("records");
                        List<Map<String, Object>> newSubRecords = new ArrayList<>();
                        subRecords.forEach(subrecord -> {
                            List<Map<String, String>> subFields = (List<Map<String, String>>) subrecord.get("fields");
                            List<Map<String, String>> subFieldsClone = new ArrayList<>();
                            for (Map<String, String> field : subFields) {
                                String val = field.get("value");
                                if(StringUtils.isNotBlank(val)) {
                                    FormFieldBean fieldBean = formBean.getFieldBeanByName(field.get("name"));
                                    if(null != fieldBean) {
                                        field.put("value", dealParams(fieldBean, val));
                                    }
                                }
                                subFieldsClone.add(field);
                            }
                            subrecord.put("fields", subFieldsClone);
                            newSubRecords.add(subrecord);
                            row.put("records", newSubRecords);
                        });
                        subTablesClone.add(row);
                    });
                    data.put("subTables", subTablesClone);
                } catch (Exception e) {
                    log.error("处理失败：" + e.getMessage());
                }
            }
            params.put("data", data);
            args[0] = params;

        } catch (Exception e) {
            // ignore
            log.error("处理数据发生异常:", e);
        }
        return joinPoint.proceed(args);
    }

    private String dealParams(FormFieldBean field, String val) {
        FormFieldComEnum inputTypeEnum = field.getInputTypeEnum();
        try {
            switch (inputTypeEnum) {
                case RADIO:
                case SELECT:
                    String code = Convert.toStr(val);
                    if (StringUtils.isBlank(code)) {
                        val = null;
                    }
                    CtpEnumItem item = enumManagerNew .getItemByCode(code);
                    if (null == item) {
                        long enumId = field.getEnumId();
                        List<CtpEnumItem> emumItems = enumManagerNew.getEmumItemByEmumId(enumId);
                        if (null != emumItems) {
                            for (CtpEnumItem emumItem : emumItems) {
                                if (emumItem.getShowvalue().equals(code)) {
                                    val = emumItem.getId() + "";
                                    break;
                                }
                            }
                        }
                        log.error("枚举不存在：" + val);
                        val = null;
                    } else {
                        val = item.getId() + "";
                    }
                    break;
                case EXTEND_MEMBER:
                    //V3xOrgMember member = orgManager.getMemberByLoginName(val);
                    List<V3xOrgEntity> memberList  = orgManager.getEntityListNoRelation(V3xOrgMember.class.getSimpleName(),
                            "code", val, null);
                    log.info("人员转换：" + val + ",查询结果：" + (memberList != null && memberList.size() > 0));
                    if(memberList != null&&! ListUtils.EMPTY_LIST.equals(memberList)){
                        for (V3xOrgEntity v3xOrgEntity : memberList) {
                            V3xOrgMember member = (V3xOrgMember) v3xOrgEntity;
                            if(val.equals(member.getCode())){
                                val = member.getId() + "";
                                break;
                            }
                        }
                    }
                    break;
                case EXTEND_ACCOUNT:
                    List<V3xOrgEntity> accList  = orgManager.getEntityListNoRelation(V3xOrgAccount.class.getSimpleName(),
                            "code", val, null);
                    log.info("单位值转换：" + val + ",查询结果：" + (accList != null && accList.size() > 0));
                    if(accList != null&&! ListUtils.EMPTY_LIST.equals(accList)){
                        for (V3xOrgEntity acc : accList) {
                            V3xOrgAccount account = (V3xOrgAccount) acc;
                            if(val.equals(account.getCode())){
                                val = account.getId() + "";
                                break;
                            }
                        }
                    }
                    break;
                case EXTEND_DEPARTMENT:
                    List<V3xOrgEntity> deptList  = orgManager.getEntityListNoRelation(V3xOrgDepartment.class.getSimpleName(),
                            "code", val, null);
                    log.info("部门值转换：" + val + ",查询结果：" + (deptList != null && deptList.size() > 0));
                    if(deptList != null&&! ListUtils.EMPTY_LIST.equals(deptList)){
                        for (V3xOrgEntity v3xOrgEntity : deptList) {
                            V3xOrgDepartment dept = (V3xOrgDepartment) v3xOrgEntity;
                            if(val.equals(dept.getCode())){
                                val = dept.getId() + "";
                                break;
                            }
                        }
                    }
                    break;
                case EXTEND_POST:
                    List<V3xOrgEntity> postlist  = orgManager.getEntityListNoRelation(V3xOrgPost.class.getSimpleName(),
                            "code", val, null);
                    log.info("岗位转换：" + val + ",查询结果：" + (postlist != null && postlist.size() > 0));
                    if(postlist != null&&! ListUtils.EMPTY_LIST.equals(postlist)){
                        for (V3xOrgEntity v3xOrgEntity : postlist) {
                            V3xOrgPost post = (V3xOrgPost) v3xOrgEntity;
                            if(val.equals(post.getCode())){
                                val = post.getId() + "";
                                break;
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            log.error("处理字段异常：" + field.getName()+ ","  + field.getDisplay());
        }
        return val;
    }

}
