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

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


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.google.gson.JsonObject;
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.SendSmsUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.system.domain.TextMessageLog;
import com.ruoyi.system.domain.project.*;
import com.ruoyi.system.domain.vo.BmDeptPlanVo;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.TextMessageLogMapper;

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 sun.security.provider.MD4;
import sun.security.provider.MD5;

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;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TextMessageLogMapper textMessageLogMapper;

    /**
     * 企查查
     */
    private static final String KEY = "e50f4b2011ea41a3ad489f0476160041";
    private static final String SECRET_KEY = "BD8D23FCD36CDEE7E0B25DAB28588163";

    /**
     * 查询项目(添加线索)
     *
     * @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("当前已审核通过");
            }else if ((projectStatus & 1) == 0 && code.equals(EXAMINE_FOUR)) {
                //是偶数并且撤回审核
                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){
                        return AjaxResult.error("信息不全,请补全后重新提交");
                    }
                    //非必填
/*                    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) {
                        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 & 1) == 1 ? projectStatus + EXAMINE_COMMIT : projectStatus - EXAMINE_COMMIT;

            //判断如果是撤销审核需要在减一
            if (code.equals(EXAMINE_FOUR)){
                projectStatus = 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("驳回原因:").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,Long deptId) {
        List<BmProject> bmProjects = bmProjectMapper.selectStatisticsList(deptId,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;
    }

    /**
     * 每周三下午14点给未添加线索信息的用户发送短信
     */
    @Override
    public void selectBmProjectInProjectStatus() {
        List<BmProject> bmProjects = bmProjectMapper.selectBmProjectInProjectStatus();
        String accessKeyId = "LTAI5tNA2fcBJH6EWRH6Pxr6";
        String accessKeySecret = "5WdaPEOvC3u9LC7pwy2DQ9pgmJvgUr";
        String signName = "潜山市招商中心";
        String templateCode = "SMS_220545214";
        String message = null;
        if (bmProjects.size() > 0){
            for (BmProject bmProject : bmProjects) {
                Long deptId = bmProject.getDeptId();
                List<SysUser> sysUsers = sysUserMapper.selectUserByDeptId(deptId);
                if (sysUsers != null && sysUsers.size() > 0){
                    for (SysUser sysUser : sysUsers) {
                         String phoneNumber = sysUser.getPhonenumber();
                         String userName = sysUser.getUserName();
                        if (StringUtils.isNotBlank(phoneNumber)){
                            try {
                                SendSmsResponse sendSmsResponse = SendSmsUtils.sendSms(phoneNumber, userName, accessKeyId, accessKeySecret, signName, templateCode);
                                message = sendSmsResponse.getMessage();
                            } catch (ClientException e) {
                                e.printStackTrace();
                            }finally {
                                TextMessageLog textMessageLog = new TextMessageLog();
                                textMessageLog.setPhoneNum(phoneNumber);
                                textMessageLog.setNickName(userName);
                                textMessageLog.setCreateTime(DateUtils.getNowDate());
                                textMessageLog.setContent(userName + " 您好，您在招商引资管理平台有未完善的项目线索信息，请及时登陆招商引资管理平台在项目管理里完善项目线索信息。");
                                textMessageLog.setCreateBy("admin");
                                textMessageLog.setStatus(message);
                                textMessageLogMapper.insertTextMessageLog(textMessageLog);
                            }
                        }else {
                            if (!"null".equals(userName)) {
                                TextMessageLog textMessageLog = new TextMessageLog();
                                textMessageLog.setNickName(userName);
                                textMessageLog.setCreateTime(DateUtils.getNowDate());
                                textMessageLog.setContent(userName + " 您好，您在招商引资管理平台有未完善的项目线索信息，请及时登陆招商引资管理平台在项目管理里完善项目线索信息。");
                                textMessageLog.setCreateBy("admin");
                                textMessageLog.setStatus("该用户没有手机号");
                                textMessageLogMapper.insertTextMessageLog(textMessageLog);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 首页-统计数字(只根据当前登录人的部门)
     * @param bmProject
     * @return
     */
    @Override
    public AjaxResult indexInfo(BmProject bmProject) {
        int zt = 0;
        int qy = 0;
        int zj = 0;
        int tc = 0;
        List<BmProject> bmProjects = bmProjectMapper.indexInfo(bmProject);
        if (bmProjects.size()>0){
            for (BmProject project : bmProjects) {
                Long projectStatus = project.getProjectStatus();
                if (projectStatus == 1 || projectStatus == 2 || projectStatus == 3){
                    zt = zt + Integer.parseInt(project.getNum());
                }
                if (projectStatus == 5){
                    qy = qy + Integer.parseInt(project.getNum());
                }
                if (projectStatus == 7){
                    zj = zj + Integer.parseInt(project.getNum());
                }
                if (projectStatus == 9){
                    tc = tc + Integer.parseInt(project.getNum());
                }
            }
        }
        Map<String,Object> map  = new HashMap<>();
        map.put("zt",zt);
        map.put("qy",qy);
        map.put("zj",zj);
        map.put("tc",tc);
        return AjaxResult.success(map);
    }

    /**
     * 通过企查查,查询企业信息
     * @param searchKey
     * @return
     *
     *  {
     *   "Paging": {
     *     "PageSize": 1,
     *     "PageIndex": 1,
     *     "TotalRecords": 19
     *   },
     *   "Result": [
     *     {
     *       "KeyNo": "f625a5b661058ba5082ca508f99ffe1b",
     *       "Name": "企查查科技有限公司",
     *       "CreditCode": "91320594088140947F",
     *       "StartDate": "2014-03-12",
     *       "OperName": "陈德强",
     *       "Status": "存续",
     *       "No": "320594000299470"
     *     }
     *   ],
     *   "Status": "200",
     *   "Message": "【有效请求】查询成功",
     *   "OrderNumber": "FUZZYSEARCH2021070316421997519956"
     * }
     * key:e50f4b2011ea41a3ad489f0476160041
     * SecretKey:BD8D23FCD36CDEE7E0B25DAB28588163
     */
    @Override
    public AjaxResult qichachaSearch(String searchKey) {
        //Headers头信息
        Map<String,String> map = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        String unix = DateUtils.getUnix();
        map.put("Timespan", unix);
        sb.append(KEY).append(unix).append(SECRET_KEY);
        map.put("Token", Md5Utils.hash(sb.toString()).toUpperCase());
        StringBuilder sbd = new StringBuilder();
        sbd.append("key=").append(KEY).append("&").append("searchKey=").append(searchKey);
        String s = HttpUtils.sendGetMap("http://api.qichacha.com/FuzzySearch/GetList",sbd.toString(),map);
        JSONObject result = JSONObject.parseObject(s);
        JSONArray resultOut = result.getJSONArray("Result");
        if (resultOut != null){
            return AjaxResult.success(resultOut);
        }
/*       List<Map<String,String>> list =  new ArrayList<>();
        Map<String,String> mapHash  = new HashMap<>();
        mapHash.put("KeyNo","dca20a8e527f6a9e0810fa27e62d6aeb");
        mapHash.put("StartDate","2018-07-11");
        mapHash.put("Status","存续");
        mapHash.put("CreditCode","91340100MA2RWTYA7C");
        mapHash.put("No","");
        mapHash.put("OperName","江瑾");
        mapHash.put("Name","安徽博曼网络科技有限公司");
        list.add(mapHash);
        Map<String,String> mapHash2  = new HashMap<>();
        mapHash2.put("KeyNo","499ede50895e9be65d93c88dc1c67143");
        mapHash2.put("StartDate","2018-07-11");
        mapHash2.put("Status","存续");
        mapHash2.put("CreditCode","91340124MA2UYAET7U");
        mapHash2.put("No","");
        mapHash2.put("OperName","谈家强");
        mapHash2.put("Name","安徽博曼装饰工程有限公司");
        list.add(mapHash2);*/
        return AjaxResult.success(new ArrayList<>());
    }
}
