package com.yh.saas.plugin.base.service.impl;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.winsea.svc.base.workflow.entity.WorkflowHistoricTask;
import com.yh.saas.toolkit.workflow.service.IWorkflowHistoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.winsea.svc.base.base.entity.CommonRole;
import com.winsea.svc.base.base.entity.CommonStaff;
import com.winsea.svc.base.base.entity.CommonStaffRole;
import com.winsea.svc.base.base.service.ICommonRoleService;
import com.winsea.svc.base.base.service.ICommonStaffRoleService;
import com.winsea.svc.base.base.service.ICommonStaffService;
import com.winsea.svc.base.security.entity.User;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.plugin.base.entity.CommonBillOperateHis;
import com.yh.saas.plugin.base.mapper.CommonBillOperateHisMapper;
import com.yh.saas.plugin.base.service.ICommonBillOperateHisService;

/**
 * <p>
 * 记录单据操作历史 服务实现类
 * </p>
 *
 * @author SongJin
 * @since 2020-01-03
 */
@Service
public class CommonBillOperateHisServiceImpl extends ServiceImpl<CommonBillOperateHisMapper, CommonBillOperateHis>
        implements ICommonBillOperateHisService {

    @SofaReference
    private ICommonStaffRoleService staffRoleService;

    @SofaReference
    private ICommonStaffService staffService;

    @SofaReference
    private ICommonRoleService roleService;

    @Autowired
    private IWorkflowHistoryService workflowHistoryService;

    @Override
    public String saveBillOperateHis(String billId, String billName, String makeUser, Date nowDate, String statusName,
                                     String statusNameEn, String reason) {
        String id = IdGenerator.generateUUID();
        // 插入操作历史
        CommonBillOperateHis billOperateHis = new CommonBillOperateHis();
        billOperateHis.setId(id);
        billOperateHis.setBillId(billId);
        billOperateHis.setBillName(billName);
        billOperateHis.setOperateUser(makeUser);
        if (nowDate == null) {
            nowDate = new Date();
        }
        billOperateHis.setOperateDate(nowDate);
        billOperateHis.setDealMsg(statusName);
        billOperateHis.setDealMsgEn(statusNameEn);
        billOperateHis.setVerifyRemark(reason);
        this.insert(billOperateHis);

        return id;
    }

    @Override
    public String saveBillOperateHis(String billId, String billName, String makeUser, Date nowDate, String statusName,
                                     String statusNameEn, String reason, String singPath) {
        String id = IdGenerator.generateUUID();
        // 插入操作历史
        CommonBillOperateHis billOperateHis = new CommonBillOperateHis();
        billOperateHis.setId(id);
        billOperateHis.setBillId(billId);
        billOperateHis.setBillName(billName);
        billOperateHis.setOperateUser(makeUser);
        if (nowDate == null) {
            nowDate = new Date();
        }
        billOperateHis.setOperateDate(nowDate);
        billOperateHis.setDealMsg(statusName);
        billOperateHis.setDealMsgEn(statusNameEn);
        billOperateHis.setVerifyRemark(reason);
        billOperateHis.setSignPath(singPath);
        this.insert(billOperateHis);

        return id;
    }

    @Override
    public String saveSystem(String billId, String billName, String makeUser, Date nowDate, String statusName,
                             String statusNameEn, String reason) {

        makeUser = "系统";
        String id = this.saveBillOperateHis(billId, billName, makeUser, nowDate, statusName, statusNameEn, reason);
        CommonBillOperateHis billOperateHis = new CommonBillOperateHis();
        billOperateHis.setId(id);
        billOperateHis.setCreateUserId("sysadmin");
        billOperateHis.setUpdateUserId("sysadmin");
        this.updateById(billOperateHis);

        return id;

    }

    @Override
    public String create(CommonBillOperateHis billOperateHis) {
        String id = IdGenerator.generateUUID();
        billOperateHis.setId(id);
        if (billOperateHis.getOperateDate() == null) {
            billOperateHis.setOperateDate(new Date());
        }
        this.insert(billOperateHis);
        return id;
    }

    /**
     * 取得当前登录人职务姓名
     *
     * @return
     */
    @Override
    public String getStaffAndName() {
        User currentUser = AuthSecurityUtils.getCurrentUserInfo();
        if (currentUser == null) {
            return "系统";
        }
        // 当前登录人主要角色
        CommonStaffRole staffRole = staffRoleService.getMajorRole(currentUser.getUserId());
        CommonStaff staff = staffService.getInfo(staffRole.getStaffId());
        CommonRole role = roleService.selectById(staffRole.getRoleId());
        return role.getRoleName() + " " + staff.getStaffName();
    }

    /**
     * 取得职务姓名
     *
     * @return
     */
    @Override
    public String getStaffAndName(String staffId) {
        if (StringUtils.isEmpty(staffId)) {
            return "系统";
        }
        // 当前登录人主要角色
        CommonStaffRole staffRole = staffRoleService.getMajorRole(staffId);
        CommonStaff staff = staffService.getInfo(staffRole.getStaffId());
        CommonRole role = roleService.selectById(staffRole.getRoleId());
        return role.getRoleName() + " " + staff.getStaffName();
    }

    @Override
    public List<CommonBillOperateHis> getBillOperateHis(String applId, String workflowId) {
        Wrapper<CommonBillOperateHis> wrapper = new EntityWrapper<>();
        wrapper.eq(CommonBillOperateHis.QueryFields.BILL_ID, applId);
        wrapper.orderBy(CommonBillOperateHis.QueryFields.OPERATE_DATE, false);

        List<CommonBillOperateHis> list = this.selectList(wrapper);
        if (StringUtils.isNotBlank(workflowId)) {
            List<WorkflowHistoricTask> historicTasks = this.workflowHistoryService.getInstanceHistories(workflowId,
                    applId);
            historicTasks
                    .forEach(historyTask -> list.add(CommonBillOperateHis.getInstance(historyTask.getOperatorName(),
                            historyTask.getEndTime(), historyTask.getApproved() ? "1" : "0", historyTask.getTaskName(),
                            historyTask.getTaskNameEn(), historyTask.getOperatorMajorRoleName(),
                            historyTask.getAuditMind())));
        }

        return list.stream().sorted(Comparator.comparing(CommonBillOperateHis::getOperateDate).reversed())
                .collect(Collectors.toList());
    }

}
