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.satisfaction.SatisfiedControlProjectMapper;
import cn.com.countrygarden.bi.main.dao.sys.UserRolesMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbSysUserMapper;
import cn.com.countrygarden.bi.main.dto.ck.SatisfiedControlProjectDTO;
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.satisfaction.SatisfiedControlProject;
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.SatisfiedControlProjectService;
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 cn.hutool.core.util.NumberUtil;
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.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *   控制塔满意度-项目业务处理
 * </p>
 *
 * @author
 * @date 2021-08-06
 * @version V1.0
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class SatisfiedControlProjectServiceImpl implements SatisfiedControlProjectService {

    @Autowired
    private SatisfiedControlProjectMapper satisfiedControlProjectMapper;
    @Autowired
    private UserRolesMapper userRolesMapper;

    @Autowired
    private ShareConfigMapper shareConfigMapper;

    @Autowired
    private TbSysUserMapper tbSysUserMapper;

    private final org.slf4j.Logger logger = LoggerFactory.getLogger(ExcelArrearageServiceImpl.class);
    @Override
    public Result queryPageList(SatisfiedControlProject satisfiedControlProject, int page, int size, AccessToken accessToken) {
        List<String> rolesList = queryRoleCodes(null, accessToken.getUserCode());

        if (rolesList.contains("satisfaction_admin")) {
            if(StringUtil.isBlank(satisfiedControlProject.getYearNian())){
                if(StringUtil.isNotBlank(satisfiedControlProject.getNouchYue())){
                    String[] yuesr=satisfiedControlProject.getNouchYue().split(",");
                    satisfiedControlProject.setYueList(Arrays.asList(yuesr));
                    satisfiedControlProject.setMonthStr(null);
                    List<String> niancha=satisfiedControlProjectMapper.niancha();
                    List<String> nianxin=new ArrayList<>();
                    for (int i = 0; i <satisfiedControlProject.getYueList().size() ; i++) {
                        for (int j = 0; j <niancha.size() ; j++) {
                            String yuehie=niancha.get(j)+"-"+satisfiedControlProject.getYueList().get(i);
                            nianxin.add(yuehie);
                        }
                    }
                    satisfiedControlProject.setYueList(nianxin);
                }
            }

            if(StringUtil.isNotBlank(satisfiedControlProject.getMonthStr())){
                String[] yuesr=satisfiedControlProject.getMonthStr().split(",");
                satisfiedControlProject.setYueList(Arrays.asList(yuesr));
                satisfiedControlProject.setYearNian(null);
            }

            if(StringUtil.isNotBlank(satisfiedControlProject.getOrgCode())){
                if(satisfiedControlProject.getOrgCode().equals("0")){
                    satisfiedControlProject.setOrgCode("");
                }
            }

            if(StringUtil.isNotBlank(satisfiedControlProject.getCommStr())){
                String[] comm=satisfiedControlProject.getCommStr().split(",");
                satisfiedControlProject.setCommCodeList(Arrays.asList(comm));
            }

            Long toble=satisfiedControlProjectMapper.selectListDataToble(satisfiedControlProject);

            Page<Object> pageList = PageHelper.startPage(page,size);
            List<SatisfiedControlProject> list=satisfiedControlProjectMapper.queryPageList(satisfiedControlProject);

            if (CollectionUtils.isNotEmpty(list)){
                NumberFormat df = NumberFormat.getNumberInstance();
                df.setMaximumFractionDigits(2);
                for (int i = 0; i <list.size() ; i++) {
                    if(StringUtil.isBlank(list.get(i).getSamples())){
                        list.get(i).setSamples("/");
                    }

                    if(StringUtil.isBlank(list.get(i).getDissatisfied())){
                        list.get(i).setDissatisfied("/");
                    }

                    if(StringUtil.isBlank(list.get(i).getIsAssessment())){
                        list.get(i).setIsAssessment("/");
                    }

                    if(StringUtil.isNotBlank(list.get(i).getSatisfaction())){
                        list.get(i).setSatisfaction(String.valueOf(df.format(Double.valueOf(list.get(i).getSatisfaction())*100))+"%");
                    }else {
                        list.get(i).setSatisfaction("/");
                    }
                    if(StringUtil.isNotBlank(list.get(i).getSecurity())){
                        list.get(i).setSecurity(String.valueOf(df.format(Double.valueOf(list.get(i).getSecurity())*100))+"%");
                    }else {
                        list.get(i).setSecurity("/");
                    }
                    if(StringUtil.isNotBlank(list.get(i).getCleaning())){
                        list.get(i).setCleaning(String.valueOf(df.format(Double.valueOf(list.get(i).getCleaning())*100))+"%");
                    }else {
                        list.get(i).setCleaning("/");
                    }
                    if(StringUtil.isNotBlank(list.get(i).getGreen())){
                        list.get(i).setGreen(String.valueOf(df.format(Double.valueOf(list.get(i).getGreen())*100))+"%");
                    }else {
                        list.get(i).setGreen("/");
                    }
                    if(StringUtil.isNotBlank(list.get(i).getEngineering())){
                        list.get(i).setEngineering(String.valueOf(df.format(Double.valueOf(list.get(i).getEngineering())*100))+"%");
                    }else {
                        list.get(i).setEngineering("/");
                    }
                    if(StringUtil.isNotBlank(list.get(i).getCustomer())){
                        list.get(i).setCustomer(String.valueOf(df.format(Double.valueOf(list.get(i).getCustomer())*100))+"%");
                    }else {
                        list.get(i).setCustomer("/");
                    }
                    if(StringUtil.isNotBlank(list.get(i).getComprehensive())){
                        list.get(i).setComprehensive(String.valueOf(df.format(Double.valueOf(list.get(i).getComprehensive())*100))+"%");
                    }else {
                        list.get(i).setComprehensive("/");
                    }
                }
            }

            PageData data = new PageData(pageList);
            data.setData(list);
            data.setTotal(toble);
            return Response.response(data);
        }else {
            throw new ServiceException("此账号无权限查看");
        }
    }

    @Override
    public Result getrevenue(AccessToken accessToken, HttpServletRequest request) throws IOException {

        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){
            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");
        try {
            if(json.containsKey("startTime")){
                Date parse = sb.parse(json.getString("startTime"));
            }
            if(json.containsKey("endTime")){
                Date parse = sb.parse(json.getString("endTime"));
            }
        }catch (Exception e){
            logger.error("参数错误:startTime 或者 endTime 时间格式有误");
            System.err.println("参数错误:startTime 或者 endTime 时间格式有误");
            return Response.responseFail("参数错误:startTime 或者 endTime 时间格式有误");
        }*/
        String startTime=null;
        String endTime=null;

        if(json.containsKey("startTime")){
            startTime = json.getString("startTime")+" 00:00:00";
        }
        if(json.containsKey("endTime")){
            endTime = json.getString("endTime")+" 23:59:59";
        }
        SatisfiedControlProjectDTO satiseDTO=new SatisfiedControlProjectDTO();
        List<Map<String,String>> lima=new ArrayList<>();

        List<SatisfiedControlProject> listBiao=satisfiedControlProjectMapper.listBiao();

        List<SatisfiedControlProject> list=satisfiedControlProjectMapper.getrevenue(startTime,endTime);
        if(CollectionUtils.isNotEmpty(list)){
            for (int i = 0; i <list.size() ; i++) {
                if(StringUtil.isBlank(list.get(i).getSamples())){
                    list.get(i).setSamples("");
                }

                if(StringUtil.isBlank(list.get(i).getDissatisfied())){
                    list.get(i).setDissatisfied("");
                }

                if(StringUtil.isBlank(list.get(i).getIsAssessment())){
                    list.get(i).setIsAssessment("");
                }
                if(StringUtil.isBlank(list.get(i).getSatisfaction())){
                    list.get(i).setSatisfaction("");
                }
                if(StringUtil.isBlank(list.get(i).getSecurity())){
                    list.get(i).setSecurity("");
                }
                if(StringUtil.isBlank(list.get(i).getCleaning())){
                    list.get(i).setCleaning("");
                }
                if(StringUtil.isBlank(list.get(i).getGreen())){
                    list.get(i).setGreen("");
                }
                if(StringUtil.isBlank(list.get(i).getEngineering())){
                    list.get(i).setEngineering("");
                }
                if(StringUtil.isBlank(list.get(i).getCustomer())){
                    list.get(i).setCustomer("");
                }
                if(StringUtil.isBlank(list.get(i).getComprehensive())){
                    list.get(i).setComprehensive("");
                }
            }
            /*NumberFormat df = NumberFormat.getNumberInstance();
            df.setMaximumFractionDigits(2);
            for (int i = 0; i <list.size() ; i++) {
                if(StringUtil.isNotBlank(list.get(i).getSatisfaction())){
                    list.get(i).setSatisfaction(String.valueOf(df.format(Double.valueOf(list.get(i).getSatisfaction())*100)));
                }
                if(StringUtil.isNotBlank(list.get(i).getSecurity())){
                    list.get(i).setSecurity(String.valueOf(df.format(Double.valueOf(list.get(i).getSecurity())*100)));
                }
                if(StringUtil.isNotBlank(list.get(i).getCleaning())){
                    list.get(i).setCleaning(String.valueOf(df.format(Double.valueOf(list.get(i).getCleaning())*100)));
                }
                if(StringUtil.isNotBlank(list.get(i).getGreen())){
                    list.get(i).setGreen(String.valueOf(df.format(Double.valueOf(list.get(i).getGreen())*100)));
                }
                if(StringUtil.isNotBlank(list.get(i).getEngineering())){
                    list.get(i).setEngineering(String.valueOf(df.format(Double.valueOf(list.get(i).getEngineering())*100)));
                }
                if(StringUtil.isNotBlank(list.get(i).getCustomer())){
                    list.get(i).setCustomer(String.valueOf(df.format(Double.valueOf(list.get(i).getCustomer())*100)));
                }
                if(StringUtil.isNotBlank(list.get(i).getComprehensive())){
                    list.get(i).setComprehensive(String.valueOf(df.format(Double.valueOf(list.get(i).getComprehensive())*100)));
                }
            }*/
            satiseDTO.setList(list);

            for (int i = 0; i < listBiao.size(); i++) {
                Map<String,String> mapSt=new HashMap<>();
                mapSt.put(listBiao.get(i).getKey(),listBiao.get(i).getValue());
                lima.add(mapSt);
            }
            satiseDTO.setName(lima);
        }

        return Response.response(satiseDTO);
    }

    @Override
    public Result edit(SatisfiedControlProject satisfiedControlProject, AccessToken accessToken) {

        String s=null;
        Double sd=null;

        NumberFormat df = NumberFormat.getNumberInstance();
        df.setMaximumFractionDigits(5);

        if(!NumberUtil.isInteger(satisfiedControlProject.getSamples())){
            throw new ServiceException("样本数 请输入整数！！");
        }

        if(!NumberUtil.isInteger(satisfiedControlProject.getDissatisfied())){
            throw new ServiceException("不满意人数 请输入整数！！");
        }

        if(!satisfiedControlProject.getIsAssessment().equals("1") && !satisfiedControlProject.getIsAssessment().equals("0")){
            throw new ServiceException("X月是否考核 请输入0或1！！");
        }


        if(satisfiedControlProject.getSatisfaction().equals("/")){
            satisfiedControlProject.setSatisfaction("");
        }else if(satisfiedControlProject.getSatisfaction().indexOf("%")!=-1){
            s = satisfiedControlProject.getSatisfaction();
            s = s.substring(0, s.length() - 1);
            sd=Double.valueOf(s);
            sd=sd/100;
            satisfiedControlProject.setSatisfaction(df.format(sd));
        }

        if(satisfiedControlProject.getSecurity().equals("/")){
            satisfiedControlProject.setSecurity("");
        }else if(satisfiedControlProject.getSecurity().indexOf("%")!=-1){
            s = satisfiedControlProject.getSecurity();
            s = s.substring(0, s.length() - 1);
            sd=Double.valueOf(s);
            sd=sd/100;
            satisfiedControlProject.setSecurity(df.format(sd));
        }

        if(satisfiedControlProject.getCleaning().equals("/")){
            satisfiedControlProject.setCleaning("");
        }else if(satisfiedControlProject.getCleaning().indexOf("%")!=-1){
            s = satisfiedControlProject.getCleaning();
            s = s.substring(0, s.length() - 1);
            sd=Double.valueOf(s);
            sd=sd/100;
            satisfiedControlProject.setCleaning(df.format(sd));
        }

        if(satisfiedControlProject.getGreen().equals("/")){
            satisfiedControlProject.setGreen("");
        }else if(satisfiedControlProject.getGreen().indexOf("%")!=-1){
            s = satisfiedControlProject.getGreen();
            s = s.substring(0, s.length() - 1);
            sd=Double.valueOf(s);
            sd=sd/100;
            satisfiedControlProject.setGreen(df.format(sd));
        }

        if(satisfiedControlProject.getEngineering().equals("/")){
            satisfiedControlProject.setEngineering("");
        }else if(satisfiedControlProject.getEngineering().indexOf("%")!=-1){
            s = satisfiedControlProject.getEngineering();
            s = s.substring(0, s.length() - 1);
            sd=Double.valueOf(s);
            sd=sd/100;
            satisfiedControlProject.setEngineering(df.format(sd));
        }

        if(satisfiedControlProject.getCustomer().equals("/")){
            satisfiedControlProject.setCustomer("");
        }else if(satisfiedControlProject.getCustomer().indexOf("%")!=-1){
            s = satisfiedControlProject.getCustomer();
            s = s.substring(0, s.length() - 1);
            sd=Double.valueOf(s);
            sd=sd/100;
            satisfiedControlProject.setCustomer(df.format(sd));
        }

        if(satisfiedControlProject.getComprehensive().equals("/")){
            satisfiedControlProject.setComprehensive("");
        }else if(satisfiedControlProject.getComprehensive().indexOf("%")!=-1){
            s = satisfiedControlProject.getComprehensive();
            s = s.substring(0, s.length() - 1);
            sd=Double.valueOf(s);
            sd=sd/100;
            satisfiedControlProject.setComprehensive(df.format(sd));
        }
        TbSysUser tbSysUser = tbSysUserMapper.findByUserCodeNew(accessToken.getUserCode());
        satisfiedControlProject.setIsEditor(1);
        satisfiedControlProject.setUpdateTime(new Date());
        satisfiedControlProject.setUpdateBy(tbSysUser.getUserName());
        satisfiedControlProjectMapper.updateByPrimaryKeySelective(satisfiedControlProject);
        return Response.response();
    }

    @Override
    public Result del(String id, AccessToken accessToken) {
        TbSysUser tbSysUser = tbSysUserMapper.findByUserCodeNew(accessToken.getUserCode());
        SatisfiedControlProject satisfiedControlProject=new SatisfiedControlProject();
        satisfiedControlProject.setId(Long.valueOf(id));
        satisfiedControlProject.setStatus(0);
        satisfiedControlProject.setUpdateTime(new Date());
        satisfiedControlProject.setUpdateBy(tbSysUser.getUserName());
        satisfiedControlProjectMapper.updateByPrimaryKeySelective(satisfiedControlProject);
        return Response.response();

    }

    //身份认证
    public Result checkIdentity(String clientId, String timeString, String sign){
        ShareConfig share=new ShareConfig();
        share.setClientId(clientId);
        ShareConfig shareConfig = shareConfigMapper.selectOne(share);
        if(shareConfig ==null){
            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){
                return Response.responseFail("参数错误:调用时间与参数时间不能超过5分钟");
            }
        }catch (Exception e){
            return Response.responseFail("参数错误:timeString格式有误");
        }

        String md5String =clientId+clientSecret+timeString;
        String s = MD5.GetMD5Code(md5String);
        if(!s.equals(sign)){
            return Response.responseFail("认证失败:签名错误");
        }
        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("权限不足");
    }
}
