package com.tofly.feesapi.cbgl.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.tofly.common.core.util.StringUtil;
import com.tofly.feesapi.bjgl.entity.YhCbkxx;
import com.tofly.feesapi.bjgl.service.YhCbkxxService;
import com.tofly.feesapi.cbgl.entity.ZnbZlLog;
import com.tofly.feesapi.cbgl.entity.dto.ZnbCbLogFilter;
import com.tofly.feesapi.cbgl.entity.dto.ZnbFkFilter;
import com.tofly.feesapi.cbgl.entity.dto.ZnbZlLogFilter;
import com.tofly.feesapi.cbgl.entity.vo.ZnbZlLogSelect;
import com.tofly.feesapi.cbgl.mapper.ZnbZlLogMapper;
import com.tofly.feesapi.cbgl.service.IZnbZlLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.feesapi.common.core.dto.PageDto;
import com.tofly.feesapi.common.core.vo.PageResult;
import com.tofly.feesapi.common.enums.ZnbZlEnum;
import com.tofly.feesapi.common.exception.FeesErrorCode;
import com.tofly.feesapi.common.exception.FeesException;

import com.tofly.feesapi.common.util.ToolsUtils;
import com.tofly.feesapi.security.util.SecurityUtils;
import com.tofly.feesapi.yhgl.entity.YhKhjbxx;
import com.tofly.feesapi.yhgl.service.YhKhjbxxService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toMap;

/**
 * <p>
 * 智能表指令明细 服务实现类
 * </p>
 *
 * @author decai
 * @since 2024-04-10
 */
@Service
public class ZnbZlLogServiceImpl extends ServiceImpl<ZnbZlLogMapper, ZnbZlLog> implements IZnbZlLogService {


    @Autowired
    private YhKhjbxxService khjbxxService;

    @Autowired
    private YhCbkxxService cbkxxService;


    @Autowired
    private TransactionTemplate transactionTemplate;

    @Override
    public PageResult<ZnbZlLogSelect> getPage(PageDto pageDto, ZnbZlLogFilter filter) {

//        if (StringUtils.isNotEmpty(filter.getZltype())) {
//            if (filter.getZltype().equals("znb_da_log")) {
//                filter.setZltype("0");
//            }
//            if (filter.getZltype().equals("znb_zl_log")) {
//                filter.setZltype("1");
//            }
//            if (filter.getZltype().equals("znb_cz_log")) {
//                filter.setZltype("2");
//            }
//        }


        PageDto<ZnbZlLogSelect> page = this.baseMapper.getPage(pageDto, filter);
        if (!StringUtil.isNull(page)) {
            page.getRecords().forEach(i -> {
                i.setZlvalue(getZlValue(i.getZltype(), i.getZlvalue()));
                i.setZltype(fkType(i.getZltype().toLowerCase()));
            });
        }
        return page.toVo();
    }


    private String fkType(String name) {
    Map<String, ZnbZlEnum> lookup = Stream.of(ZnbZlEnum.values())
                .collect(toMap(ZnbZlEnum::getValue, Function.identity()));
        ZnbZlEnum zlenums = lookup.get(name);
        if(zlenums==null){
            return  "";
        }
        return zlenums.getName();
    }

    private String getZlValue(String type, String value) {
        String retValue = "";
        if (type.equals("1")) {
            switch (value) {
                case "1":
                    retValue = "开阀";
                    break;
                case "0":
                    retValue = "关阀";
                    break;
            }
        }
        return retValue;
    }
    @Override
    public List<ZnbZlLogSelect> getList(ZnbCbLogFilter filter) {
        return this.baseMapper.getList(filter);
    }

    @Override
    public boolean ZnbFk(ZnbFkFilter filter) {
        List<String> yhbhs = filter.getYhbhs();

//        if (yhbhs.size() == 0) {
//            throw new FeesException("未查询到相关操作用户", FeesErrorCode.BUSINESS_ERROR);
//        }
//        List<YhKhjbxx> yhList = khjbxxService.lambdaQuery().in(YhKhjbxx::getYhbh, yhbhs).list();
//        if (yhList.isEmpty()) {
//            throw new FeesException("未查询到可操作的用户", FeesErrorCode.BUSINESS_ERROR);
//        }
        List<String> sbbhs = filter.getSbbhs();
        if (sbbhs.size() == 0) {
            throw new FeesException("请选择需要操作的水表！", FeesErrorCode.BUSINESS_ERROR);
        }
        List<YhCbkxx> cbkList = cbkxxService.lambdaQuery().in(YhCbkxx::getSbbh, sbbhs).list();
        if (cbkList.isEmpty()) {
            throw new FeesException("未查询到可操作的表", FeesErrorCode.BUSINESS_ERROR);
        }
        return fk1(cbkList, filter.getZltype(), SecurityUtils.getUserId()) == 1;
    }

    private int fk(List<YhKhjbxx> yhList, String zltype, Long czry) {
        int rlt = transactionTemplate.execute(status -> {
            try {
                String pch = UUID.randomUUID().toString();
                for (YhKhjbxx khjbxx : yhList) {
                    List<YhCbkxx> cbkList = cbkxxService.lambdaQuery().in(YhCbkxx::getYhbh, khjbxx.getYhbh()).list();
                    for (YhCbkxx cbk : cbkList) {
                        ZnbZlLog log = new ZnbZlLog();
                        log.setYhbh(cbk.getYhbh());
                        log.setCbkh(cbk.getCbkh());
                        log.setCbkid(cbk.getCbkid());
                        log.setPch(pch);
                        log.setSccj(cbk.getSbsccj());
                        log.setSsgs(khjbxx.getSsgs());
                        log.setCzry(czry.toString());
                        log.setCzsj(LocalDateTime.now());
                        log.setClLock("0");
                        log.setClCljg("0");
                        log.setZltype("1");
                        log.setZlvalue(zltype);
                        this.save(log);
                    }
                }
                return 1;
            } catch (Exception e) {
                status.setRollbackOnly();
                throw e;
            }
        });
        return rlt;
    }

    private int fk1(List<YhCbkxx> cbkList, String zltype, Long czry) {
        int rlt = transactionTemplate.execute(status -> {
            try {
                String pch = UUID.randomUUID().toString();
                for (YhCbkxx cbk : cbkList) {
                    //作废之前没有执行的指令
                    this.lambdaUpdate()
                            .set(ZnbZlLog::getClCljg, "-2")
                            .eq(ZnbZlLog::getCbkid, cbk.getCbkid())
                            .eq(ZnbZlLog::getClLock, "0")
                            .eq(ZnbZlLog::getClCljg, "0")
                            .update();

                    ZnbZlLog log = new ZnbZlLog();
                    log.setYhbh(cbk.getYhbh());
                    log.setCbkh(cbk.getCbkh());
                    log.setCbkid(cbk.getCbkid());
                    log.setBjbh(cbk.getSbbh());
                    log.setPch(pch);
                    log.setSccj(cbk.getSbsccj());
                    log.setSsgs("1");
                    log.setCzry(czry.toString());
                    log.setCzsj(LocalDateTime.now());
                    log.setClLock("0");
                    log.setClCljg("0");
                    log.setZltype("1");
                    log.setZlvalue(zltype);
                    //log.setNbimei(cbk.getNbimei());
                    this.save(log);
                }
                return 1;
            } catch (Exception e) {
                status.setRollbackOnly();
                throw e;
            }
        });
        return rlt;
    }

    /**
     * 重新推送指令
     *
     * @param znbZlLogFilter
     * @return
     */

    public boolean reZnbZlSend(ZnbZlLogFilter znbZlLogFilter) {

        if (StringUtils.isEmpty(znbZlLogFilter.getId())) {
            return false;
        }
        ZnbZlLog znbZlLog = this.baseMapper.selectById(znbZlLogFilter.getId());
        ZnbZlLog newZlb = new ZnbZlLog();

        BeanUtils.copyProperties(znbZlLog, newZlb);

        newZlb.setId(ToolsUtils.getGuid());
        newZlb.setCzsj(LocalDateTime.now());
        newZlb.setClCljg("0");
        newZlb.setClLock("0");
        newZlb.setClClry("");
        newZlb.setClClsj(null);
        newZlb.setClRecode(null);
        newZlb.setClRemessage(null);
        newZlb.setCzry(SecurityUtils.getUserId().toString());
        newZlb.setCzry(SecurityUtils.getUserName());
        boolean isAdd = this.baseMapper.insert(newZlb) > 0;
        return isAdd;

    }

}
