package com.ruoyi.system.service.impl.project;

import java.math.BigDecimal;
import java.util.*;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.project.*;
import com.ruoyi.system.domain.vo.BmDeptPlanVo;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.mapper.project.*;
import com.ruoyi.system.service.project.IBmProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.ruoyi.common.constant.Constants.*;


/**
 * 项目(添加线索)Service业务层处理
 *
 * @author bm
 * @date 2021-03-03
 */
@Service
public class BmProjectServiceImpl implements IBmProjectService {
    @Autowired
    private BmProjectMapper bmProjectMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private BmProjectInfoMapper bmProjectInfoMapper;

    @Autowired
    private BmProjectPersionMapper bmProjectPersionMapper;

    @Autowired
    private BmProjectInvestorMapper bmProjectInvestorMapper;

    @Autowired
    private BmCompanyShareholderMapper bmCompanyShareholderMapper;

    @Autowired
    private BmProjectOrderinfoMapper bmProjectOrderinfoMapper;

    @Autowired
    private BmProjectConstructionMapper bmProjectConstructionMapper;

    @Autowired
    private BmConstructionRateMapper bmConstructionRateMapper;

    @Autowired
    private BmConstructionEqMapper bmConstructionEqMapper;

    @Autowired
    private BmConstructionPayMapper bmConstructionPayMapper;

    @Autowired
    private BmConstructionPayInfoMapper bmConstructionPayInfoMapper;

    @Autowired
    private BmProjectProductMapper bmProjectProductMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;


    /**
     * 查询项目(添加线索)
     *
     * @param id 项目(添加线索)ID
     * @return 项目(添加线索)
     */
    @Override
    public BmProject selectBmProjectById(Long id) {
        BmProject bmProject = bmProjectMapper.selectBmProjectById(id);
        List<SysDictData> dictDataList = sysDictDataMapper.selectDictDataByType("project_industry");
        for (SysDictData sysDictData : dictDataList) {
            if (sysDictData.getDictValue().equals(bmProject.getIndustry())){
                bmProject.setIndustry(sysDictData.getDictLabel());
                break;
            }
        }
        return bmProject;
    }

    /**
     * 查询项目(添加线索)列表
     *
     * @param bmProject 项目(添加线索)
     * @return 项目(添加线索)
     */
    @Override
    public List<BmProject> selectBmProjectList(BmProject bmProject) {
        return bmProjectMapper.selectBmProjectList(bmProject);
    }

    /**
     * 新增项目(添加线索)
     *
     * @param bmProject 项目(添加线索)
     * @return 结果
     */
    @Override
    public AjaxResult insertBmProject(BmProject bmProject) {
        bmProject.setCreateTime(DateUtils.getNowDate());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        Long deptId = user.getDeptId();
        bmProject.setDeptId(deptId);
        bmProject.setCreateBy(user.getUserName());
        //新增线索,默认值1
        bmProject.setProjectStatus(1L);
        bmProjectMapper.insertBmProject(bmProject);
        String isBackbussiness = bmProject.getIsBackbussiness();
        if (StringUtils.isBlank(isBackbussiness)) {
            bmProject.setIsBackbussiness("N");
        }
        return AjaxResult.success(bmProject);
    }

    /**
     * 修改项目(添加线索)
     *
     * @param bmProject 项目(添加线索)
     * @return 结果
     */
    @Override
    public int updateBmProject(BmProject bmProject) {
        bmProject.setUpdateTime(DateUtils.getNowDate());
        bmProject.setUpdateBy(SecurityUtils.getUsername());
        return bmProjectMapper.updateBmProject(bmProject);
    }

    /**
     * 批量删除项目(添加线索)
     *
     * @param ids 需要删除的项目(添加线索)ID
     * @return 结果
     */
    @Override
    public int deleteBmProjectByIds(Long[] ids) {
        return bmProjectMapper.deleteBmProjectByIds(ids);
    }

    /**
     * 删除项目(添加线索)信息
     *
     * @param id 项目(添加线索)ID
     * @return 结果
     */
    @Override
    public int deleteBmProjectById(Long id) {
        return bmProjectMapper.deleteBmProjectById(id);
    }

    /**
     * 审核项目状态(审核/提交/驳回项目)
     *
     * @param bmProjectStatus 审核请求对象
     * @return
     */
    @Override
    public AjaxResult examine(BmProjectStatus bmProjectStatus) {
        Long projectId = bmProjectStatus.getBmProjectId();
        if (projectId == null) {
            return AjaxResult.error("项目id为NULL");
        }
        Long code = bmProjectStatus.getCode();
        synchronized (this) {
            BmProject bmProject = bmProjectMapper.selectBmProjectById(projectId);
            //获取当前状态
            Long projectStatus = bmProject.getProjectStatus();
            //如果当前进度是1:新增线索,不能继续驳回
            if (projectStatus.equals(EXAMINE_COMMIT) && code.equals(EXAMINE_BACK)) {
                return AjaxResult.error("无法继续驳回");
            }
            if ((projectStatus & 1) == 0 && code.equals(EXAMINE_COMMIT)) {
                //是偶数并且还是提交审核
                return AjaxResult.error("正在等待审核");
            } else if ((projectStatus & 1) == 1 && code.equals(EXAMINE_BACK)) {
                //是奇数并且还是驳回审核
                return AjaxResult.error("当前已审核通过");
            } else if ((projectStatus & 1) == 1 && code.equals(EXAMINE_PASS)) {
                //是奇数并且还是审核通过
                return AjaxResult.error("当前已审核通过");
            }

            //如果是提交审核判断相应信息是否填写
            if (code.equals(EXAMINE_COMMIT)) {
                if (projectStatus.equals(EXAMINE_COMMIT)) {
                    //当前是新增线索,然后提交线索,需要判断是否有对应的bm_project_info中id和bm_project_persion中id或者bm_project_investor中id
                    BmProjectInfo bmProjectInfo = bmProjectInfoMapper.selectBmProjectInfoById(projectId);
                    if (bmProjectInfo != null) {
                        BmProjectInvestor bmProjectInvestor = bmProjectInvestorMapper.selectBmProjectInvestorByProjectId(projectId);
                        BmProjectPersion bmProjectPersion = bmProjectPersionMapper.selectBmProjectPersionByProjectId(projectId);
                        if (bmProjectInvestor == null && bmProjectPersion == null) {
                            return AjaxResult.error("信息不全,请补全后重新提交");
                        }
                    } else {
                        return AjaxResult.error("信息不全,请补全后重新提交");
                    }
                }
                if (projectStatus.equals(EXAMINE_PASS)) {
                    //提交签约审核申请,判断bm_company_shareholder和bm_project_orderinfo
                    BmProjectOrderinfo bmProjectOrderinfo = bmProjectOrderinfoMapper.selectBmProjectOrderinfoById(projectId);
                    if (bmProjectOrderinfo != null) {
                        BmCompanyShareholder bmCompanyShareholder = bmCompanyShareholderMapper.selectBmCompanyShareholderByProjectId(projectId);
                        if (bmCompanyShareholder == null) {
                            return AjaxResult.error("信息不全,请补全后重新提交");
                        }
                    } else {
                        return AjaxResult.error("信息不全,请补全后重新提交");
                    }
                }

                if (projectStatus.equals(EXAMINE_FIVE)) {
                    //提交在建信息审核申请
                    //判断bm_project_construction/bm_construction_rate/bm_construction_eq/bm_construction_pay/bm_construction_payinfo
                    BmProjectConstruction bmProjectConstruction = bmProjectConstructionMapper.selectBmProjectConstructionById(projectId);
                    BmConstructionRate bmConstructionRate = bmConstructionRateMapper.selectBmConstructionRateByProjectId(projectId);
                    BmConstructionEq bmConstructionEq = bmConstructionEqMapper.selectBmConstructionEqByProjectId(projectId);
                    BmConstructionPay bmConstructionPay = bmConstructionPayMapper.selectBmConstructionPayByProjectId(projectId);
                    BmConstructionPayInfo bmConstructionPayInfo = bmConstructionPayInfoMapper.selectBmConstructionPayInfoById(projectId);
                    if (bmProjectConstruction == null || bmConstructionRate == null || bmConstructionEq == null || bmConstructionPay == null || bmConstructionPayInfo == null) {
                        return AjaxResult.error("信息不全,请补全后重新提交");
                    }
                }

                if (projectStatus.equals(EXAMINE_SEVEN)){
                    //提交投产审核判断bm_project_product
                    BmProjectProduct bmProjectProduct = bmProjectProductMapper.selectBmProjectProductById(projectId);
                    if (bmProjectProduct == null){
                        return AjaxResult.error("信息不全,请补全后重新提交");
                    }
                }
            }

            //查询项目状态最多有多少个
            List<SysDictData> dictDataList = dictDataMapper.selectDictDataByType("project_status");

            if (dictDataList.size() > 0 && projectStatus == dictDataList.size()) {
                return AjaxResult.error("当前项目已结束,无法继续操作");
            }
            //判断是否是提交审核/通过审核
            projectStatus = !code.equals(EXAMINE_BACK) ? projectStatus + EXAMINE_COMMIT : projectStatus - EXAMINE_COMMIT;
            if (projectStatus < EXAMINE_COMMIT) {
                projectStatus = EXAMINE_COMMIT;
            }
            BmProject bmProjectNew = new BmProject();
            bmProjectNew.setId(projectId);
            bmProjectNew.setProjectStatus(projectStatus);
            if (dictDataList.size() > 0) {
                for (SysDictData sysDictData : dictDataList) {
                    if (sysDictData.getDictValue().equals(projectStatus.toString())) {
                        StringBuilder sb = new StringBuilder(DateUtils.getTime());
                        sb.append("<br>").append("[");
                        if (code.equals(EXAMINE_BACK)){
                            //如果是驳回,保存驳回建议
                            String remark = bmProjectStatus.getRemark();
                            if (StringUtils.isNotBlank(remark)){
                                sb.append(remark);
                            }
                        }else {
                            sb.append(sysDictData.getDictLabel());
                        }
                        sb.append("]");
                        bmProjectNew.setRemark(sb.toString());
                        break;
                    }
                }
            }
            bmProjectMapper.updateBmProject(bmProjectNew);
        }
        return AjaxResult.success();
    }

    /**
     * 首页查询待审核列表
     *
     * @param bmProject
     * @return
     */
    @Override
    public List<BmProject> selectToBeReviewedList(BmProject bmProject) {
        List<BmProject> bmProjects = bmProjectMapper.selectToBeReviewedList(bmProject);
        return bmProjects;
    }

    /**
     * 统计分析公共查询列表
     *
     * @param ids
     * @return
     */
    @Override
    public List<BmProject> selectStatisticsList(Long[] ids) {
        List<BmProject> bmProjects = bmProjectMapper.selectStatisticsList(ids);
        return bmProjects;
    }

    /**
     * 统计分析-在谈线索-柱状图
     *
     * @param year
     * @return
     */
    @Override
    public Map<String, Object> selectProjectEharts(String year) {
        List<BmDeptPlanVo> bmDeptPlanVos = bmProjectMapper.selectProjectEharts(year);
        Map<String, Object> map = new HashMap<>(2);
        List<String> deptName = new ArrayList<>();
        List<Integer> successMission = new ArrayList<>();
        if (bmDeptPlanVos.size() > 0) {
            for (BmDeptPlanVo bmDeptPlanVo : bmDeptPlanVos) {
                deptName.add(bmDeptPlanVo.getDeptName());
                successMission.add(bmDeptPlanVo.getSuccessMission());
            }
        }
        map.put("x", deptName);
        map.put("y", successMission);
        return map;
    }

    /**
     * 统计分析-签约项目-柱状图
     *
     * @param year
     * @return
     */
    @Override
    public Map<String, Object> selectProjectContractEharts(String year) {
        List<BmDeptPlanVo> bmDeptPlanVos = bmProjectMapper.selectProjectContractEharts(year);
        Map<String, Object> map = new HashMap<>(3);
        List<String> deptName = new ArrayList<>();
        List<Integer> successMission = new ArrayList<>();
        List<BigDecimal> totAmt = new ArrayList<>();
        if (bmDeptPlanVos.size() > 0) {
            for (BmDeptPlanVo bmDeptPlanVo : bmDeptPlanVos) {
                deptName.add(bmDeptPlanVo.getDeptName());
                successMission.add(bmDeptPlanVo.getSuccessMission());
                totAmt.add(bmDeptPlanVo.getTotAmt());
            }
        }
        map.put("x", deptName);
        map.put("y1", successMission);
        map.put("y2", totAmt);
        return map;
    }
}
