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.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.CkCleanerQueyr;
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.sys.UserRoles;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysUser;
import cn.com.countrygarden.bi.main.service.ck.CkResourceIncomeService;
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.SimpleDateFormat;
import java.time.LocalDate;
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 CkResourceIncomeServiceImpl implements CkResourceIncomeService {
    @Autowired
    private TbSysOrganMapper tbSysOrganMapper;
    @Autowired
    private CkResourceIncomeMapper ckResourceIncomeMapper;
    @Autowired
    private TbSysUserMapper tbSysUserMapper;
    @Autowired
    private UserRolesMapper userRolesMapper;
    @Autowired
    private ShareConfigMapper shareConfigMapper;

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


    @Override
    public Result queryPageList(CkResourceIncome 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_resources_audit") || rolesList.contains("ck_resource_input")){
                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=ckResourceIncomeMapper.selectListDataToble(cleanerQueyr,organCodeString,commIdString,time);

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

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

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

    @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<CkResourceIncome> list=ckResourceIncomeMapper.selectGetrevenue(commCode,updateDate);
        return Response.response(list);
    }

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

    @Override
    public Result addone(CkResourceIncome ro, AccessToken accessToken, HttpServletRequest request) {
       //添加上月
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH )+1;

        if(month-1==0){
            ro.setTimeMonth((year-1)+"年"+"12月");
        }else {
            if(month-1<=9){
                ro.setTimeMonth(year+"年"+"0"+(month-1)+"月");
            }else {
                ro.setTimeMonth(year+"年"+(month-1)+"月");
            }
        }

        ro.setStatus(1);
        List<CkResourceIncome> list=ckResourceIncomeMapper.select(ro);
        if(CollectionUtils.isNotEmpty(list)){
            return Response.response(0);
        }else {
            return Response.response(1);
        }
    }

    @Override
    public Result openingClosing(CkResourceIncome ro,AccessToken accessToken, HttpServletRequest request) {

        LocalDate date = LocalDate.now();
        String nian=String.valueOf(date.getYear());
        ro.setTimeMonth(nian+"年");
        ro.setStatus(1);
        List<CkResourceIncome> list=ckResourceIncomeMapper.selectOpeningClosing(ro);
        if(CollectionUtils.isNotEmpty(list)){
            return Response.response(list);
        }
        return Response.response();
    }

    @Override
    public Result openingClosingShenHeOne(CkResourceIncome ro, AccessToken accessToken, HttpServletRequest request) {
        CkCleanerQueyr ckCleanerQueyr=new CkCleanerQueyr();
        LocalDate date = LocalDate.now();
        String nian=String.valueOf(date.getYear());
        ro.setTimeMonth(nian+"年");
        ro.setStatus(1);
        ro.setAuditBy(accessToken.getUserCode());
        List<CkResourceIncome> list=ckResourceIncomeMapper.selectOpeningClosingShenHeOne(ro);
        if(CollectionUtils.isNotEmpty(list)){
            if (list.get(0).getId().equals(ro.getId())){
                ckCleanerQueyr.setIsckSert(true);
                return Response.response(ckCleanerQueyr);
            }

        }
        ckCleanerQueyr.setIsckSert(false);
        return Response.response(ckCleanerQueyr);
    }

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

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


        ro.setStatus(1);
        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());
        ckResourceIncomeMapper.insert(ro);
        return Response.response("添加成功");
    }

    @Override
    public Result edit(CkResourceIncome ro,AccessToken accessToken) {
        TbSysUser tbSysUser = tbSysUserMapper.findByUserCodeNew(accessToken.getUserCode());
        ro.setUpdateTime(new Date());
        ro.setUpdateName(tbSysUser.getUserName());
        ckResourceIncomeMapper.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("认证成功");
    }
}
