package com.house365.ws.util;

import com.house365.beans.entity.*;
import com.house365.ws.beans.util.HResult;
import com.house365.ws.dao.mapper.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 日志工具类
 *
 * @author zy
 */
@Component
public class OperateLogUtils {

    private Logger logger = LoggerFactory.getLogger(OperateLogUtils.class);

    @Autowired
    private ProjectLogMapper logMapper;
    @Autowired
    private CustomerLogMapper customerLogMapper;
    @Autowired
    private LogFieldMapper fieldMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private ExternalCustomerLogMapper externalCusLogMapper;
    @Autowired
    private ExternalCustomerMapper externalCusMapper;

    /**
     * 除编辑外其他类型的日志(项目日志)
     *
     * @param id       关联id
     * @param type     类型  日志类型
     * @param userId   操作人id
     * @param userName 操作人姓名
     */
    public void saveProjectLog(int id, int type, int userId, String userName) {
        try {
            ProjectLogEntity logEntity = new ProjectLogEntity();
            logEntity.setRelateId(id);
            logEntity.setType(type);
            logEntity.setModifyColumn("");
            logEntity.setModifyName("");
            logEntity.setOldValue("");
            logEntity.setNewValue("");
            logEntity.setCreateUserId(userId);
            logEntity.setCreateUserName(userName);
            logEntity.setCreateTime(new Date());
            logMapper.save(logEntity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("saveProjectLog失败", e);
        }
    }


    /**
     * <p>记录操作日志。
     * 调用方方法须有事务管理，若是新增操作，则target传null。
     * 新增在保存方法后调
     * </p>
     *
     * @param source 旧值
     * @param target 新值
     * @return HResult.status 0 正常 1 失败， HResult.data 为返回实体
     * @throws
     */
    public HResult<Object> recordOperateLog(Object source, Object target, int id, int userId, String userName) {
        HResult response = null;
        try {
            if (source == null) {
                return new HResult<>(-1, "参数为空");
            }
            Class sourceClass = source.getClass();
            PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(sourceClass);

            response = CompareObjects(source, target, descriptors, id, userId, userName);
        } catch (Exception e) {
            logger.error("recordOperateLog方法异常", e);
            return new HResult<>(-1, "recordOperateLog方法异常");
        }
        return response;
    }

    /**
     * <p>
     * 比较两对象
     * </p>
     *
     * @param source      旧值
     * @param target      新值
     * @param descriptors get、set方法
     * @param id          表信息
     * @return 新的对象
     */

    private HResult CompareObjects(Object source, Object target, PropertyDescriptor[] descriptors, int id, int userId, String userName) {
        Class sourceClass = source.getClass();
        HResult result = HResult.DEFAULT_OK();
        Class targetClass = target.getClass();

        if (!sourceClass.isAssignableFrom(targetClass)) {
            return new HResult<>(-1, "参数不是同一类型");
        }
        int count = 0;
        for (PropertyDescriptor descriptor : descriptors) {
            ProjectLogEntity logEntity = new ProjectLogEntity();
            Method getMethod = descriptor.getReadMethod();
            Method setMethod = descriptor.getWriteMethod();
            if (getMethod == null || setMethod == null) {
                continue;
            }

            //属性名
            String name = descriptor.getName();
            String srcValue = null == getValue(source, name) ? "" : String.valueOf(getValue(source, name));
            String tarValue = null == getValue(target, name) ? "" : String.valueOf(getValue(target, name));
            if (srcValue.equals(tarValue)) {
                continue;
            }
            if ("updateTime".equals(name) || "updateUserid".equals(name) || "updateUsername".equals(name) || "createTime".equals(name)) {
                continue;
            }
            if ("showStatus".equals(name)) {
                count++;
                continue;
            }

            Map<String, Object> map = new HashMap<>(10);
            map.put("type", 1);
            map.put("field", name);
            List<LogFieldEntity> list = fieldMapper.queryByConditions(map);
            if (CollectionUtils.isNotEmpty(list)) {
                logEntity.setModifyName(list.get(0).getFieldName());
            } else {
                logEntity.setModifyName("");
            }
            logEntity.setRelateId(id);
            logEntity.setModifyColumn(name);
            logEntity.setType(2);
            logEntity.setOldValue(srcValue);
            logEntity.setNewValue(tarValue);
            if ("status".equals(name)) {
                if (StringUtils.isNotBlank(srcValue)) {
                    if ("1".equals(srcValue)) {
                        logEntity.setOldValue("默认");
                    } else if ("2".equals(srcValue)) {
                        logEntity.setOldValue("执行中");
                    } else if ("3".equals(srcValue)) {
                        logEntity.setOldValue("办结");
                    } else if ("4".equals(srcValue)) {
                        logEntity.setOldValue("合同周期结束");
                    } else if ("5".equals(srcValue)) {
                        logEntity.setOldValue("终止");
                    } else if ("6".equals(srcValue)) {
                        logEntity.setOldValue("立项审核中");
                    } else if ("7".equals(srcValue)) {
                        logEntity.setOldValue("删除");
                    }
                }
                if (StringUtils.isNotBlank(tarValue)) {
                    if ("1".equals(tarValue)) {
                        logEntity.setNewValue("默认");
                    } else if ("2".equals(tarValue)) {
                        logEntity.setNewValue("执行中");
                    } else if ("3".equals(tarValue)) {
                        logEntity.setNewValue("办结");
                    } else if ("4".equals(tarValue)) {
                        logEntity.setNewValue("合同周期结束");
                    } else if ("5".equals(tarValue)) {
                        logEntity.setNewValue("终止");
                    } else if ("6".equals(tarValue)) {
                        logEntity.setNewValue("立项审核中");
                    } else if ("7".equals(tarValue)) {
                        logEntity.setNewValue("删除");
                    }
                }
            }
            logEntity.setCreateUserId(userId);
            logEntity.setCreateUserName(userName);
            logEntity.setCreateTime(new Date());
            logMapper.save(logEntity);
            count++;
        }
        //记录无变动日志
        if (count == 0 && !"经管系统".equals(userName)) {
            ProjectLogEntity logEntity = new ProjectLogEntity();
            logEntity.setRelateId(id);
            logEntity.setModifyColumn("");
            logEntity.setModifyName("");
            logEntity.setType(5);
            logEntity.setOldValue("");
            logEntity.setNewValue("");
            logEntity.setCreateUserId(userId);
            logEntity.setCreateUserName(userName);
            logEntity.setCreateTime(new Date());
            logMapper.save(logEntity);
        }
        return result;
    }

    /**
     * <p>
     * 根据实体类、属性名获取该属性值
     * </p>
     *
     * @param obj       类
     * @param fieldName 属性名
     * @return
     */
    private static Object getValue(Object obj, String fieldName) {
        if (obj == null || StringUtils.isBlank(fieldName)) {
            return null;
        }
        Object object = null;
        try {
            Class clzss = obj.getClass();
            PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName, clzss);
            Method method = propertyDescriptor.getReadMethod();
            if (method == null) {
                return null;
            }
            object = method.invoke(obj);
            if (object instanceof Date) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                object = sdf.format((Date) object);
            }
        } catch (Exception e) {
            return null;
        }
        return object;
    }

    /**
     * 除编辑外其他类型的日志(客户日志)
     *
     * @param entity   客户实体类
     * @param type     类型  日志类型
     * @param userId   操作人id
     * @param userName 操作人姓名
     */
    public void saveCustomerLog(CustomerEntity entity, int type, int userId, String userName) {
        try {
            CustomerLogEntity logEntity = new CustomerLogEntity();
            logEntity.setRelateId(entity.getId());
            logEntity.setCustomerPhone(entity.getPhone());
            if (entity.getManagerId() != null) {
                logEntity.setManagerId(entity.getManagerId());
            } else {
                logEntity.setManagerId(0);
            }
            logEntity.setType(type);
            logEntity.setModifyColumn("");
            logEntity.setModifyName("");
            logEntity.setOldValue("");
            logEntity.setNewValue("");
            if (type == 4 || type == 5 || type == 7 || type == 9) {
                if (entity.getManagerId() != null) {
                    logEntity.setNewValue(entity.getManagerId().toString());
                }
            }
            logEntity.setCreateTime(new Date());
            logEntity.setCreateUserId(userId);
            logEntity.setCreateUserName(userName);
            customerLogMapper.save(logEntity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("saveCustomerLog失败", e);
        }
    }

    public void saveCustomerLog2(CustomerEntity entity, int type, int userId, String userName, String oldValue, String newValue) {
        try {
            CustomerLogEntity logEntity = new CustomerLogEntity();
            logEntity.setRelateId(entity.getId());
            logEntity.setCustomerPhone(entity.getPhone());
            if (entity.getManagerId() != null) {
                logEntity.setManagerId(entity.getManagerId());
            } else {
                logEntity.setManagerId(0);
            }
            logEntity.setType(type);
            logEntity.setModifyColumn("");
            logEntity.setModifyName("");
            logEntity.setOldValue(oldValue);
            logEntity.setNewValue(newValue);
            if (type == 4 || type == 5 || type == 7 || type == 9) {
                if (entity.getManagerId() != null) {
                    logEntity.setNewValue(entity.getManagerId().toString());
                }
            }
            logEntity.setCreateTime(new Date());
            logEntity.setCreateUserId(userId);
            logEntity.setCreateUserName(userName);
            customerLogMapper.save(logEntity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("saveCustomerLog失败", e);
        }
    }

    /**
     * 除编辑外其他类型的日志(外部客户日志)
     *
     * @param entity   客户实体类
     * @param type     类型  日志类型
     * @param userId   操作人id
     * @param userName 操作人姓名
     */
    public void saveExterCustomerLog(ExternalCustomerEntity entity, int type, int userId, String userName) {
        try {
            ExternalCustomerLogEntity logEntity = new ExternalCustomerLogEntity();
            logEntity.setRelateId(entity.getId());
            logEntity.setCustomerPhone(entity.getPhone());
            logEntity.setManagerId(entity.getManagerId());

            logEntity.setType(type);
            logEntity.setModifyColumn("");
            logEntity.setModifyName("");
            logEntity.setOldValue("");
            logEntity.setNewValue("");
            logEntity.setCreateTime(new Date());
            logEntity.setCreateUserId(userId);
            logEntity.setCreateUserName(userName);
            externalCusLogMapper.save(logEntity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("saveExterCustomerLog失败", e);
        }
    }

    /**
     * 客户日志记录方法
     *
     * @param source
     * @param target
     * @param id
     * @param userId
     * @param userName
     * @return
     */
    public HResult<Object> newRecordOperateLog(Object source, Object target, int id, int userId, String userName) {
        HResult response = null;
        try {
            if (source == null) {
                return new HResult<>(-1, "参数为空");
            }
            Class sourceClass = source.getClass();
            PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(sourceClass);

            response = newCompareObjects(source, target, descriptors, id, userId, userName);
        } catch (Exception e) {
            logger.error("newRecordOperateLog方法异常", e);
            return new HResult<>(-1, "newRecordOperateLog方法异常");
        }
        return response;
    }

    /**
     * 客户日志只针对几个字段做改变
     */
    private HResult newCompareObjects(Object source, Object target, PropertyDescriptor[] descriptors, int id, int userId, String userName) {
        Class sourceClass = source.getClass();
        HResult result = HResult.DEFAULT_OK();
        Class targetClass = target.getClass();

        if (!sourceClass.isAssignableFrom(targetClass)) {
            return new HResult<>(-1, "参数不是同一类型");
        }
        int count = 0;
        for (PropertyDescriptor descriptor : descriptors) {
            //属性名
            String name = descriptor.getName();
            if ("name".equals(name) || "sex".equals(name) || "bakPhone1".equals(name) || "traceStatus".equals(name) || "buyIntention".equals(name)) {

                CustomerLogEntity logEntity = new CustomerLogEntity();
                Method getMethod = descriptor.getReadMethod();
                Method setMethod = descriptor.getWriteMethod();
                if (getMethod == null || setMethod == null) {
                    continue;
                }

                String srcValue = null == getValue(source, name) ? "" : String.valueOf(getValue(source, name));
                String tarValue = null == getValue(target, name) ? "" : String.valueOf(getValue(target, name));
                if (srcValue.equals(tarValue)) {
                    continue;
                }
                Map<String, Object> map = new HashMap<>(10);
                map.put("type", 2);
                map.put("field", name);
                List<LogFieldEntity> list = fieldMapper.queryByConditions(map);
                if (CollectionUtils.isNotEmpty(list)) {
                    logEntity.setModifyName(list.get(0).getFieldName());
                } else {
                    logEntity.setModifyName("");
                }
                CustomerEntity customerEntity = customerMapper.queryById(id);
                logEntity.setRelateId(id);
                logEntity.setCustomerPhone(customerEntity.getPhone());
                if (customerEntity.getManagerId() != null) {
                    logEntity.setManagerId(customerEntity.getManagerId());
                } else {
                    logEntity.setManagerId(0);
                }
                logEntity.setModifyColumn(name);
                logEntity.setType(2);
                logEntity.setOldValue(srcValue);
                logEntity.setNewValue(tarValue);
                //翻译展示
                if ("buyIntention".equals(name)) {
                    if (StringUtils.isNotBlank(srcValue)) {
                        if ("1".equals(srcValue)) {
                            logEntity.setOldValue("A");
                        } else if ("2".equals(srcValue)) {
                            logEntity.setOldValue("B");
                        } else if ("3".equals(srcValue)) {
                            logEntity.setOldValue("C");
                        } else if ("4".equals(srcValue)) {
                            logEntity.setOldValue("D");
                        } else if ("5".equals(srcValue)) {
                            logEntity.setOldValue("E");
                        }
                    }
                    if (StringUtils.isNotBlank(tarValue)) {
                        if ("1".equals(tarValue)) {
                            logEntity.setNewValue("A");
                        } else if ("2".equals(tarValue)) {
                            logEntity.setNewValue("B");
                        } else if ("3".equals(tarValue)) {
                            logEntity.setNewValue("C");
                        } else if ("4".equals(tarValue)) {
                            logEntity.setNewValue("D");
                        } else if ("5".equals(tarValue)) {
                            logEntity.setNewValue("E");
                        }
                    }
                }
                if ("traceStatus".equals(name)) {
                    if (StringUtils.isNotBlank(srcValue)) {
                        if ("1".equals(srcValue)) {
                            logEntity.setOldValue("有效");
                        } else if ("2".equals(srcValue)) {
                            logEntity.setOldValue("已购");
                        } else if ("3".equals(srcValue)) {
                            logEntity.setOldValue("我购");
                        } else if ("4".equals(srcValue)) {
                            logEntity.setOldValue("暂缓");
                        }
                    }
                    if (StringUtils.isNotBlank(tarValue)) {
                        if ("1".equals(tarValue)) {
                            logEntity.setNewValue("有效");
                        } else if ("2".equals(tarValue)) {
                            logEntity.setNewValue("已购");
                        } else if ("3".equals(tarValue)) {
                            logEntity.setNewValue("我购");
                        } else if ("4".equals(tarValue)) {
                            logEntity.setNewValue("暂缓");
                        }
                    }
                }
                if ("sex".equals(name)) {
                    if (StringUtils.isNotBlank(srcValue)) {
                        if ("0".equals(srcValue)) {
                            logEntity.setOldValue("女");
                        } else if ("1".equals(srcValue)) {
                            logEntity.setOldValue("男");
                        } else if ("2".equals(srcValue)) {
                            logEntity.setOldValue("未知");
                        }
                    }
                    if (StringUtils.isNotBlank(tarValue)) {
                        if ("0".equals(tarValue)) {
                            logEntity.setNewValue("女");
                        } else if ("1".equals(tarValue)) {
                            logEntity.setNewValue("男");
                        } else if ("2".equals(tarValue)) {
                            logEntity.setNewValue("未知");
                        }
                    }
                }
                logEntity.setCreateUserId(userId);
                logEntity.setCreateUserName(userName);
                logEntity.setCreateTime(new Date());
                customerLogMapper.save(logEntity);
                count++;
            }
        }
        //记录无变动日志
        if (count == 0) {
            CustomerLogEntity logEntity = new CustomerLogEntity();
            CustomerEntity customerEntity = customerMapper.queryById(id);
            logEntity.setRelateId(id);
            logEntity.setCustomerPhone(customerEntity.getPhone());
            if (customerEntity.getManagerId() != null) {
                logEntity.setManagerId(customerEntity.getManagerId());
            } else {
                logEntity.setManagerId(0);
            }
            logEntity.setModifyColumn("");
            logEntity.setModifyName("");
            logEntity.setType(8);
            logEntity.setOldValue("");
            logEntity.setNewValue("");
            logEntity.setCreateUserId(userId);
            logEntity.setCreateUserName(userName);
            logEntity.setCreateTime(new Date());
            customerLogMapper.save(logEntity);
        }
        return result;
    }

    /**
     * 外部客户日志记录
     *
     * @param source
     * @param target
     * @param id
     * @param userId
     * @param userName
     * @return
     */
    public HResult<Object> extRecordOperateLog(Object source, Object target, int id, int userId, String userName) {
        HResult response = null;
        try {
            if (source == null) {
                return new HResult<>(-1, "参数为空");
            }
            Class sourceClass = source.getClass();
            PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(sourceClass);

            response = extCompareObjects(source, target, descriptors, id, userId, userName);
        } catch (Exception e) {
            logger.error("extRecordOperateLog方法异常", e);
            return new HResult<>(-1, "extRecordOperateLog方法异常");
        }
        return response;
    }

    /**
     * 外部客户日志只针对几个字段做改变
     */
    private HResult extCompareObjects(Object source, Object target, PropertyDescriptor[] descriptors, int id, int userId, String userName) {
        Class sourceClass = source.getClass();
        HResult result = HResult.DEFAULT_OK();
        Class targetClass = target.getClass();

        if (!sourceClass.isAssignableFrom(targetClass)) {
            return new HResult<>(-1, "参数不是同一类型");
        }
        int count = 0;
        for (PropertyDescriptor descriptor : descriptors) {
            //属性名
            String name = descriptor.getName();
            if ("name".equals(name) || "sex".equals(name) || "bakPhone".equals(name) || "traceStatus".equals(name) || "buyIntention".equals(name)) {

                ExternalCustomerLogEntity logEntity = new ExternalCustomerLogEntity();
                Method getMethod = descriptor.getReadMethod();
                Method setMethod = descriptor.getWriteMethod();
                if (getMethod == null || setMethod == null) {
                    continue;
                }

                String srcValue = null == getValue(source, name) ? "" : String.valueOf(getValue(source, name));
                String tarValue = null == getValue(target, name) ? "" : String.valueOf(getValue(target, name));
                if (srcValue.equals(tarValue)) {
                    continue;
                }
                Map<String, Object> map = new HashMap<>(10);
                map.put("type", 2);
                map.put("field", name);
                List<LogFieldEntity> list = fieldMapper.queryByConditions(map);
                if (CollectionUtils.isNotEmpty(list)) {
                    logEntity.setModifyName(list.get(0).getFieldName());
                } else {
                    logEntity.setModifyName("");
                }
                ExternalCustomerEntity customerEntity = externalCusMapper.queryById(id);
                logEntity.setRelateId(id);
                logEntity.setCustomerPhone(customerEntity.getPhone());
                logEntity.setManagerId(customerEntity.getManagerId());
                logEntity.setModifyColumn(name);
                logEntity.setType(2);
                logEntity.setOldValue(srcValue);
                logEntity.setNewValue(tarValue);
                //翻译展示
                if ("buyIntention".equals(name)) {
                    if (StringUtils.isNotBlank(srcValue)) {
                        if ("1".equals(srcValue)) {
                            logEntity.setOldValue("A");
                        } else if ("2".equals(srcValue)) {
                            logEntity.setOldValue("B");
                        } else if ("3".equals(srcValue)) {
                            logEntity.setOldValue("C");
                        } else if ("4".equals(srcValue)) {
                            logEntity.setOldValue("D");
                        } else if ("5".equals(srcValue)) {
                            logEntity.setOldValue("E");
                        }
                    }
                    if (StringUtils.isNotBlank(tarValue)) {
                        if ("1".equals(tarValue)) {
                            logEntity.setNewValue("A");
                        } else if ("2".equals(tarValue)) {
                            logEntity.setNewValue("B");
                        } else if ("3".equals(tarValue)) {
                            logEntity.setNewValue("C");
                        } else if ("4".equals(tarValue)) {
                            logEntity.setNewValue("D");
                        } else if ("5".equals(tarValue)) {
                            logEntity.setNewValue("E");
                        }
                    }
                }
                if ("traceStatus".equals(name)) {
                    if (StringUtils.isNotBlank(srcValue)) {
                        if ("1".equals(srcValue)) {
                            logEntity.setOldValue("有效");
                        } else if ("2".equals(srcValue)) {
                            logEntity.setOldValue("已购");
                        } else if ("3".equals(srcValue)) {
                            logEntity.setOldValue("我购");
                        } else if ("4".equals(srcValue)) {
                            logEntity.setOldValue("暂缓");
                        }
                    }
                    if (StringUtils.isNotBlank(tarValue)) {
                        if ("1".equals(tarValue)) {
                            logEntity.setNewValue("有效");
                        } else if ("2".equals(tarValue)) {
                            logEntity.setNewValue("已购");
                        } else if ("3".equals(tarValue)) {
                            logEntity.setNewValue("我购");
                        } else if ("4".equals(tarValue)) {
                            logEntity.setNewValue("暂缓");
                        }
                    }
                }
                if ("sex".equals(name)) {
                    if (StringUtils.isNotBlank(srcValue)) {
                        if ("0".equals(srcValue)) {
                            logEntity.setOldValue("女");
                        } else if ("1".equals(srcValue)) {
                            logEntity.setOldValue("男");
                        } else if ("2".equals(srcValue)) {
                            logEntity.setOldValue("未知");
                        }
                    }
                    if (StringUtils.isNotBlank(tarValue)) {
                        if ("0".equals(tarValue)) {
                            logEntity.setNewValue("女");
                        } else if ("1".equals(tarValue)) {
                            logEntity.setNewValue("男");
                        } else if ("2".equals(tarValue)) {
                            logEntity.setNewValue("未知");
                        }
                    }
                }
                logEntity.setCreateUserId(userId);
                logEntity.setCreateUserName(userName);
                logEntity.setCreateTime(new Date());
                externalCusLogMapper.save(logEntity);
                count++;
            }
        }
        //记录无变动日志
        if (count == 0) {
            ExternalCustomerLogEntity logEntity = new ExternalCustomerLogEntity();
            ExternalCustomerEntity customerEntity = externalCusMapper.queryById(id);
            logEntity.setRelateId(id);
            logEntity.setCustomerPhone(customerEntity.getPhone());
            logEntity.setManagerId(customerEntity.getManagerId());
            logEntity.setModifyColumn("");
            logEntity.setModifyName("");
            logEntity.setType(8);
            logEntity.setOldValue("");
            logEntity.setNewValue("");
            logEntity.setCreateUserId(userId);
            logEntity.setCreateUserName(userName);
            logEntity.setCreateTime(new Date());
            externalCusLogMapper.save(logEntity);
        }
        return result;
    }
}























