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.SatisfiedRegionMapper;
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.SatisfiedRegionDTO;
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.SatisfiedRegion;
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.SatisfiedRegionService;
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.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 SatisfiedRegionServiceImpl implements SatisfiedRegionService {

    @Autowired
    private SatisfiedRegionMapper satisfiedRegionMapper;
    @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(SatisfiedRegion satisfiedRegion, int page, int size, AccessToken accessToken) {

        List<String> rolesList = queryRoleCodes(null, accessToken.getUserCode());

        if (rolesList.contains("satisfaction_admin")) {

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

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

            if(StringUtil.isNotBlank(satisfiedRegion.getOrgCodeStr())){
                if(satisfiedRegion.getOrgCodeStr().equals("0")){
                    satisfiedRegion.setOrgCodeList(null);
                }else {
                    String[] org=satisfiedRegion.getOrgCodeStr().split(",");
                    satisfiedRegion.setOrgCodeList(Arrays.asList(org));
                }

            }
            
            Long toble=satisfiedRegionMapper.selectListDataToble(satisfiedRegion);

            Page<Object> pageList = PageHelper.startPage(page,size);
            List<SatisfiedRegion> list=satisfiedRegionMapper.queryPageList(satisfiedRegion);

            if (CollectionUtils.isNotEmpty(list)){
                NumberFormat df = NumberFormat.getNumberInstance();
                df.setMaximumFractionDigits(2);
                for (int i = 0; i <list.size() ; i++) {
                    if(StringUtil.isNotBlank(list.get(i).getSecurityResults())){
                        list.get(i).setSecurityResults(String.valueOf(df.format(Double.valueOf(list.get(i).getSecurityResults())*100))+"%");
                    }else {
                        list.get(i).setSecurityResults("/");
                    }
                    if(StringUtil.isNotBlank(list.get(i).getCleaningResults())){
                        list.get(i).setCleaningResults(String.valueOf(df.format(Double.valueOf(list.get(i).getCleaningResults())*100))+"%");
                    }else {
                        list.get(i).setCleaningResults("/");
                    }
                    if(StringUtil.isNotBlank(list.get(i).getGreenResults())){
                        list.get(i).setGreenResults(String.valueOf(df.format(Double.valueOf(list.get(i).getGreenResults())*100))+"%");
                    }else {
                        list.get(i).setGreenResults("/");
                    }
                    if(StringUtil.isNotBlank(list.get(i).getEngineeringResults())){
                        list.get(i).setEngineeringResults(String.valueOf(df.format(Double.valueOf(list.get(i).getEngineeringResults())*100))+"%");
                    }else {
                        list.get(i).setEngineeringResults("/");
                    }
                    if(StringUtil.isNotBlank(list.get(i).getCustomerResults())){
                        list.get(i).setCustomerResults(String.valueOf(df.format(Double.valueOf(list.get(i).getCustomerResults())*100))+"%");
                    }else {
                        list.get(i).setCustomerResults("/");
                    }
                    if(StringUtil.isNotBlank(list.get(i).getMonthResults())){
                        list.get(i).setMonthResults(String.valueOf(df.format(Double.valueOf(list.get(i).getMonthResults())*100))+"%");
                    }else {
                        list.get(i).setMonthResults("/");
                    }
                    if(StringUtil.isNotBlank(list.get(i).getAnnualResults())){
                        list.get(i).setAnnualResults(String.valueOf(df.format(Double.valueOf(list.get(i).getAnnualResults())*100))+"%");
                    }else {
                        list.get(i).setAnnualResults("/");
                    }
                    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;
        }

        if(!json.containsKey("startTime") && !json.containsKey("endTime")){
            logger.error("请传入时间参数");
            System.err.println("请传入时间参数");
            return Response.responseFail("请传入时间参数");
        }

      /*  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";
        }
        SatisfiedRegionDTO satiseDTO=new SatisfiedRegionDTO();
        List<Map<String,String>> lima=new ArrayList<>();

        List<SatisfiedRegion> listBiao=satisfiedRegionMapper.listBiao();

        List<SatisfiedRegion> list=satisfiedRegionMapper.getrevenue(startTime,endTime);
        if(CollectionUtils.isNotEmpty(list)){
            for (int i = 0; i <list.size() ; i++) {
                if (StringUtil.isBlank(list.get(i).getSecurityResults())) {
                    list.get(i).setSecurityResults("");
                }
                if (StringUtil.isBlank(list.get(i).getCleaningResults())) {
                    list.get(i).setCleaningResults("");
                }
                if (StringUtil.isBlank(list.get(i).getGreenResults())) {
                    list.get(i).setGreenResults("");
                }
                if (StringUtil.isBlank(list.get(i).getEngineeringResults())) {
                    list.get(i).setEngineeringResults("");
                }
                if (StringUtil.isBlank(list.get(i).getCustomerResults())) {
                    list.get(i).setCustomerResults("");
                }
                if (StringUtil.isBlank(list.get(i).getMonthResults())) {
                    list.get(i).setMonthResults("");
                }
                if (StringUtil.isBlank(list.get(i).getAnnualResults())) {
                    list.get(i).setAnnualResults("");
                }
                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).getSecurityResults())){
                    list.get(i).setSecurityResults(String.valueOf(df.format(Double.valueOf(list.get(i).getSecurityResults())*100)));
                }
                if(StringUtil.isNotBlank(list.get(i).getCleaningResults())){
                    list.get(i).setCleaningResults(String.valueOf(df.format(Double.valueOf(list.get(i).getCleaningResults())*100)));
                }
                if(StringUtil.isNotBlank(list.get(i).getGreenResults())){
                    list.get(i).setGreenResults(String.valueOf(df.format(Double.valueOf(list.get(i).getGreenResults())*100)));
                }
                if(StringUtil.isNotBlank(list.get(i).getEngineeringResults())){
                    list.get(i).setEngineeringResults(String.valueOf(df.format(Double.valueOf(list.get(i).getEngineeringResults())*100)));
                }
                if(StringUtil.isNotBlank(list.get(i).getCustomerResults())){
                    list.get(i).setCustomerResults(String.valueOf(df.format(Double.valueOf(list.get(i).getCustomerResults())*100)));
                }
                if(StringUtil.isNotBlank(list.get(i).getMonthResults())){
                    list.get(i).setMonthResults(String.valueOf(df.format(Double.valueOf(list.get(i).getMonthResults())*100)));
                }
                if(StringUtil.isNotBlank(list.get(i).getAnnualResults())){
                    list.get(i).setAnnualResults(String.valueOf(df.format(Double.valueOf(list.get(i).getAnnualResults())*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(SatisfiedRegion satisfiedRegion, AccessToken accessToken) {

        String s=null;
        Double sd=null;

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

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

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


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

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

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

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

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


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

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

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

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

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

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

        return Response.response();
    }

    @Override
    public Result del(String id, AccessToken accessToken) {
        TbSysUser tbSysUser = tbSysUserMapper.findByUserCodeNew(accessToken.getUserCode());
        SatisfiedRegion satisfiedRegion=new SatisfiedRegion();
        satisfiedRegion.setId(Long.valueOf(id));
        satisfiedRegion.setStatus(0);
        satisfiedRegion.setUpdateTime(new Date());
        satisfiedRegion.setUpdateBy(tbSysUser.getUserName());
        satisfiedRegionMapper.updateByPrimaryKeySelective(satisfiedRegion);
        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("权限不足");
    }
}
