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

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Lists;
import com.winsea.svc.base.base.entity.CommonStaff;
import com.winsea.svc.base.base.entity.CommonStaffRole;
import com.winsea.svc.base.base.service.ICommonRoleResourceService;
import com.winsea.svc.base.base.service.ICommonStaffRoleService;
import com.winsea.svc.base.base.service.ICommonStaffService;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.winsea.svc.notice.entity.NoticeTaskInfo;
import com.winsea.svc.notice.entity.base.BaseNotice;
import com.winsea.svc.notice.service.INoticeService;
import com.winsea.svc.notice.service.INoticeTaskService;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.common.support.util.StringUtils;
import com.yh.saas.plugin.yiliangyiyun.constant.StatusEnum;
import com.yh.saas.plugin.yiliangyiyun.entity.*;
import com.yh.saas.plugin.yiliangyiyun.mapper.AcquisitionInfoMapper;
import com.yh.saas.plugin.yiliangyiyun.service.IAcquisitionInfoService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yh.saas.plugin.yiliangyiyun.service.IFocusAcquisitionInformationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 记录收购信息 服务实现类
 * </p>
 *
 * @author Gdc
 * @since 2021-11-26
 */
@Service
public class AcquisitionInfoServiceImpl extends ServiceImpl<AcquisitionInfoMapper, AcquisitionInfo> implements IAcquisitionInfoService {


    @Autowired
    private INoticeService noticeService;
    @Autowired
    private INoticeTaskService noticeTaskService;
    @Autowired
    private ICommonStaffService staffService;
    @Autowired
    private ICommonStaffRoleService commonStaffRoleService;
    @Autowired
    private ICommonRoleResourceService roleResourceService;
    @Autowired
    private IFocusAcquisitionInformationService focusAcquisitionInformationService;

    /**
     * 收购信息列表
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<AcquisitionInfo> selectAcquisitionPage(AcquisitionInfo acquisitionInfo){
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("searchKeyWord", acquisitionInfo.getSearchKeyWord());
        pageView.put("phone", acquisitionInfo.getLoginPhone());
        pageView.put("city", acquisitionInfo.getCity());
        // 查询收购总数
        List<AcquisitionInfo> acquisitionInfoList = baseMapper.getListByCondition(pageView);
        return acquisitionInfoList;
    }

    /**
     * 添加收购信息
     * @param  acquisitionInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addAcquisition(AcquisitionInfo acquisitionInfo){
        //判断id是否为空，空是新增
        if(StringUtils.isEmpty(acquisitionInfo.getId())){
            //新增主键id
            acquisitionInfo.setId(IdGenerator.generateUUID());
            acquisitionInfo.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
            acquisitionInfo.setStatusFlag(StatusEnum.GRAIN_REVIEWED.getFlag());
            acquisitionInfo.setStatus(StatusEnum.GRAIN_REVIEWED.getName());
            //操作主表数据
            this.insert(acquisitionInfo);
            // 先删除任务
            noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "ACQUISITION-SETTLEMENT-APPRPVE",
                    acquisitionInfo.getId(), null);
            tesk(acquisitionInfo);
        }else{
            //有id是修改
            acquisitionInfo.setStatusFlag(StatusEnum.GRAIN_REVIEWED.getFlag());
            acquisitionInfo.setStatus(StatusEnum.GRAIN_REVIEWED.getName());
            this.updateById(acquisitionInfo);
            // 先删除任务
            noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "ACQUISITION-SETTLEMENT-APPRPVE",
                    acquisitionInfo.getId(), null);
            tesk(acquisitionInfo);
        }
        return acquisitionInfo.getId();
    }

    /**
     * 关注
     * @param  acquisitionInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String follow(AcquisitionInfo acquisitionInfo){
        FocusAcquisitionInformation focusAcquisitionInformation = new FocusAcquisitionInformation();
        focusAcquisitionInformation.setId(IdGenerator.generateUUID());
        focusAcquisitionInformation.setInfoId(acquisitionInfo.getId());
        focusAcquisitionInformation.setWarehouseName(acquisitionInfo.getWarehouseName());
        focusAcquisitionInformation.setPhone(acquisitionInfo.getLoginPhone());
        focusAcquisitionInformationService.insert(focusAcquisitionInformation);
        return "OK";
    }

    /**
     * 取消关注
     * @param  acquisitionInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String followNot(AcquisitionInfo acquisitionInfo){
        focusAcquisitionInformationService.delete(new EntityWrapper<FocusAcquisitionInformation>()
            .eq("info_id",acquisitionInfo.getId())
            .eq("phone",acquisitionInfo.getLoginPhone()));
        return "Ok";
    }

    /**
     * 查看收购信息
     *
     * @param id
     * @return
     */
    @Override
    public AcquisitionInfo getAcquisition(String id) {
        //查看收购信息
        AcquisitionInfo acquisitionInfo = this.selectById(id);
        return acquisitionInfo;
    }

    /**
     * 收购业务查看
     *
     * @param acquisitionInfo
     * @return
     */
    @Override
    public AcquisitionInfo getInfo(AcquisitionInfo acquisitionInfo) {
        //根据用户id查看收购信息
        if(acquisitionInfo.getWarehouseName() == null){
            AcquisitionInfo acquisitionInfo1 = this.selectOne(new EntityWrapper<AcquisitionInfo>()
                    .eq("common_id",acquisitionInfo.getCommonId()));
            return acquisitionInfo1;
        }
        AcquisitionInfo acquisitionInfo1 = this.selectOne(new EntityWrapper<AcquisitionInfo>()
                .eq("warehouse_name",acquisitionInfo.getWarehouseName()));
        return acquisitionInfo1;
    }

    /**
     * 审核
     *
     * @param acquisitionInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String examine(AcquisitionInfo acquisitionInfo) {
        //查询收购信息
        AcquisitionInfo acquisitionInfo1 = this.selectById(acquisitionInfo.getId());
        if (acquisitionInfo1 != null) {
            //通过
            if (acquisitionInfo.getFlag() == 1) {
                acquisitionInfo1.setStatusFlag(StatusEnum.GRAIN_ADOPT.getFlag());
                acquisitionInfo1.setStatus(StatusEnum.GRAIN_ADOPT.getName());
            }
            //驳回
            else {
                acquisitionInfo1.setStatusFlag(StatusEnum.GRAIN_REJECT.getFlag());
                acquisitionInfo1.setStatus(StatusEnum.GRAIN_REJECT.getName());
            }
            //更改收购信息信息
            this.updateById(acquisitionInfo1);
            // 先删除任务
            noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "ACQUISITION-SETTLEMENT-APPRPVE",
                    acquisitionInfo.getId(), null);
            return "OK";
        }
        return "NG";
    }




    /**
     * 任务
     *
     * @param acquisitionInfo
     */
    private void tesk(AcquisitionInfo acquisitionInfo) {
        List<String> roleIdList = new ArrayList<>();
        roleIdList = roleResourceService.getBindRoleIdsByResourceIds(AuthSecurityUtils.getCurrentUserInfo().getCompId(),
                Lists.newArrayList("acquisitionInfor-Delete"));
        // 先删除任务
        noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "ACQUISITION-SETTLEMENT-APPRPVE",
                acquisitionInfo.getId(), null);
        String staffName = "XXX";
        CommonStaff commitUserInfo = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
        if (commitUserInfo != null) {
            staffName = commitUserInfo.getMajorRole() != null
                    ? commitUserInfo.getMajorRole().getRoleName() + " " + commitUserInfo.getStaffName()
                    : commitUserInfo.getStaffName();
        }
        List<CommonStaffRole> commonStaffRoles = commonStaffRoleService.findStaff(roleIdList);
        List<String> staffIds = commonStaffRoles.stream().map(CommonStaffRole::getStaffId).collect(Collectors.toList());
        String taskContent = "";
        // 向下一步操作人发送任务通知
        taskContent =  staffName + "提交的"+acquisitionInfo.getWarehouseName()+"收购信息等待审核";
        NoticeTaskInfo taskInfo = new NoticeTaskInfo();
        taskInfo.setCompId(commitUserInfo.getCompId());
        taskInfo.setAcceptType(BaseNotice.AcceptStatus.STAFF);
        taskInfo.setBusinessId(acquisitionInfo.getId());
        taskInfo.setBusinessType("ACQ");
        taskInfo.setMessageContent(taskContent);
        taskInfo.setBusinessCode("ACQUISITION-SETTLEMENT-APPRPVE");
//            taskInfo.setNoticeTaskStatus(NoticeTaskInfo.NoticeTaskStatus.RETURN);
        noticeTaskService.createNoticeTask(staffIds,
                null, taskInfo);

    }


}
