package com.bonus.material.basic.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import com.bonus.common.biz.constant.MaterialConstants;
import com.bonus.common.biz.enums.TmTaskTypeEnum;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.common.biz.domain.BmFileInfo;
import com.bonus.material.basic.mapper.BmFileInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bonus.material.basic.mapper.BmAgreementInfoMapper;
import com.bonus.material.basic.domain.BmAgreementInfo;
import com.bonus.material.basic.service.IBmAgreementInfoService;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;

/**
 * 协议管理Service业务层处理
 * 
 * @author xsheng
 * @date 2024-09-26
 */
@Service
public class BmAgreementInfoServiceImpl implements IBmAgreementInfoService 
{
    @Autowired
    private BmAgreementInfoMapper bmAgreementInfoMapper;

    @Resource
    private BmFileInfoMapper bmFileInfoMapper;

    /**
     * 查询协议管理
     * 
     * @param agreementId 协议管理主键
     * @return 协议管理
     */
    @Override
    public BmAgreementInfo selectBmAgreementInfoByAgreementId(Long agreementId)
    {
        BmAgreementInfo bmAgreementInfo = bmAgreementInfoMapper.selectBmAgreementInfoByAgreementId(agreementId);
        if(bmAgreementInfo.getBranchProIdsStr()!= null && !bmAgreementInfo.getBranchProIdsStr().equals("")){
                String[] strArray = bmAgreementInfo.getBranchProIdsStr().split(",");
                String branchProIdsStr = "";
                int[] intArray = new int[strArray.length];
                for (int i = 0; i < strArray.length; i++) {
                    String dictLabel = bmAgreementInfoMapper.getDictLabel(Integer.parseInt(strArray[i]));
                    if (i != strArray.length - 1) {
                        branchProIdsStr += dictLabel + ",";
                    }else {
                        branchProIdsStr +=dictLabel;
                    }
                    intArray[i] = Integer.parseInt(strArray[i]);
                }
                bmAgreementInfo.setBranchProIds(intArray);
                bmAgreementInfo.setBranchProIdsStr(branchProIdsStr);

        }
        if (Objects.nonNull(bmAgreementInfo)) {
            BmFileInfo bmFileInfo = new BmFileInfo();
            bmFileInfo.setModelId(bmAgreementInfo.getAgreementId());
            bmFileInfo.setTaskType(TmTaskTypeEnum.TM_TASK_AGREEMENT_MANAGEMENT.getTaskTypeId());
            List<BmFileInfo> fileInfos = bmFileInfoMapper.selectBmFileInfoList(bmFileInfo);
            bmAgreementInfo.setBmFileInfos(fileInfos);
        }
        return bmAgreementInfo;
    }

    /**
     * 查询协议管理列表
     * 
     * @param bmAgreementInfo 协议管理
     * @return 协议管理
     */
    @Override
    public List<BmAgreementInfo> selectBmAgreementInfoList(BmAgreementInfo bmAgreementInfo)
    {
        List<BmAgreementInfo> bmAgreementInfoList = new ArrayList<>();
        bmAgreementInfoList = bmAgreementInfoMapper.selectBmAgreementInfoList(bmAgreementInfo);
        if(!CollectionUtils.isEmpty(bmAgreementInfoList)){
            bmAgreementInfoList.forEach(bmAgreementInfo1 -> {
                if(bmAgreementInfo1.getBranchProIdsStr()!= null &&!bmAgreementInfo1.getBranchProIdsStr().equals("")){
                    String[] strArray = bmAgreementInfo1.getBranchProIdsStr().split(",");
                    String branchProIdsStr = "";
                    for (int i = 0; i < strArray.length; i++) {
                        String dictLabel = bmAgreementInfoMapper.getDictLabel(Integer.parseInt(strArray[i]));
                        if (i != strArray.length - 1) {
                            branchProIdsStr += dictLabel + ",";
                        }else {
                            branchProIdsStr +=dictLabel;
                        }
                    }
                    bmAgreementInfo1.setBranchProIdsStr(branchProIdsStr);
                }
            });
        }
        return bmAgreementInfoList;
    }

    /**
     * 新增协议管理
     * 
     * @param bmAgreementInfo 协议管理
     * @return 结果
     */
    @Override
    public AjaxResult insertBmAgreementInfo(BmAgreementInfo bmAgreementInfo)
    {
        List<BmAgreementInfo> list = bmAgreementInfoMapper.selectBmAgreementInfoList(bmAgreementInfo);
        if (!CollectionUtils.isEmpty(list) && list.size() > 0) {
            return AjaxResult.error("已存在重复数据");
        }
        try {
            bmAgreementInfo.setCreateTime(DateUtils.getNowDate());
            bmAgreementInfo.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
            bmAgreementInfo.setSignTime(DateUtils.getNowDate());
            bmAgreementInfo.setAgreementCode(getAgreementCode());
            if(bmAgreementInfo.getBranchProIds() != null){
                String branchProIdsStr = "";
                int[] split = bmAgreementInfo.getBranchProIds();
                for (int i = 0; i < split.length; i++) {
//                    String dictLabel = bmAgreementInfoMapper.getDictLabel(split[i]);
                    if (i != split.length - 1) {
                        branchProIdsStr += split[i] + ",";
                    }else {
                        branchProIdsStr += split[i];
                    }
                }
                bmAgreementInfo.setBranchProIdsStr(branchProIdsStr);
            }
            int count = bmAgreementInfoMapper.insertBmAgreementInfo(bmAgreementInfo);
            if (count > 0) {
                if (CollectionUtils.isEmpty(bmAgreementInfo.getBmFileInfos())) {
                    return AjaxResult.success("新增任务成功,无营业执照附件");
                }
                AtomicBoolean addFileInfoResult = new AtomicBoolean(false);
                bmAgreementInfo.getBmFileInfos().forEach(bmFileInfo -> {
                    bmFileInfo.setModelId(bmAgreementInfo.getAgreementId());
                    bmFileInfo.setCreateTime(DateUtils.getNowDate());
                    addFileInfoResult.set(bmFileInfoMapper.insertBmFileInfo(bmFileInfo) > 0);
                });
                return addFileInfoResult.get() ? AjaxResult.success("新增任务成功") : AjaxResult.error("新增任务失败,附件表插入0条");
            } else {
                return AjaxResult.error("新建任务失败,插入0条");
            }
        } catch (Exception e) {
            throw new ServiceException("错误信息描述");
        }
    }

    private String getAgreementCode() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        String result = format.replace("-", "");
        int num = bmAgreementInfoMapper.selectNumByMonth(nowDate);
        return MaterialConstants.AGREEMENT_PREFIX + result + String.format("-%03d", num + 1);
    }

    /**
     * 修改协议管理
     * 
     * @param bmAgreementInfo 协议管理
     * @return 结果
     */
    @Override
    public AjaxResult updateBmAgreementInfo(BmAgreementInfo bmAgreementInfo)
    {
        // 根据unitId和projectId判断，修改的单位和工程是否已经关联协议
        BmAgreementInfo agreementInfo = new BmAgreementInfo();
        agreementInfo.setUnitId(bmAgreementInfo.getUnitId());
        agreementInfo.setProjectId(bmAgreementInfo.getProjectId());
        List<BmAgreementInfo> list = bmAgreementInfoMapper.selectBmAgreementInfoList(agreementInfo);
        if (!CollectionUtils.isEmpty(list)) {
            BmAgreementInfo info = list.get(0);
            if (info != null && info.getAgreementId() != null && !info.getAgreementId().equals(bmAgreementInfo.getAgreementId())) {
                return AjaxResult.error("该单位和工程已关联协议，请勿重复创建！");
            }
        }
        bmAgreementInfo.setUpdateTime(DateUtils.getNowDate());
        if(bmAgreementInfo.getBranchProIds() != null){
            String branchProIdsStr = "";
            int[] split = bmAgreementInfo.getBranchProIds();
            for (int i = 0; i < split.length; i++) {
//                    String dictLabel = bmAgreementInfoMapper.getDictLabel(split[i]);
                if (i != split.length - 1) {
                    branchProIdsStr += split[i] + ",";
                }else {
                    branchProIdsStr += split[i];
                }
            }
            bmAgreementInfo.setBranchProIdsStr(branchProIdsStr);
        }else if(bmAgreementInfo.getBranchProIds() == null || bmAgreementInfo.getBranchProIds().length == 0){
            bmAgreementInfo.setBranchProIdsStr(null);
        }
        int count = bmAgreementInfoMapper.updateBmAgreementInfo(bmAgreementInfo);
        if (count > 0) {
            BmFileInfo bmFileInfoToDelete = new BmFileInfo();
            bmFileInfoToDelete.setModelId(bmAgreementInfo.getAgreementId());
            bmFileInfoToDelete.setTaskType(TmTaskTypeEnum.TM_TASK_AGREEMENT_MANAGEMENT.getTaskTypeId());
            bmFileInfoMapper.deleteBmFileInfoByBizInfo(bmFileInfoToDelete);
            if (CollectionUtils.isEmpty(bmAgreementInfo.getBmFileInfos())) {
                return AjaxResult.success("修改任务成功,无营业执照附件");
            }
            AtomicBoolean addFileInfoResult = new AtomicBoolean(false);
            bmAgreementInfo.getBmFileInfos().forEach(bmFileInfo -> {
                bmFileInfo.setModelId(bmAgreementInfo.getAgreementId());
                bmFileInfo.setCreateTime(DateUtils.getNowDate());
                addFileInfoResult.set(bmFileInfoMapper.insertBmFileInfo(bmFileInfo) > 0);
            });
            return addFileInfoResult.get() ? AjaxResult.success("修改任务成功") : AjaxResult.error("修改任务失败,附件表插入0条");
        } else {
            AjaxResult.error("无协议被修改");
        }
        return AjaxResult.success("修改协议成功");
    }

    /**
     * 批量删除协议管理
     * 
     * @param agreementIds 需要删除的协议管理主键
     * @return 结果
     */
    @Override
    public int deleteBmAgreementInfoByAgreementIds(Long[] agreementIds)
    {
        return bmAgreementInfoMapper.deleteBmAgreementInfoByAgreementIds(agreementIds);
    }

    /**
     * 删除协议管理信息
     * 
     * @param agreementId 协议管理主键
     * @return 结果
     */
    @Override
    public int deleteBmAgreementInfoByAgreementId(Long agreementId)
    {
        //查询该协议是否存在领料任务，有的话不能删除
        int res = bmAgreementInfoMapper.selectByagreementId(agreementId);
        if (res > 0) {
            throw new ServiceException("该协议存在领料任务，不能删除");
        } else {
            return bmAgreementInfoMapper.deleteBmAgreementInfoByAgreementId(agreementId);
        }
    }
}
