package cn.com.countrygarden.bi.main.service.ck.impl;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.ShareConfigMapper;
import cn.com.countrygarden.bi.main.dao.ck.res.CkResourceIncomeMapper;
import cn.com.countrygarden.bi.main.dao.ck.res.CkResourcesRevenueMapper;
import cn.com.countrygarden.bi.main.dao.sys.UserRolesMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbSysOrganMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbSysUserMapper;
import cn.com.countrygarden.bi.main.dto.advise.ProjectListVO;
import cn.com.countrygarden.bi.main.dto.advise.RegionListVO;
import cn.com.countrygarden.bi.main.dto.ck.CkRegionVo;
import cn.com.countrygarden.bi.main.dto.ck.CkauditReminderVO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.ShareConfig;
import cn.com.countrygarden.bi.main.model.ck.res.CkResourceIncome;
import cn.com.countrygarden.bi.main.model.ck.res.CkResourcesRevenue;
import cn.com.countrygarden.bi.main.model.sys.UserRoles;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysUser;
import cn.com.countrygarden.bi.main.service.ck.CkResourcesRevenueService;
import cn.com.countrygarden.bi.main.service.erp.impl.ExcelArrearageServiceImpl;
import cn.com.countrygarden.bi.main.util.MD5;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *   公共资源收入业务处理
 * </p>
 *
 * @author
 * @date 2021-06-29
 * @version V1.0
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class CkResourcesRevenueServiceImpl implements CkResourcesRevenueService {
    @Autowired
    private TbSysOrganMapper tbSysOrganMapper;
    @Autowired
    private UserRolesMapper userRolesMapper;
    @Autowired
    private CkResourcesRevenueMapper ckResourcesRevenueMapper;
    @Autowired
    private TbSysUserMapper tbSysUserMapper;
    @Autowired
    private ShareConfigMapper shareConfigMapper;
    @Autowired
    private CkResourceIncomeMapper ckResourceIncomeMapper;

    private final org.slf4j.Logger logger = LoggerFactory.getLogger(ExcelArrearageServiceImpl.class);


    @Override
    public Result queryPageList(CkResourcesRevenue cleanerQueyr,int page,int size,AccessToken accessToken) {

        List<String> organCodeString=new ArrayList<>();
        List<String> commIdString=new ArrayList<>();
        String addrole=null;
        List<String> rolesList = queryRoleCodes(null, accessToken.getUserCode());
        if (rolesList.contains("admin")|| rolesList.contains("ck_resource_input")|| rolesList.contains("ck_resources_audit")){
            if(rolesList.contains("ck_resource_input") || rolesList.contains("ck_resources_audit")){
                List<RegionListVO> areaList = tbSysOrganMapper.findArea(null, accessToken.getUserCode());
                for (int i = 0; i < areaList.size(); i++) {
                    organCodeString.add(areaList.get(i).getOrganCode());
                    List<ProjectListVO> projectList = tbSysOrganMapper.findProject(areaList.get(i).getOrganCode(),accessToken.getUserCode(),null,null,null);
                    for (int j = 0; j <projectList.size() ; j++) {
                        commIdString.add(projectList.get(j).getCommId());
                    }
                }
            }
        }else {
            throw new ServiceException("此账号没有权限查看");
        }
        List<String> time=new ArrayList<>();
        if(StringUtil.isNotBlank(cleanerQueyr.getTimeMonth())){
            String[] shitime=cleanerQueyr.getTimeMonth().split(",");
            for (int i = 0; i < shitime.length; i++) {
                time.add(shitime[i]);
            }
        }


        Long toble=ckResourcesRevenueMapper.selectListDataToble(cleanerQueyr,organCodeString,commIdString,time);

        Page<Object> pageList = PageHelper.startPage(page, size);
        List<CkResourcesRevenue> list=ckResourcesRevenueMapper.selectListData(cleanerQueyr,organCodeString,commIdString,time);

        PageData data = new PageData(pageList);
        data.setData(list);
        data.setTotal(toble);
        return Response.response(data);
    }

    @Override
    public List<RegionListVO> getRegionDate(AccessToken accessToken) {
        List<String> rolesList = queryRoleCodes(null, accessToken.getUserCode());
        List<RegionListVO> areaList = null;
        List<CkRegionVo> ckRegionVoList = new ArrayList<>();
        CkRegionVo ckRegionVo = null;
        List<ProjectListVO> projectList = null;
        List<ProjectListVO> projects = null;
        if (rolesList.contains("admin") || rolesList.contains("ck_resource_input")  || rolesList.contains("ck_resources_audit")){
            String userCode=null;
            if (rolesList.contains("admin")) {
                userCode=null;
            }else {
                userCode=accessToken.getUserCode();
            }
            areaList = tbSysOrganMapper.findAreaBasicInfo(null,null,userCode);
        }
        return areaList;
    }

    @Override
    public List<ProjectListVO> getPojDate(AccessToken accessToken, String organCode) {
        String userCode=null;
        List<String> rolesList = queryRoleCodes(null, accessToken.getUserCode());
        if(rolesList.contains("ck_resource_input") || rolesList.contains("ck_resources_audit")){
            userCode=accessToken.getUserCode();
        }
        List<ProjectListVO> projectList = tbSysOrganMapper.findProjectBasicInfo(organCode,userCode,null,null,null);

        return projectList;
    }

    @Override
    public Result getrevenue(AccessToken accessToken, HttpServletRequest request) throws IOException {
        logger.info("正在进行调用接口获取数据------------------------");
        System.out.println("正在进行调用接口获取数据------------------------");

        BufferedReader bufferReader = new BufferedReader(request.getReader());
        StringBuffer sbder = new StringBuffer();
        String line = null;
        while ((line = bufferReader.readLine()) != null) {
            sbder.append(line);
        }
        if(sbder==null || sbder.length()==0){
            logger.error("请输入参数");
            System.err.println("请输入参数");
            return Response.responseFail("请输入参数");
        }
        JSONObject json = JSONObject.fromObject(sbder.toString());
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("clientId",json.getString("clientId"));
        map.put("timeString",json.getString("timeString"));
        map.put("sign",json.getString("sign"));
        Result result = checkIdentity(json.getString("clientId"), json.getString("timeString"), json.getString("sign"));
        int code = result.getResultCode();
        if(500 == code){
            logger.error("认证失败-----------");
            System.err.println("认证失败-----------");
            return result;
        }

        SimpleDateFormat sb=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            if(json.containsKey("updateDate")){
                Date parse = sb.parse(json.getString("updateDate"));
            }
        }catch (Exception e){
            logger.error("参数错误:updateDate时间格式有误");
            System.err.println("参数错误:updateDate时间格式有误");
            return Response.responseFail("参数错误:updateDate时间格式有误");
        }

        String commCode=null;
        String updateDate=null;
        if(!json.containsKey("updateDate")&&!json.containsKey("commCode")){
            logger.error("请传入更新日期或者项目编号");
            System.err.println("请传入更新日期或者项目编号");
            return Response.responseFail("请传入更新日期或者项目编号");
        }else {
            if(json.containsKey("updateDate")){
                updateDate=json.getString("updateDate");
            }
            if(json.containsKey("commCode")){
                commCode=json.getString("commCode");
            }
        }
       List<CkResourcesRevenue> list=ckResourcesRevenueMapper.selectGetrevenue(commCode,updateDate);
        return Response.response(list);
    }

    @Override
    public Result queryById(Long id) {
        List<CkResourcesRevenue> list=ckResourcesRevenueMapper.selectByIds(String.valueOf(id));
        return Response.response(list);
    }

    @Override
    public Result toExamine(CkResourcesRevenue ckResourcesRevenue) {
        TbSysUser tbSysUser = tbSysUserMapper.findByUserCodeNew(ckResourcesRevenue.getAuditBy());
        ckResourcesRevenue.setDataStatus(1);
        ckResourcesRevenue.setAuditName(tbSysUser.getUserName()+tbSysUser.getUserCode());
        ckResourcesRevenue.setUpdateName(tbSysUser.getUserName());
        ckResourcesRevenue.setUpdateTime(new Date());
        ckResourcesRevenueMapper.updateByPrimaryKeySelective(ckResourcesRevenue);
        return Response.response("审核通过");
    }

    @Override
    public Result auditorUser(String organCode,String commCode,AccessToken accessToken,HttpServletRequest request) {

        UserRoles userRoles=new UserRoles();
        userRoles.setRoleCode("ck_resources_audit");
        List<UserRoles> rolesList = userRolesMapper.select(userRoles);
        List<TbSysUser> shenhe=new ArrayList<>();
        for (int i = 0; i < rolesList.size(); i++) {
            List<RegionListVO> areaLishenqu=tbSysOrganMapper.findAreaBasicInfo(organCode,commCode,rolesList.get(i).getUserCode());
            if(CollectionUtils.isNotEmpty(areaLishenqu)){
                TbSysUser tbSysUser = tbSysUserMapper.findByUserCodeNew(rolesList.get(i).getUserCode());
                tbSysUser.setUserName(tbSysUser.getUserName()+tbSysUser.getUserCode());
                shenhe.add(tbSysUser);
            }
        }
        return Response.response(shenhe);
    }
// 0 收益  1收入
    @Override
    public Result auditReminder(AccessToken accessToken, HttpServletRequest request) throws ParseException {

        SimpleDateFormat dFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

       // CkauditReminderVO
        List<CkauditReminderVO> stringList=new ArrayList<>();

        CkResourcesRevenue ckResoRev=new CkResourcesRevenue();
        ckResoRev.setAuditBy(accessToken.getUserCode());
        ckResoRev.setDataStatus(0);
        List<CkResourcesRevenue> revenueList=ckResourcesRevenueMapper.selectckResoRevtishi(ckResoRev);

        CkResourceIncome income=new CkResourceIncome();
        income.setAuditBy(accessToken.getUserCode());
        income.setDataStatus(0);
         List<CkResourceIncome> incomeList=ckResourceIncomeMapper.selectincometishi(income);

         String xinxishouru="";
        String xinxishouyi="";
        Long shouyilong=0L;
        Long shourulong=0L;
        String xinxi="";
        CkauditReminderVO ckauditReminderVO=new CkauditReminderVO();
        if(CollectionUtils.isNotEmpty(revenueList)){
            if(revenueList.size()==1){
                for (int i = 0; i < revenueList.size(); i++) {
                    xinxishouru+=revenueList.get(i).getOrgName()+"-"
                            +revenueList.get(i).getCommName()+"-"+revenueList.get(i).getCreateName()+"提交了"+revenueList.get(i).getTimeMonth()
                            +"【公共资源收入】,请审批。 ";
                }
            }else {
                xinxishouru+="你有【公共资源收入】"+revenueList.size()+"条信息，待审批";
            }
            String shourudateStr=dFormat2.format(revenueList.get(0).getCreateTime());
            Date shourudate=dFormat2.parse(shourudateStr);
            shourulong=shourudate.getTime();
            ckauditReminderVO.setIndex(1);
            ckauditReminderVO.setOrgCode(revenueList.get(0).getOrgCode());
            ckauditReminderVO.setCommCode(revenueList.get(0).getCommCode());
            ckauditReminderVO.setTimeMonth(revenueList.get(0).getTimeMonth());
        }

        if(CollectionUtils.isNotEmpty(incomeList)){
            if(incomeList.size()==1){
                for (int j = 0; j < incomeList.size(); j++) {
                    xinxishouyi+=incomeList.get(j).getOrgName()+"-"
                            +incomeList.get(j).getCommName()+"-"+incomeList.get(j).getCreateName()+"提交了"+incomeList.get(j).getTimeMonth()
                            +"【公共资源收益】,请审批。 ";

                }
            }else {
                xinxishouyi+=" 你有【公共资源收益】"+incomeList.size()+"条信息，待审批";
            }
            String shouyidateStr=dFormat2.format(incomeList.get(0).getCreateTime());
            Date shouyidate=dFormat2.parse(shouyidateStr);
            shouyilong=shouyidate.getTime();
            ckauditReminderVO.setIndex(0);
            ckauditReminderVO.setOrgCode(incomeList.get(0).getOrgCode());
            ckauditReminderVO.setCommCode(incomeList.get(0).getCommCode());
            ckauditReminderVO.setTimeMonth(incomeList.get(0).getTimeMonth());
        }

        if(!shouyilong.equals(0L)){
            xinxi="";
            xinxi+=xinxishouru+xinxishouyi;
            ckauditReminderVO.setIndex(0);
        }

        if(!shourulong.equals(0L)){
            xinxi="";
            xinxi+=xinxishouru+xinxishouyi;
            ckauditReminderVO.setIndex(1);
        }
        if(!shourulong.equals(0L)&&!shouyilong.equals(0L)){
            xinxi="";
            if(shouyilong>shourulong){
                //收益时间后   //收入时间前
                xinxi+=xinxishouru+xinxishouyi;
                ckauditReminderVO.setIndex(1);
            }else {
                xinxi+=xinxishouyi+xinxishouru;
                ckauditReminderVO.setIndex(0);
            }
        }


        ckauditReminderVO.setXinxi(xinxi);
        stringList.add(ckauditReminderVO);
        return Response.response(stringList);
    }

    @Override
    public Result addone(CkResourcesRevenue ro,AccessToken accessToken, HttpServletRequest request) {

        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH )+1;

        if(month<=9){
            ro.setTimeMonth(year+"年"+"0"+month+"月");
        }else {
            ro.setTimeMonth(year+"年"+month+"月");
        }
        ro.setStatus(1);
        List<CkResourcesRevenue> list=ckResourcesRevenueMapper.select(ro);
        if(CollectionUtils.isNotEmpty(list)){
            return Response.response(0);
        }else {
            return Response.response(1);
        }
    }


    @Override
    public Result add(CkResourcesRevenue ro,AccessToken accessToken) {
        TbSysUser tbSysUser = tbSysUserMapper.findByUserCodeNew(accessToken.getUserCode());
        TbSysUser tbSy = tbSysUserMapper.findByUserCodeNew(ro.getAuditBy());
        ro.setStatus(1);

        CkResourcesRevenue ressReve=new CkResourcesRevenue();
        ressReve.setTimeMonth(ro.getTimeMonth());
        ressReve.setStatus(1);
        ressReve.setOrgCode(ro.getOrgCode());
        ressReve.setCommCode(ro.getCommCode());
        List<CkResourcesRevenue> list=ckResourcesRevenueMapper.select(ressReve);
        if(CollectionUtils.isNotEmpty(list)){
             throw new ServiceException("请勿重复添加数据！");
        }

        ro.setDataStatus(0);
        ro.setCreateName(tbSysUser.getUserName()+tbSysUser.getUserCode());
        ro.setCreateTime(new Date());
        ro.setCreateBy(accessToken.getUserCode());
        ro.setUpdateTime(new Date());
        ro.setAuditName(tbSy.getUserName()+tbSy.getUserCode());
        ckResourcesRevenueMapper.insert(ro);
        return Response.response("添加成功");
    }

    @Override
    public Result edit(CkResourcesRevenue ro,AccessToken accessToken) {
        TbSysUser tbSysUser = tbSysUserMapper.findByUserCodeNew(accessToken.getUserCode());
        ro.setUpdateTime(new Date());
        ro.setUpdateName(tbSysUser.getUserName());
        ckResourcesRevenueMapper.updateByPrimaryKeySelective(ro);
        return Response.response("编辑成功");
    }


    public List<String> queryRoleCodes(String[] roles, String userCode) {
        //保洁模块的权限问题：admin=ck_admin>区域>项目>其他
        Condition condition = new Condition(UserRoles.class);
        condition.selectProperties("roleCode");
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("userCode", userCode);
        if (roles != null && roles.length > 0) {
            criteria.andIn("roleCode", Arrays.asList(roles));
        }

        List<UserRoles> rolesList = userRolesMapper.selectByCondition(condition);
        if (CollectionUtils.isNotEmpty(rolesList)) {
            return rolesList.stream().map(e -> e.getRoleCode()).collect(Collectors.toList());
        }
        // 权限不足
        throw new ServiceException("权限不足");
    }

    //身份认证
    public Result checkIdentity(String clientId, String timeString, String sign){
        logger.info("正在进行身份认证------------------------");
        System.out.println("正在进行身份认证------------------------");
        ShareConfig share=new ShareConfig();
        share.setClientId(clientId);
        ShareConfig shareConfig = shareConfigMapper.selectOne(share);
        if(shareConfig ==null){
            logger.error("认证失败:客户端编码有误");
            System.err.println("认证失败:客户端编码有误");
            return Response.responseFail("认证失败:客户端编码有误");
        }
        String clientSecret = shareConfig.getClientSecret();
        SimpleDateFormat sb=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            String sd = sb.format(new Date(Long.valueOf(timeString+"000")));
            Date parse = sb.parse(sd);
            Date date=new Date();
            long l = date.getTime() - parse.getTime();
            if(l>5*60*1000){
                logger.error("参数错误:调用时间与参数时间不能超过5分钟");
                System.err.println("参数错误:调用时间与参数时间不能超过5分钟");
                return Response.responseFail("参数错误:调用时间与参数时间不能超过5分钟");
            }
        }catch (Exception e){
            logger.error("参数错误:timeString格式有误");
            System.err.println("参数错误:timeString格式有误");
            return Response.responseFail("参数错误:timeString格式有误");
        }

        String md5String =clientId+clientSecret+timeString;
        String s = MD5.GetMD5Code(md5String);
        if(!s.equals(sign)){
            logger.error("认证失败:签名错误");
            System.err.println("认证失败:签名错误");
            return Response.responseFail("认证失败:签名错误");
        }
        logger.info("认证成功");
        System.out.println("认证成功");
        return Response.response("认证成功");
    }
}
