package com.chushang.inspection.terminal.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chushang.common.core.constant.SecurityConstants;
import com.chushang.common.core.exception.utils.AssertUtil;
import com.chushang.common.dict.utils.DictUtils;
import com.chushang.common.mybatis.enums.Operator;
import com.chushang.common.mybatis.page.CommonParam;
import com.chushang.common.mybatis.utils.PageResult;
import com.chushang.common.mybatis.utils.WrapperUtils;
import com.chushang.inspection.project.po.WrkProjectContract;
import com.chushang.inspection.project.vo.CountVO;
import com.chushang.inspection.project.vo.TerminalApp;
import com.chushang.inspection.project.vo.TerminalAppVO;
import com.chushang.inspection.terminal.po.Store;
import com.chushang.inspection.terminal.po.Terminal;
import com.chushang.inspection.terminal.po.TerminalIns;
import com.chushang.inspection.terminal.query.TerminalAppQuery;
import com.chushang.inspection.terminal.query.TerminalQuery;
import com.chushang.inspection.terminal.service.DispatchRecordService;
import com.chushang.inspection.terminal.service.StoreService;
import com.chushang.inspection.terminal.service.TerminalInsService;
import com.chushang.inspection.terminal.service.TerminalService;
import com.chushang.inspection.terminal.vo.StoreTerminalVO;
import com.chushang.inspection.terminal.vo.TerminalVO;
import com.chushang.inspection.utils.BeanCopyUtils;
import com.chushang.inspection.utils.TaskConfigUtils;
import com.chushang.inspection.work.dto.DispatchDTO;
import com.chushang.inspection.work.dto.WrkIcbcJsReceive;
import com.chushang.inspection.work.po.WrkDispatchRecord;
import com.chushang.inspection.work.po.WrkIcbcJs;
import com.chushang.inspection.work.po.WrkInfo;
import com.chushang.inspection.work.query.DispatchQuery;
import com.chushang.system.feign.RemoteDeptService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chushang.inspection.terminal.mapper.TerminalMapper;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
  * @auther: zhao
  * @date: 2024/6/21 16:39
  */
@Service
public class TerminalServiceImpl extends ServiceImpl<TerminalMapper, Terminal> implements TerminalService {
    @Resource
    private StoreService storeService;
    @Resource
    private TerminalInsService terminalInsService;
    @Resource
    private RemoteDeptService remoteDeptService;

    @Resource
    private DispatchRecordService dispatchRecordService;


    @Override
    public PageResult pageList(TerminalQuery query) {
        WrapperUtils.buildSql(query);
        CommonParam commonParam = CommonParam.buildPageRequest();
        Page<StoreTerminalVO> page = new Page<>(commonParam.getPage(), commonParam.getLimit());
        List<StoreTerminalVO> terminalVOS = baseMapper.pageList(query, page);
        if (CollectionUtil.isNotEmpty(terminalVOS)){
            Set<Long> deptIds =
                    terminalVOS.stream().map(StoreTerminalVO::getDeptId).collect(Collectors.toSet());
            Map<Long, String> deptNameByIds
                    = remoteDeptService.getDeptNameByIds(deptIds, SecurityConstants.INNER);
            if (CollectionUtil.isNotEmpty(deptNameByIds)){
                terminalVOS.forEach(s-> s.setDeptName(deptNameByIds.get(s.getDeptId())));
            }
        }
        return new PageResult(terminalVOS, page);
    }

    @Override
    public PageResult dispatchRecord(TerminalQuery query) {
        return dispatchRecordService.pageList(query);
    }

    @Override
    public PageResult queryPageApp(TerminalAppQuery query) {
        CommonParam commonParam = CommonParam.buildPageRequest();
        Page<TerminalAppVO> page = new Page<>(commonParam.getPage(), commonParam.getLimit());
        List<TerminalAppVO> terminalVOS = baseMapper.selectPageApp(query, page);
        return new PageResult(terminalVOS, page);
    }

    /**
     * TODO 终端app
     * @param terminalId
     * @param taskId
     * @return
     */
    @Override
    public TerminalApp getAppById(Long terminalId, Long taskId) {
        String label = TaskConfigUtils.reviewMethod(taskId) == 3 ? "复审通过" : "初审通过";
        String wrkStatus = DictUtils.getDictValue("wrk_status", label);
        Integer state = Convert.toInt(wrkStatus);
        LambdaQueryWrapper<Terminal> terminalSql = new LambdaQueryWrapper<Terminal>()
                .eq(Terminal::getTerminalId, terminalId)
                .eq(Terminal::getTaskId, taskId).last(Operator.LIMIT_ONE.getCharacter());
        Terminal terminal = getOne(terminalSql);
        if (ObjectUtil.isNotEmpty(terminal)){
            Store store = storeService.getById(terminal.getStoreId());

        }
        return null;
    }

    @Override
    public void updateOccupy(Collection<Long> terminalIds, int i) {
        for (Long terminalId : terminalIds) {
            Terminal terminal = getById(terminalId);
            terminal.setOccupy(i);
            baseMapper.updateById(terminal);
        }
    }

    @Override
    public List<DispatchDTO> getStoreByTasKIdOrIds(DispatchQuery query) {
        return baseMapper.getStoreByTasKIdOrIds(query);
    }

    @Override
    public JSONObject save(Store store, WrkIcbcJsReceive dto) {
        Terminal terminal = getOne(new LambdaQueryWrapper<Terminal>()
                .eq(Terminal::getStoreId, store.getStoreId())
                .eq(Terminal::getTerminalNo, dto.getTermId())
        );
        TerminalIns terminalIns;
        if (terminal == null){
            terminal = new Terminal().save(store, dto);
            save(terminal);
            terminalIns = new TerminalIns();
            terminalIns.setTerminalId(terminal.getTerminalId());
            terminalIns.setIsEnter(2);
            terminalIns.setCreateBy(store.getCreateBy());
            terminalInsService.save(terminalIns);
            return JSONObject.of("terminal", terminal, "terminalIns", terminalIns);
        }else {
            terminalIns = terminalInsService.getById(terminal.getTerminalId());
        }
        return JSONObject.of("terminal", terminal, "terminalIns", terminalIns);
    }

    @Override
    public JSONObject getTerMap(Long terminalId) {
        return JSONObject.of("terminal", getById(terminalId), "terminalIns", terminalInsService.getById(terminalId));
    }

    @Override
    public List<CountVO> countByProjectIds(Set<Long> projectIds) {
        return baseMapper.countByProjectIds(projectIds);
    }

    @Override
    public JSONObject save(Store store, WrkIcbcJs w) {
        Terminal terminal = getOne(new LambdaQueryWrapper<Terminal>()
                .eq(Terminal::getStoreId, store.getStoreId())
                .eq(Terminal::getTerminalNo, w.getTermId())
        );
        TerminalIns terminalIns;
        if (terminal == null){
            terminal = new Terminal().save(store, w);
            save(terminal);
            terminalIns = new TerminalIns();
            terminalIns.setTerminalId(terminal.getTerminalId());
            terminalIns.setIsEnter(2);
            terminalIns.setCreateBy(store.getCreateBy());
            terminalInsService.save(terminalIns);
            return JSONObject.of("terminal", terminal, "terminalIns", terminalIns);
        }else {
            terminalIns = terminalInsService.getById(terminal.getTerminalId());
        }
        return JSONObject.of("terminal", terminal, "terminalIns", terminalIns);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public long updateTerminalAndStore(TerminalQuery query) {
        Terminal curTerminal = getById(query.getTerminalId());
        AssertUtil.invalidate(ObjectUtil.isEmpty(curTerminal), "未找寻到对应的终端信息");
        curTerminal.setTerminalNo(query.getTerminalNo());
        curTerminal.setTerminalSn(query.getTerminalSn());
        curTerminal.setTerminalAddress(query.getTerminalAddress());
        curTerminal.setTerminalModel(query.getTerminalModel());
        curTerminal.setTerminalType(query.getTerminalType());
        curTerminal.setTerminalSource(query.getTerminalSource());
        updateById(curTerminal);
        Store store = new Store();
        store.setStoreId(curTerminal.getStoreId());
        store.setStoreNo(query.getStoreNo());
        store.setStoreName(query.getStoreName());
        store.setState(query.getStoreState());
        storeService.updateById(store);
        return query.getTerminalId();
    }

}
