package com.ruoyi.framework.web.service.projectV2;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.jPush.JPushToolUtil;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.domain.projectV2.ZsyzFj;
import com.ruoyi.system.domain.projectV2.ZsyzLcjl;
import com.ruoyi.system.domain.projectV2.ZsyzSbbzb;
import com.ruoyi.system.domain.projectV2.common.SendSmsConfig;
import com.ruoyi.system.mapper.projectV2.*;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.projectV2.IZsyzSbbzbService;
import com.ruoyi.system.service.projectV2.common.ISendSmsConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

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

/**
 * 招商引资_申报_首谈信息_主Service业务层处理
 *
 * @author boman
 * @date 2023-02-23
 */
@Service
public class ZsyzSbbzbServiceImpl implements IZsyzSbbzbService {
    @Autowired
    private ZsyzSbbzbMapper zsyzSbbzbMapper;

    @Autowired
    private ZsyzFjMapper zsyzFjMapper;

    @Autowired
    private XmProjectPersionMapper xmProjectPersionMapper;

    @Autowired
    private XmProjectInvestorMapper xmProjectInvestorMapper;

    @Autowired
    private ZsyzLcjlMapper zsyzLcjlMapper;

    @Autowired
    private ISendSmsConfigService sendSmsConfigService;
    @Autowired
    private ISysUserService sysUserService;

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

    /**
     * 查询招商引资_申报_首谈信息_主
     *
     * @param id 招商引资_申报_首谈信息_主ID
     * @return 招商引资_申报_首谈信息_主
     */
    @Override
    @Transactional
    public ZsyzSbbzb selectZsyzSbbzbById(Long id) {
        ZsyzSbbzb zsyzSbbzb = zsyzSbbzbMapper.selectZsyzSbbzbById(id);
        if (zsyzSbbzb != null){
            ZsyzFj zsyzFj = new ZsyzFj();
            zsyzFj.setSourceId(zsyzSbbzb.getId());
            zsyzFj.setType(ONE);
            List<ZsyzFj> zsyzFjList = zsyzFjMapper.selectZsyzFjList(zsyzFj);
            if (zsyzFjList != null && zsyzFjList.size() > 0) {
                zsyzSbbzb.setZsyzFjList(zsyzFjList);
            }
        }
        return zsyzSbbzb;
    }

    /**
     * 查询招商引资_申报_首谈信息_主列表
     *
     * @param zsyzSbbzb 招商引资_申报_首谈信息_主
     * @return 招商引资_申报_首谈信息_主
     */
    @Override
    @DataScope(deptAlias = "s",permission = "s.cjd_id")
    public List<ZsyzSbbzb> selectZsyzSbbzbList(ZsyzSbbzb zsyzSbbzb) {
        List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
        List<ZsyzSbbzb> zsyzSbbzbs = new ArrayList<>();
        boolean flag = true;
        if (roles != null){
            for (SysRole role : roles) {
                String roleKey = role.getRoleKey();
                if (YSBM.equals(roleKey)){
                    //如果是要素部门角色只能看到分派给要素部门的和自己新增的线索
                    flag = false;
                    break;
                }
            }
        }
        if (flag){
            zsyzSbbzbs = zsyzSbbzbMapper.selectZsyzSbbzbList(zsyzSbbzb);
        }else {
            //如果是要素部门角色只能看到分派给要素部门的和自己新增的线索
            zsyzSbbzb.setDeptId(SecurityUtils.getDeptId());
            zsyzSbbzbs = zsyzSbbzbMapper.selectZsyzSbbzbListByZp(zsyzSbbzb);
        }
        return zsyzSbbzbs;
    }

    /**
     * 查询招商引资_申报_首谈信息_主列表_招商引资单位单独列表
     */
    @Override
    public List<ZsyzSbbzb> selectZsyzSbbzbListYz(ZsyzSbbzb zsyzSbbzb) {
        zsyzSbbzb.setDeptId(SecurityUtils.getDeptId());
        List<ZsyzSbbzb> zsyzSbbzbs = zsyzSbbzbMapper.selectZsyzSbbzbListYz(zsyzSbbzb);
        return zsyzSbbzbs;
    }

    /**
     * 新增招商引资_申报_首谈信息_主
     *
     * @param zsyzSbbzb 招商引资_申报_首谈信息_主
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertZsyzSbbzb(ZsyzSbbzb zsyzSbbzb) {
        //获取当前人员信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        zsyzSbbzb.setCreateTime(DateUtils.getNowDate());
        zsyzSbbzb.setUserId(user.getUserId());
        zsyzSbbzb.setDeptId(user.getDeptId());
        int count = zsyzSbbzbMapper.insertZsyzSbbzb(zsyzSbbzb);
        //保存附件信息
        List<ZsyzFj> zsyzFjList = zsyzSbbzb.getZsyzFjList();
        if (zsyzFjList != null){
            for (ZsyzFj zsyzFj : zsyzFjList) {
                zsyzFj.setSourceId(zsyzSbbzb.getId());
                zsyzFj.setType(ONE);
                zsyzFj.setXmId(zsyzSbbzb.getId());
                zsyzFj.setXmbh(zsyzSbbzb.getXmbh());
                zsyzFjMapper.insertZsyzFj(zsyzFj);
            }
        }
        //将项目投资方-自然人、企业两张表赋值项目ID
        xmProjectPersionMapper.updateXmProjectPersionByXmbh(zsyzSbbzb.getId(),zsyzSbbzb.getXmxsmc(), zsyzSbbzb.getXmbh());
        xmProjectInvestorMapper.updateXmProjectInvestorByXmbh(zsyzSbbzb.getId(),zsyzSbbzb.getXmxsmc(), zsyzSbbzb.getXmbh());

        //插入流程记录表
        ZsyzLcjl zsyzLcjl = new ZsyzLcjl();
        zsyzLcjl.setXmId(zsyzSbbzb.getId());
        zsyzLcjl.setXmmc(zsyzSbbzb.getXmxsmc());
        zsyzLcjl.setXmbh(zsyzSbbzb.getXmbh());
        zsyzLcjl.setDeptId(user.getDeptId());
        String deptName = user.getDept().getDeptName();
        zsyzLcjl.setDeptName(deptName);
        zsyzLcjl.setProgress(ONE);
        zsyzLcjl.setXmStatus(ONE);
        zsyzLcjlMapper.insertZsyzLcjl(zsyzLcjl);
        //发送短信
        SendSmsConfig sendSmsConfig = new SendSmsConfig();
        sendSmsConfig.setProgress(ONE);
        List<SendSmsConfig> sendSmsConfigs = sendSmsConfigService.selectSendSmsConfigList(sendSmsConfig);
        if (sendSmsConfigs != null){
            AsyncManager.me().execute(AsyncFactory.sendSms(sendSmsConfigs,"SMS_271465081"));
        }

        //发极光推送
        List<SysUser> sysUsers = sysUserService.selectUserByDeptId(100L);
        if(sysUsers!=null && sysUsers.size()>0){
            String notificationTitle = "消息通知";
            String msgTitle = "首谈审核";
            String msgContent = "您有一条首谈审核信息，请及时处理！";
            String jPushVO = "";
            List<String> listS = sysUsers.stream().map(SysUser::getJgId).collect(Collectors.toList());
            listS.removeAll(Collections.singleton(null));
            if(listS!=null && listS.size()>0){
                String[]  registrationId = listS.toArray(new String[listS.size()]);
                JPushToolUtil.sendToRegistrationId(notificationTitle,msgTitle,msgContent,jPushVO,registrationId);
            }
        }


        return count;
    }

    /**
     * 修改招商引资_申报_首谈信息_主
     *
     * @param zsyzSbbzb 招商引资_申报_首谈信息_主
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateZsyzSbbzb(ZsyzSbbzb zsyzSbbzb) {

        zsyzSbbzb.setUpdateTime(DateUtils.getNowDate());
        zsyzSbbzb.setXmStatus(ONE);
        int count = zsyzSbbzbMapper.updateZsyzSbbzb(zsyzSbbzb);
        //修改附件
        if (zsyzSbbzb.getZsyzFjList() != null && zsyzSbbzb.getZsyzFjList().size() > 0) {
            ZsyzFj zsyzFjDelete = new ZsyzFj();
            zsyzFjDelete.setSourceId(zsyzSbbzb.getId());
            zsyzFjDelete.setType(ONE);
            //先删除相关附件
            zsyzFjMapper.deleteZsyzFjBySourceId(zsyzFjDelete);
            //再将文件新增进数据库
            List<ZsyzFj> zsyzFjList = zsyzSbbzb.getZsyzFjList();
            if (zsyzFjList != null){
                for (ZsyzFj zsyzFj : zsyzFjList) {
                    zsyzFj.setSourceId(zsyzSbbzb.getId());
                    zsyzFj.setType(ONE);
                    zsyzFj.setXmId(zsyzSbbzb.getId());
                    zsyzFj.setXmbh(zsyzSbbzb.getXmbh());
                    zsyzFjMapper.insertZsyzFj(zsyzFj);
                }
            }
        }

        //发送短信
        SendSmsConfig sendSmsConfig = new SendSmsConfig();
        sendSmsConfig.setProgress(ONE);
        List<SendSmsConfig> sendSmsConfigs = sendSmsConfigService.selectSendSmsConfigList(sendSmsConfig);
        if (sendSmsConfigs != null){
            AsyncManager.me().execute(AsyncFactory.sendSms(sendSmsConfigs,"SMS_271465081"));
        }

        //发极光推送
        List<SysUser> sysUsers = sysUserService.selectUserByDeptId(100L);
        if(sysUsers!=null && sysUsers.size()>0){
            String notificationTitle = "消息通知";
            String msgTitle = "首谈审核";
            String msgContent = "您有一条首谈审核信息，请及时处理！";
            String jPushVO = "";
            List<String> listS = sysUsers.stream().map(SysUser::getJgId).collect(Collectors.toList());
            listS.removeAll(Collections.singleton(null));
            if(listS!=null && listS.size()>0){
                String[]  registrationId = listS.toArray(new String[listS.size()]);
                JPushToolUtil.sendToRegistrationId(notificationTitle,msgTitle,msgContent,jPushVO,registrationId);
            }
        }
        return count;
    }

    /**
     * 专班跟进
     *
     * @param zsyzSbbzb
     * @return
     */
    @Override
    public int updateZsyzSbbzbMeet(ZsyzSbbzb zsyzSbbzb) {
        return zsyzSbbzbMapper.updateZsyzSbbzbMeet(zsyzSbbzb);
    }

    /**
     * 更新承接地信息
     *
     * @param zsyzSbbzb
     * @return
     */
    @Override
    public int updateZsyzSbbzbCjd(ZsyzSbbzb zsyzSbbzb) {
        return zsyzSbbzbMapper.updateZsyzSbbzbCjd(zsyzSbbzb);
    }

    //线索暂存/终止接口
    @Override
    public int updateZsyzSbbzbForZc(ZsyzSbbzb zsyzSbbzb) {
        return zsyzSbbzbMapper.updateZsyzSbbzbForZc(zsyzSbbzb);
    }


    /**
     * 批量删除招商引资_申报_首谈信息_主
     *
     * @param ids 需要删除的招商引资_申报_首谈信息_主ID
     * @return 结果
     */
    @Override
    public int deleteZsyzSbbzbByIds(Long[] ids) {
        return zsyzSbbzbMapper.deleteZsyzSbbzbByIds(ids);
    }

    /**
     * 删除招商引资_申报_首谈信息_主信息
     *
     * @param id 招商引资_申报_首谈信息_主ID
     * @return 结果
     */
    @Override
    public int deleteZsyzSbbzbById(Long id) {
        return zsyzSbbzbMapper.deleteZsyzSbbzbById(id);
    }

    @Override
    @DataScope(deptAlias = "s")
    public List<ZsyzSbbzb> selectZsyzSbbzbListDc(ZsyzSbbzb zsyzSbbzb) {
        return zsyzSbbzbMapper.selectZsyzSbbzbListDc(zsyzSbbzb);
    }

    @Override
    @DataScope(deptAlias = "s",permission = "s.cjd_id")
    public List<ZsyzSbbzb> ldpsList(ZsyzSbbzb zsyzSbbzb) {

        List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
        List<ZsyzSbbzb> zsyzSbbzbs = new ArrayList<>();
        boolean flag = true;
        if (roles != null){
            for (SysRole role : roles) {
                String roleKey = role.getRoleKey();
                if (YSBM.equals(roleKey)){
                    //如果是要素部门角色只能看到分派给要素部门的和自己新增的线索
                    flag = false;
                    break;
                }
            }
        }
        if (flag){
            zsyzSbbzbs = zsyzSbbzbMapper.selectZsyzSbbzbListPs(zsyzSbbzb);
        }else {
            //如果是要素部门角色只能看到分派给要素部门的和自己新增的线索
            zsyzSbbzb.setDeptId(SecurityUtils.getDeptId());
            zsyzSbbzbs = zsyzSbbzbMapper.selectZsyzSbbzbListByZpPs(zsyzSbbzb);
        }
        return zsyzSbbzbs;
    }


    @Override
    public long selectZsyzSbbzbListCount(ZsyzSbbzb zsyzSbbzb) {
        return zsyzSbbzbMapper.selectZsyzSbbzbListCount(zsyzSbbzb);
    }

    /**
     * 通过企查查,查询企业信息
     * @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("https://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<>());
    }
}
