package com.mosty.base.manager.service.impl;

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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mosty.base.manager.mapper.TbJcglJyqxMapper;
import com.mosty.base.manager.remote.TbBaseAdaptRemoteService;
import com.mosty.base.manager.service.TbJcglJyqxService;
import com.mosty.base.manager.service.TbJcglZbjlService;
import com.mosty.base.model.dto.qwzx.AppSearchQuery;
import com.mosty.base.model.entity.jcgl.TbJcglJyqx;
import com.mosty.base.model.entity.jcgl.TbJcglJz;
import com.mosty.base.model.entity.jcgl.TbJcglZbjl;
import com.mosty.base.model.entity.jcgl.TbJcglZnzb;
import com.mosty.base.model.query.jcgl.TbJcglJyqxQuery;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.base.utils.DateUtils;
import com.mosty.base.utils.UUIDGenerator;
import com.mosty.common.base.exception.BusinessException;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import com.mosty.common.util.PermissionsUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@AllArgsConstructor
@Service
public class TbJcglJyqxServiceImpl extends ServiceImpl<TbJcglJyqxMapper, TbJcglJyqx>
        implements TbJcglJyqxService {

    private final TbBaseAdaptRemoteService tbBaseAdaptRemoteService;
    private final TbJcglZbjlService tbJcglZbjlService;

    @Override
    public void xfZnzb(TbJcglJyqx jyqx) {
        if (StringUtils.isNotBlank(jyqx.getId()) && StringUtils.isNotBlank(jyqx.getSsbmdm())) {
            TbJcglJyqx tbJcglJyqx = this.baseMapper.selectById(jyqx.getId());
            //下发修改数量
//            tbJcglJyqx.setSl(tbJcglJyqx.getSl() - jyqx.getSl() < 0 ? 0 : tbJcglJyqx.getSl() - jyqx.getSl());
            tbJcglJyqx.setXfs(tbJcglJyqx.getXfs() + jyqx.getSl());
            this.baseMapper.updateById(tbJcglJyqx);
            //保存下发数据
            DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(jyqx.getSsbmdm());
            if (ObjectUtils.isNotEmpty(dept)) {
                tbJcglJyqx.setSsbm(dept.getDeptname());
                tbJcglJyqx.setSsbmid(dept.getDeptid());
                tbJcglJyqx.setSsbmdm(dept.getDeptcode());
                tbJcglJyqx.setSsxgajdm(dept.getFxjcode());
                tbJcglJyqx.setSsxgajid(dept.getFxjid());
                tbJcglJyqx.setSsxgaj(dept.getFxjname());
                tbJcglJyqx.setSssgaj(dept.getDszname());
                tbJcglJyqx.setSssgajdm(dept.getDszcode());
                tbJcglJyqx.setSssgajid(dept.getDszid());
            }
            tbJcglJyqx.setXtSjly("1");
            tbJcglJyqx.setId(UUIDGenerator.getUUID());
            tbJcglJyqx.setXfid(jyqx.getId());
            tbJcglJyqx.setSfbs("0");
            tbJcglJyqx.setSl(jyqx.getSl());
            tbJcglJyqx.setXfs(0);
            tbJcglJyqx.setBss(0);
            tbJcglJyqx.setXtCjsj(new Timestamp(System.currentTimeMillis()));
            //存入装备日志
            addZbjl(tbJcglJyqx, "2");
            this.baseMapper.insert(tbJcglJyqx);
        }
    }

    @Override
    public void htZnzb(String id, long sl) {
        if (StringUtils.isNotBlank(id)) {
            TbJcglJyqx tbJcglJyqx = this.baseMapper.selectById(id);
            //查询下发一起那个数据
            TbJcglJyqx tbJcglJyqx1 = this.baseMapper.selectById(tbJcglJyqx.getXfid());
            if (ObjectUtils.isNotEmpty(tbJcglJyqx1)) {
//                tbJcglJyqx1.setSl(tbJcglJyqx1.getSl() + tbJcglJyqx.getSl());
                tbJcglJyqx1.setXfs((tbJcglJyqx1.getXfs() - sl) < 0 ? 0 : tbJcglJyqx1.getXfs() - sl);
                this.baseMapper.updateById(tbJcglJyqx1);
            }
            //比较当前数量  等于库存删除
            if (sl >= tbJcglJyqx.getSl()) {
                this.baseMapper.deleteById(id);
            } else {
                tbJcglJyqx.setSl(tbJcglJyqx.getSl() - sl);
                //修改以前的数量
                this.baseMapper.updateById(tbJcglJyqx);
            }
            //存入装备日志
            addZbjl(tbJcglJyqx, "3");
        }
    }

    @Override
    public void bsZnzb(String id, long sl) {
        if (StringUtils.isNotBlank(id)) {
            TbJcglJyqx tbJcglJyqx = this.baseMapper.selectById(id);
            //比较当前数量  等于库存删除
            if (sl >= tbJcglJyqx.getSl()) {
                tbJcglJyqx.setSfbs("1");
                tbJcglJyqx.setBss(tbJcglJyqx.getSl());
//                tbJcglJyqx.setSl(0);
            } else {
//                tbJcglJyqx.setSl(tbJcglJyqx.getSl() - sl);
                tbJcglJyqx.setBss(tbJcglJyqx.getBss() + sl);
//                tbJcglJyqx.setXtSjly("1");
//                tbJcglJyqx.setId(UUIDGenerator.getUUID());
//                tbJcglJyqx.setXfid(id);
//                tbJcglJyqx.setSfbs("1");
//                tbJcglJyqx.setSl(sl);
//                tbJcglJyqx.setXtCjsj((new Timestamp(System.currentTimeMillis())));
//                this.baseMapper.insert(tbJcglJyqx);
            }
            this.baseMapper.updateById(tbJcglJyqx);
            //存入装备日志
            addZbjl(tbJcglJyqx, "1");
        }
    }


    public void addZbjl(TbJcglJyqx jyqx, String sjly) {
        TbJcglZbjl dto = new TbJcglZbjl();
        dto.setSjbm("tb_jcgl_jyqx");
        dto.setGlid(jyqx.getId());
        dto.setSjly(sjly);
        dto.setZblx("2");
        UserInfo user = UserInfoManager.get();
        dto.setCzr(user.getUserName());
        dto.setCzrSfz(user.getIdEntityCard());
        dto.setCzrSsbmid(String.valueOf(user.getDeptId()));
        dto.setCzrSsbm(user.getDeptName());
        dto.setCzrSsbmdm(user.getDeptCode());
        dto.setXfSsbmid(jyqx.getSsbmid());
        dto.setXfSsbm(jyqx.getSsbm());
        dto.setXfSsbmdm(jyqx.getSsbmdm());
        dto.setExt(String.valueOf(jyqx.getSl()));
        tbJcglZbjlService.addEntity(dto);
    }


    @Override
    public void addJyqx(TbJcglJyqx jyqx) {
        if (StringUtils.isNotBlank(jyqx.getScode())) {
            //查询设备类型信息
            List<TbJcglJyqx> jyqxList = this.baseMapper.selectList(
                    new QueryWrapper<TbJcglJyqx>()
                            .eq("qxbh", jyqx.getQxbh())
                            .eq("xt_scbz", 0)
            );
            if (jyqxList.size() > 0) {
                throw new BusinessException("设备编号已存在");
            } else {
                jyqx.setId(UUIDGenerator.getUUID());
                if (StringUtils.isNotBlank(jyqx.getSsbmdm())) {
                    DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(jyqx.getSsbmdm());
                    jyqx.setSsbm(dept.getDeptname());
                    jyqx.setSsbmid(dept.getDeptid());
                    jyqx.setSsbmdm(dept.getDeptcode());
                    jyqx.setSsxgajdm(dept.getFxjcode());
                    jyqx.setSsxgajid(dept.getFxjid());
                    jyqx.setSsxgaj(dept.getFxjname());
                    jyqx.setSssgaj(dept.getDszname());
                    jyqx.setSssgajdm(dept.getDszcode());
                    jyqx.setSssgajid(dept.getDszid());
                }
                jyqx.setXtSjly("1");
                this.baseMapper.insert(jyqx);
            }
        }
    }


    @Override
    public IPage<TbJcglJyqx> selectJyqx(TbJcglJyqx jyqx, IPage<TbJcglJyqx> page) {
        QueryWrapper<TbJcglJyqx> qw = new QueryWrapper<>();
//        UserInfo userInfo = UserInfoManager.get();
//        PermissionsUtil.queryWrapperUtil(qw, userInfo);
        jyqx.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(jyqx.getSsbmdm(), null));
        if (jyqx != null) {
            qw.lambda()
//                    .eq(StringUtils.isNotBlank(jyqx.getSsbmdm()), TbJcglJyqx::getSsbmdm, jyqx.getSsbmdm())
//                    .eq(StringUtils.isNotBlank(jyqx.getSsbmid()), TbJcglJyqx::getSsbmid, jyqx.getSsbmid())
                    .eq(StringUtils.isNotBlank(jyqx.getScode()), TbJcglJyqx::getScode, jyqx.getScode())
                    .like(!StringUtils.isEmpty(jyqx.getQxMc()), TbJcglJyqx::getQxMc, jyqx.getQxMc())
                    .likeRight(!StringUtils.isEmpty(jyqx.getSsbmdm()), TbJcglJyqx::getSsbmdm, jyqx.getSsbmdm())
                    .eq(jyqx.getCgrq() != null, TbJcglJyqx::getCgrq, jyqx.getCgrq())
                    .eq(TbJcglJyqx::getXtScbz, 0)
                    .orderByDesc(TbJcglJyqx::getXtCjsj);
        }

        IPage<TbJcglJyqx> tbJcglJyqxIPage = this.baseMapper.selectPage(page, qw);

        List<TbJcglJyqx> records = tbJcglJyqxIPage.getRecords();
//        if (!CollectionUtils.isEmpty(records)) {
//            for (TbJcglJyqx qx : records) {
//                //查询是否有下发数据
//                List<TbJcglJyqx> tbJcglJyqxes = this.baseMapper.selectList(new LambdaQueryWrapper<TbJcglJyqx>().eq(TbJcglJyqx::getXfid, qx.getXfid()));
//                if (!CollectionUtils.isEmpty(tbJcglJyqxes)) {
//                    qx.setJyqxList(tbJcglJyqxes);
//                    int bss = 0;
//                    int xfs = 0;
//                    for (TbJcglJyqx xfqx : tbJcglJyqxes) {
//                        if (StringUtils.isNotBlank(xfqx.getSfbs()) || xfqx.getSfbs().equals("0")) {
//                            //下发
//                            xfs += xfqx.getSl();
//                        } else {
//                            //报损
//                            bss += xfqx.getSl();
//                        }
//                    }
//                    qx.setBss(bss);
//                    qx.setXfs(xfs);
//                }
//            }
//        }
        return tbJcglJyqxIPage;
    }

    @Override
    public void updateJyqx(TbJcglJyqx jyqx) {
        if (StringUtils.isBlank(jyqx.getSsbmdm())) throw new BusinessException("请选择所属部门！！");
        DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(jyqx.getSsbmdm());
        if (ObjectUtils.isNotEmpty(dept)) {
            jyqx.setSsbm(dept.getDeptname());
            jyqx.setSsbmid(dept.getDeptid());
            jyqx.setSsbmdm(dept.getDeptcode());
            jyqx.setSsxgajdm(dept.getFxjcode());
            jyqx.setSsxgajid(dept.getFxjid());
            jyqx.setSsxgaj(dept.getFxjname());
            jyqx.setSssgaj(dept.getDszname());
            jyqx.setSssgajdm(dept.getDszcode());
            jyqx.setSssgajid(dept.getDszid());
        }

//        if (StringUtils.isNotBlank(jyqx.getQxbh())) {
        //查询设备类型信息
//            List<TbJcglJyqx> jyqxList = this.baseMapper.selectList(
//                    new QueryWrapper<TbJcglJyqx>()
//                            .eq("qxbh", jyqx.getQxbh())
//                            .ne("id", jyqx.getId())
//                            .eq("xt_scbz", 0)
//            );
//            if (jyqxList.size() > 0) throw new BusinessException("设备编号已存在");
        this.baseMapper.updateById(jyqx);
//        }
    }

    @Override
    public void deleteJyQxzb(List<String> id) {
        //批量注销
        TbJcglJyqx tbJcglJyqx = new TbJcglJyqx();
        tbJcglJyqx.setXtScbz("1");
        if (id.size() > 0) {
            this.baseMapper.deleteZb(id);
        }
    }

    @Override
    public Object selectJyqxXq(String id) {
        return this.baseMapper.selectById(id);
    }

    @Override
    public IPage<TbJcglJyqx> selectDqjyqx(TbJcglJyqxQuery jyqx, IPage<TbJcglJyqx> page) {
        SimpleDateFormat defaultDateFormatter = new SimpleDateFormat("yyyy-MM-dd");
        String currentDate = DateUtils.getSystemDateString();
        Date dqDate = DateUtils.stepMonth(new Date(), 2);
        String dqsj = defaultDateFormatter.format(dqDate);
        QueryWrapper<TbJcglJyqx> qw = new QueryWrapper<>();
//        UserInfo userInfo = UserInfoManager.get();
//        PermissionsUtil.queryWrapperUtil(qw, userInfo);

        jyqx.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(jyqx.getSsbmdm(), null));
        if (jyqx != null) {
            qw.lambda()
//                    .eq(StringUtils.isNotBlank(jyqx.getSsbmdm()), TbJcglJyqx::getSsbmdm, jyqx.getSsbmdm())
//                    .eq(StringUtils.isNotBlank(jyqx.getSsbmid()), TbJcglJyqx::getSsbmid, jyqx.getSsbmid())
                    .eq(StringUtils.isNotBlank(jyqx.getScode()), TbJcglJyqx::getScode, jyqx.getScode())
                    .eq(TbJcglJyqx::getXtScbz, 0)
                    .eq(StringUtils.isNotBlank(jyqx.getCgrq()), TbJcglJyqx::getCgrq, jyqx.getCgrq())
                    .likeRight(StringUtils.isNotBlank(jyqx.getSsbmdm()), TbJcglJyqx::getSsbmdm, jyqx.getSsbmdm())
                    .ge(TbJcglJyqx::getDqsj, currentDate)
                    .ge(TbJcglJyqx::getDqsj, currentDate)
                    .le(TbJcglJyqx::getDqsj, dqsj);
        }
        return this.baseMapper.selectPage(page, qw);
    }

    @Override
    public String importData(List<TbJcglJyqx> jyqxList, boolean updateSupport) {
        if (CollectionUtils.isEmpty(jyqxList)) {
            throw new BusinessException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TbJcglJyqx jyqx : jyqxList) {
            try {
                if (StringUtils.isEmpty(jyqx.getQxMc())
                        || StringUtils.isEmpty(jyqx.getQxbh())
                        || StringUtils.isEmpty(jyqx.getScode())
                        || StringUtils.isEmpty(jyqx.getQxPch())
                        || ObjectUtils.isEmpty(jyqx.getDqsj())
                        || ObjectUtils.isEmpty(jyqx.getCgrq())
                ) {
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、器械名称： " + jyqx.getQxMc() + " 信息不全,请仔细核查！");
                    continue;
                }
                DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(jyqx.getSsbmdm());
                if (ObjectUtils.isNotEmpty(dept)) {
                    jyqx.setSsbm(dept.getDeptname());
                    jyqx.setSsbmid(dept.getDeptid());
                    jyqx.setSsbmdm(dept.getDeptcode());
                    jyqx.setSsxgajdm(dept.getFxjcode());
                    jyqx.setSsxgajid(dept.getFxjid());
                    jyqx.setSsxgaj(dept.getFxjname());
                    jyqx.setSssgaj(dept.getDszname());
                    jyqx.setSssgajdm(dept.getDszcode());
                    jyqx.setSssgajid(dept.getDszid());
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、所属部门编码不存在 " + jyqx.getSsbmdm() + " 信息不全,请仔细核查！");
                    continue;
                }
                jyqx.setSl(jyqx.getSl() <= 0 ? 1 : jyqx.getSl());
                jyqx.setXtSjzt("1");
                jyqx.setXtScbz("0");
                jyqx.setZbzt("1");
                jyqx.setId(UUIDGenerator.getUUID());
                this.baseMapper.insert(jyqx);
                successNum++;
                successMsg.append("<br/>" + successNum + "、器械名称 " + jyqx.getQxMc() + " 更新成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、器械名称 " + jyqx.getQxMc() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public IPage<TbJcglJyqx> getJyqxList(AppSearchQuery dto) {
        UserInfo user = UserInfoManager.get();
        LambdaQueryWrapper<TbJcglJyqx> wrapper = new LambdaQueryWrapper<TbJcglJyqx>()
                .eq(TbJcglJyqx::getXtSjzt, "1");
        //本部门
        if ("1".equals(dto.getType())) {
            wrapper.like(StringUtils.isNotBlank(dto.getKeyword()), TbJcglJyqx::getQxMc, dto.getKeyword())
                    .eq(TbJcglJyqx::getSsbmdm, String.valueOf(user.getDeptCode()))
                    .orderByAsc(TbJcglJyqx::getXtCjsj);
        } else {
            String ssbm = this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(), null);
            wrapper.likeRight(StringUtils.isNotBlank(ssbm), TbJcglJyqx::getSsbmdm, ssbm)
                    .and(StringUtils.isNotBlank(dto.getKeyword()),
                            it -> it.like(TbJcglJyqx::getQxMc, dto.getKeyword())
                                    .or()
                                    .like(TbJcglJyqx::getSsbm, dto.getKeyword())
                    );
        }
        return this.baseMapper.selectPage(new Page<>(dto.getPageCurrent(), dto.getPageSize()), wrapper);
    }
}
