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

import com.alibaba.fastjson.JSON;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
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.feign.site.ISiteFeign;
import com.mortals.xhx.module.ph.model.PhQueueQuery;
import com.mortals.xhx.module.pj.model.PjEvaluateEntity;
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.ph.model.PhQueueEntity;
import com.mortals.xhx.module.ph.service.PhQueueService;
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("ph/queue")
@Slf4j
public class PhQueueController extends BaseCRUDJsonBodyMappingController<PhQueueService, PhQueueEntity, Long> {

    @Autowired
    private ParamService paramService;
    @Autowired
    private ICacheService cacheService;
    @Autowired
    private ISiteFeign siteFeign;
    @Autowired
    private PhQueueService phQueueService;

    public PhQueueController() {
        super.setModuleDesc("排号汇总");
    }

    @Override
    protected void init(Map<String, Object> model, Context context) {
        this.addDict(model, "style", StyleEnum.getEnumMap());
        this.addDict(model, "wySignin", WySigninEnum.getEnumMap());
        super.init(model, context);
    }


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

        if (!ObjectUtils.isEmpty(entity.getExtNum())) {
            PhQueueQuery phQueueQuery = new PhQueueQuery();
            phQueueQuery.setExtNum(entity.getExtNum());
            PhQueueEntity phQueueEntity = this.service.selectOne(phQueueQuery);
            if (!ObjectUtils.isEmpty(phQueueEntity)) {
                return JSONObject.toJSONString(Rest.fail("该单号已存在，exetNum:" + entity.getExtNum()));
            }
        }

        return super.save(entity);
    }

    @Override
    protected int doListAfter(PhQueueEntity query, Map<String, Object> model, Context context) throws AppException {
        query.setFormernumList(Arrays.asList(""));
        int count = this.service.count(query, context);
        model.put("count", count);
        return super.doListAfter(query, model, context);
    }

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

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                for (PhQueueEntity entity : list) {
                    getSite(entity);
                    entity.setCreateTime(new Date());
                    entity.setCreateUserId(1L);
                    entity.setCreateUserName("admin");
                }
                removeDuplicate(list);

                if (ObjectUtils.isEmpty(list)) return;
                phQueueService.save(list);
            }
        };
        ThreadPool.getInstance().execute(runnable);
        return JSON.toJSONString(Rest.ok("接收成功"));
        //  return super.batchSave(list);
    }

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

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

    private void getSite(PhQueueEntity 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 getSite(PhQueueEntity 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);
                if (!ObjectUtils.isEmpty(sitePdu)) {
                    entity.setSiteCode(sitePdu.getSiteCode());
                    entity.setSiteName(sitePdu.getSiteName());
                } else {
                    log.info("站点信息不存在,siteId={}", entity.getSiteId());
                }
            }

            //feign调用
         *//*   Rest<SitePdu> sitePduRest = siteFeign.info(entity.getSiteId());
            if (YesNoEnum.YES.getValue() == sitePduRest.getCode()) {
                SitePdu sitePdu = sitePduRest.getData();
                if (!ObjectUtils.isEmpty(sitePdu)) {
                    entity.setSiteCode(sitePdu.getSiteCode());
                    entity.setSiteName(sitePdu.getSiteName());
                } else {
                    log.info("站点信息不存在,siteId={}", entity.getSiteId());
                }
            }*//*
        } else {
            if (!ObjectUtils.isEmpty(entity.getSiteCode())) {
                SitePdu pdu = new SitePdu();
                pdu.setSiteCode(entity.getSiteCode());

                Rest<RespData<List<SitePdu>>> sitePduRest = siteFeign.list(pdu);

                if (YesNoEnum.YES.getValue() == sitePduRest.getCode()) {
                    List<SitePdu> list = sitePduRest.getData().getData();
                    if (!ObjectUtils.isEmpty(list)) {
                        entity.setSiteCode(list.get(0).getSiteCode());
                        entity.setSiteName(list.get(0).getSiteName());
                    } else {
                        log.info("站点信息不存在,siteId={}", entity.getSiteId());
                    }
                }
            }
        }
    }*/


    private void buildSiteBySideCode(PhQueueEntity 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());
            }
        }
    }


}