package com.mortals.xhx.module.pj.web;

import com.alibaba.fastjson.JSON;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.util.ThreadPool;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.common.pdu.RespData;
import com.mortals.xhx.common.pdu.site.SitePdu;
import com.mortals.xhx.common.utils.BatchSavePjTask;
import com.mortals.xhx.feign.site.ISiteFeign;
import com.mortals.xhx.module.ph.model.PhQueueEntity;
import com.mortals.xhx.module.ph.model.PhQueueQuery;
import com.mortals.xhx.module.pj.model.PjEvaluateQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.mortals.framework.model.Context;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.module.pj.model.PjEvaluateEntity;
import com.mortals.xhx.module.pj.service.PjEvaluateService;
import org.apache.commons.lang3.ArrayUtils;
import com.mortals.framework.util.StringUtils;

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

import com.alibaba.fastjson.JSONObject;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import static com.mortals.framework.ap.SysConstains.*;

import com.mortals.xhx.common.code.*;

/**
 * 评价汇总
 *
 * @author zxfei
 * @date 2024-05-27
 */
@RestController
@RequestMapping("pj/evaluate")
@Slf4j
public class PjEvaluateController extends BaseCRUDJsonBodyMappingController<PjEvaluateService, PjEvaluateEntity, Long> {

    @Autowired
    private ISiteFeign siteFeign;

    @Autowired
    private ICacheService cacheService;
    @Autowired
    private PjEvaluateService pjEvaluateService;


    public PjEvaluateController() {
        super.setModuleDesc("评价汇总");
    }

    @Override
    protected void init(Map<String, Object> model, Context context) {
        this.addDict(model, "pjOption", PjOptionEnum.getEnumMap());
        this.addDict(model, "pjSource", PjSourceEnum.getEnumMap());
        this.addDict(model, "pjxt", PjxtEnum.getEnumMap());
        this.addDict(model, "evaluatetype", EvaluatetypeEnum.getEnumMap());
        this.addDict(model, "eyevaluate", EyevaluateEnum.getEnumMap());
        this.addDict(model, "pjType", PjTypeEnum.getEnumMap());
        super.init(model, context);
    }

    /**
     * @param entity
     * @return
     */
    @Override
    @UnAuth
    public String save(@RequestBody PjEvaluateEntity entity) {
        //获取站点信息
        this.service.getSite(entity);

        //todo 去重
        if (!ObjectUtils.isEmpty(entity.getExtNum())) {
            PjEvaluateQuery pjEvaluateQuery = new PjEvaluateQuery();
            pjEvaluateQuery.setExtNum(entity.getExtNum());
            PjEvaluateEntity pjEvaluateEntity = this.service.selectOne(pjEvaluateQuery);
            if (!ObjectUtils.isEmpty(pjEvaluateEntity)) {
                return JSONObject.toJSONString(Rest.fail("该单号已存在，exetNum:" + entity.getExtNum()));
            }
        }
        return super.save(entity);
    }

    /**
     * @param list
     * @return
     */
    @Override
    @UnAuth
    public String batchSave(@RequestBody List<PjEvaluateEntity> list) {


/*        BatchSavePjTask batchSavePjTask = new BatchSavePjTask(list);

        ThreadPool.getInstance().execute(batchSavePjTask);*/


        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                for (PjEvaluateEntity entity : list) {
                    getSite(entity);
                    entity.setCreateTime(new Date());
                    entity.setCreateUserId(1L);
                    entity.setCreateUserName("admin");

                }
                removeDuplicate(list);
                if (ObjectUtils.isEmpty(list)) return;
                pjEvaluateService.save(list);
            }
        };

        ThreadPool.getInstance().execute(runnable);

        return JSON.toJSONString(Rest.ok("接收成功"));
    }


    //去掉重复的元素
    private void removeDuplicate(List<PjEvaluateEntity> list) {
        //去重 关键exenum
        List<String> extNumList = list.stream().map(m -> m.getExtNum()).filter(f -> f != null).collect(Collectors.toList());

        PjEvaluateQuery pjEvaluateQuery = new PjEvaluateQuery();
        pjEvaluateQuery.setExtNumList(extNumList);
        List<PjEvaluateEntity> pjEvaluateEntities = this.service.find(pjEvaluateQuery);
        if (!ObjectUtils.isEmpty(pjEvaluateEntities)) {
            Set<String> existSet = pjEvaluateEntities.stream().map(item -> item.getExtNum()).collect(Collectors.toSet());
            Iterator<PjEvaluateEntity> iterator = list.iterator();
            while (iterator.hasNext()) {
                PjEvaluateEntity next = iterator.next();
                if (existSet.contains(next.getExtNum())) {
                    log.info("排号重复,extNum={}", next.getExtNum());
                    iterator.remove();
                }
            }
        }
    }


    private void getSite(PjEvaluateEntity entity) {
        if (!ObjectUtils.isEmpty(entity.getSiteId())) {
            RedisTemplate<String, String> baseRedisTemplate = cacheService.selectDbRedisTemplate(1);
            //com:mortals:xhx:module:site:model:SiteEntity  redis调用
            String siteStr = (String) baseRedisTemplate.opsForHash().get("com:mortals:xhx:module:site:model:SiteEntity", String.valueOf(entity.getSiteId()));
            if (!ObjectUtils.isEmpty(siteStr)) {
                SitePdu sitePdu = JSON.parseObject(siteStr, SitePdu.class);

                entity.setSiteId(sitePdu.getId());
                entity.setSiteCode(sitePdu.getSiteCode());
                entity.setSiteName(sitePdu.getSiteName());

            } else if (!ObjectUtils.isEmpty(entity.getSiteCode())) {
                buildSiteBySideCode(entity);
            } else {
                log.info("站点信息不存在,siteId={}", entity.getSiteId());
            }
        } else {
            if (!ObjectUtils.isEmpty(entity.getSiteCode())) {
                buildSiteBySideCode(entity);
            }
        }
    }

    private void buildSiteBySideCode(PjEvaluateEntity entity) {
        RedisTemplate<String, String> baseRedisTemplate = cacheService.selectDbRedisTemplate(1);
        String siteStr = (String) baseRedisTemplate.opsForHash().get("com:mortals:xhx:module:site:model:SiteEntity", entity.getSiteCode());
        if (!ObjectUtils.isEmpty(siteStr)) {
            SitePdu sitePdu = JSON.parseObject(siteStr, SitePdu.class);
            if (!ObjectUtils.isEmpty(sitePdu)) {
                entity.setSiteId(sitePdu.getId());
                entity.setSiteCode(sitePdu.getSiteCode());
                entity.setSiteName(sitePdu.getSiteName());
            } else {
                log.info("站点信息不存在,siteId={}", entity.getSiteId());
            }
        }
    }

}