package yangtz.cs.liu.campus.service.impl.schoolEquipment;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yangtz.cs.liu.campus.domain.schoolEquipment.*;
import yangtz.cs.liu.campus.mapper.schoolEquipment.*;
import yangtz.cs.liu.campus.service.schoolEquipment.IEquipmentLedgerService;
import yangtz.cs.liu.campus.vo.schoolEquipment.SchoolEquipmentLedgerVo;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Service
public class EquipmentLedgerServiceImpl extends ServiceImpl<EquipmentLedgerMapper, SchoolEquipmentLedger> implements IEquipmentLedgerService {

    @Autowired
    private EquipmentLedgerMapper equipmentLedgerMapper;
    @Autowired
    private EncodeMapper encodeMapper;
    @Autowired
    private InStockMapper inStockMapper;
    @Autowired
    private OutStockMapper outStockMapper;
    @Autowired
    private ProductCategoryMapper productCategoryMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查看设备台账列表
     * @param schoolEquipmentLedgerVo
     * @return
     */
    @Override
    public List<SchoolEquipmentLedger> selectSchoolEquipmentLedgerList(SchoolEquipmentLedgerVo schoolEquipmentLedgerVo) {
        List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        for (SysRole role : roles) {
            if (role.getRoleKey().equals("admin")){
                return equipmentLedgerMapper.selectSchoolEquipmentLedgerList(schoolEquipmentLedgerVo);
            }else if (role.getRoleKey().equals("productCategoryAdmin")){
                schoolEquipmentLedgerVo.setAdminId(SecurityUtils.getLoginUser().getUser().getUserId());
                return equipmentLedgerMapper.selectSchoolEquipmentLedgerListGr(schoolEquipmentLedgerVo);
            }
        }
        if (user.isAdmin()){
            return equipmentLedgerMapper.selectSchoolEquipmentLedgerList(schoolEquipmentLedgerVo);
        }
        return new ArrayList<>();
    }

    /**
     * 查看设备台账详细信息
     * @param id
     * @return
     */
    @Override
    public SchoolEquipmentLedger selectSchoolEquipmentLedgerById(Long id) {
        return equipmentLedgerMapper.selectById(id);
    }

    /**
     * 生成自编码
     * @return
     */
    @Override
    public String getCode(String code) {
        //业务分类 10
        String ywfl = "10";
        //分类
        String fl = code.substring(0, 4);
        //获取当前年
        String year = String.valueOf(LocalDate.now().getYear());
        //定义序列号
        String orderNum = "00001";
        //自编码
        long encode = Long.parseLong(ywfl + fl + year + orderNum);
        while (true){
            LambdaQueryWrapper<SchoolEncode> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SchoolEncode::getYwfl,ywfl).eq(SchoolEncode::getFl,fl).eq(SchoolEncode::getYear,year).eq(SchoolEncode::getOrderNumber,orderNum);
            List<SchoolEncode> schoolEncodes = encodeMapper.selectList(wrapper);
            if (schoolEncodes.size() > 0){
                encode ++;
                orderNum = String.valueOf(encode).substring(10);
            }else {
                SchoolEncode schoolEncode = new SchoolEncode();
                schoolEncode.setYwfl(ywfl);
                schoolEncode.setFl(fl);
                schoolEncode.setYear(year);
                schoolEncode.setOrderNumber(orderNum);
                encodeMapper.insert(schoolEncode);
                break;
            }
        }

        return String.valueOf(encode);
    }

    /**
     * 入库设备台账信息
     * @param schoolEquipmentLedger
     * @return
     */
    @Override
    @Transactional
    public int insertSchoolEquipmentLedger(SchoolEquipmentLedger schoolEquipmentLedger) {
        if (StringUtils.isNotNull(schoolEquipmentLedger.getUseId())){
            if (schoolEquipmentLedger.getUseId() == -1L){
                schoolEquipmentLedger.setUseName("物理实验室");
            }else if (schoolEquipmentLedger.getUseId() == -2L){
                schoolEquipmentLedger.setUseName("化学实验室");
            }else if (schoolEquipmentLedger.getUseId() == -3L){
                schoolEquipmentLedger.setUseName("生物实验室");
            }else if (schoolEquipmentLedger.getUseId() == -4L){
                schoolEquipmentLedger.setUseName("技术部门");
            }else if (schoolEquipmentLedger.getUseId() == -5L){
                schoolEquipmentLedger.setUseName("艺术");
            }else if (schoolEquipmentLedger.getUseId() == -6L){
                schoolEquipmentLedger.setUseName("级部");
            }else {
                String userName = sysUserMapper.selectUserById(schoolEquipmentLedger.getUseId()).getUserName();
                schoolEquipmentLedger.setUseName(userName);
            }

        }
        if (schoolEquipmentLedger.getClassificationCode().length() < 4){
            throw new ServiceException("分类编码至少选择至二级分类！");
        }
        //生成自编码
        String code = getCode(schoolEquipmentLedger.getClassificationCode());
        schoolEquipmentLedger.setEncode(code);
        schoolEquipmentLedger.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
        schoolEquipmentLedger.setCreateTime(DateUtils.getNowDate());
        int i = equipmentLedgerMapper.insert(schoolEquipmentLedger);
        //新增入库信息
        SchoolInStock schoolInStock = new SchoolInStock();
        schoolInStock.setEquipmentId(schoolEquipmentLedger.getId());
        schoolInStock.setInStockTime(DateUtils.getNowDate());
        schoolInStock.setRemark(schoolEquipmentLedger.getRemark());
        inStockMapper.insert(schoolInStock);
        return i;
    }

    /**
     * 修改设备台账信息
     * @param schoolEquipmentLedger
     * @return
     */
    @Override
    @Transactional
    public int updateSchoolEquipmentLedger(SchoolEquipmentLedger schoolEquipmentLedger) {
        if (StringUtils.isNotNull(schoolEquipmentLedger.getUseId())){
            if (schoolEquipmentLedger.getUseId() == -1L){
                schoolEquipmentLedger.setUseName("物理实验室");
            }else if (schoolEquipmentLedger.getUseId() == -2L){
                schoolEquipmentLedger.setUseName("化学实验室");
            }else if (schoolEquipmentLedger.getUseId() == -3L){
                schoolEquipmentLedger.setUseName("生物实验室");
            }else if (schoolEquipmentLedger.getUseId() == -4L){
                schoolEquipmentLedger.setUseName("技术部门");
            }else if (schoolEquipmentLedger.getUseId() == -5L){
                schoolEquipmentLedger.setUseName("艺术");
            }else if (schoolEquipmentLedger.getUseId() == -6L){
                schoolEquipmentLedger.setUseName("级部");
            }else {
                String userName = sysUserMapper.selectUserById(schoolEquipmentLedger.getUseId()).getUserName();
                schoolEquipmentLedger.setUseName(userName);
            }
        }
        schoolEquipmentLedger.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
        schoolEquipmentLedger.setUpdateTime(DateUtils.getNowDate());
        return equipmentLedgerMapper.updateById(schoolEquipmentLedger);
    }

    /**
     * 批量出库设备台账信息
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public int outSchoolEquipmentLedger(Long[] ids) {
        int i = equipmentLedgerMapper.outSchoolEquipmentLedger(ids);
        for (Long id : ids) {
            //新增出库信息
            SchoolOutStock schoolOutStock = new SchoolOutStock();
            schoolOutStock.setEquipmentId(id);
            schoolOutStock.setOutStockTime(DateUtils.getNowDate());
            outStockMapper.insert(schoolOutStock);
        }
        return i;
    }

    /**
     * 导入设备台账
     * @param list
     * @return
     */
    @Override
    public String importExamDetail(List<SchoolEquipmentLedger> list) {
        // 准备记录日志数据
        int successNum = 0;
        StringBuilder successMsg = new StringBuilder();
        for (SchoolEquipmentLedger schoolEquipmentLedger : list) {
            insertSchoolEquipmentLedger(schoolEquipmentLedger);
            successNum ++;
        }
        successMsg.insert(0, "恭喜您，数据已导入成功！共有 " + successNum + " 条，数据如下：");
        return successMsg.toString();
    }

    /**
     * 校验
     * @param list
     */
    @Override
    public void checkImport(List<SchoolEquipmentLedger> list) {
        //2024-03-15 wj add
        //查询分类编码是否重复
        SchoolProductCategory wrapper = new SchoolProductCategory();
        List<SchoolProductCategory> schoolProductCategories = productCategoryMapper.selectProductCategoryList(wrapper);


        //是否为空
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("导入数据不能为空");
        }
        //记录日志数据
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        for (SchoolEquipmentLedger schoolEquipmentLedger : list) {
            if (StringUtils.isNull(schoolEquipmentLedger.getEquipmentName())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、设备名称为空，请你重新输入！");
//            }else if (StringUtils.isNull(schoolEquipmentLedger.getModel())){
//                failureNum++;
//                failureMsg.append("<br/>" + failureNum + "、型号为空，请你重新输入！");
//            }else if (StringUtils.isNull(schoolEquipmentLedger.getSpecification())){
//                failureNum++;
//                failureMsg.append("<br/>" + failureNum + "、规格为空，请你重新输入！");
            }else if (StringUtils.isNull(schoolEquipmentLedger.getClassificationCode())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、分类编码为空，请你重新输入！");
            }else if(schoolEquipmentLedger.getClassificationCode().length() < 4){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、分类编码长度最少为4位，请你核对后重新输入！");
//            }else if (StringUtils.isNull(schoolEquipmentLedger.getUnit())){
//                failureNum++;
//                failureMsg.append("<br/>" + failureNum + "、单位为空，请你重新输入！");
            }else if (StringUtils.isNull(schoolEquipmentLedger.getAffiliationType())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、归属类型为空，请你重新输入！");
            }else if (StringUtils.isNull(schoolEquipmentLedger.getEquipmentState())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、设备状态为空，请你重新输入！");
            }else if (StringUtils.isNull(schoolEquipmentLedger.getIsAllowLend())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、是否允许借出为空，请你重新输入！");
//            }else if (StringUtils.isNull(schoolEquipmentLedger.getIsLend())){
//                failureNum++;
//                failureMsg.append("<br/>" + failureNum + "、是否已借出为空，请你重新输入！");
//            }else if (StringUtils.isNull(schoolEquipmentLedger.getDateOfProduction())){
//                failureNum++;
//                failureMsg.append("<br/>" + failureNum + "、安装时间为空，请你重新输入！");
//            }else if (StringUtils.isNull(schoolEquipmentLedger.getPrice())){
//                failureNum++;
//                failureMsg.append("<br/>" + failureNum + "、价格为空，请你重新输入！");
//            }else if (StringUtils.isNull(schoolEquipmentLedger.getLifeOfUtility())){
//                failureNum++;
//                failureMsg.append("<br/>" + failureNum + "、效用年限为空，请你重新输入！");
//            }else if (StringUtils.isNull(schoolEquipmentLedger.getPlace())){
//                failureNum++;
//                failureMsg.append("<br/>" + failureNum + "、地点为空，请你重新输入！");
            }else if (StringUtils.isNotNull(schoolEquipmentLedger.getDateOfProduction())){
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                    Date dateOfProduction = schoolEquipmentLedger.getDateOfProduction();
                    sdf.format(dateOfProduction);
                } catch (Exception e) {
                    throw new ServiceException(schoolEquipmentLedger.getDateOfProduction() + " 格式不对，请检查日期格式");
                }
//                try {
//                    Integer.parseInt(schoolEquipmentLedger.getPlace());
//                    throw new ServiceException("地点输入错误，请重新输入！");
//                } catch (NumberFormatException e) {
//                    e.printStackTrace();
//                }
            }
            if(StringUtils.isNotNull(schoolEquipmentLedger.getClassificationCode())){

                List<SchoolProductCategory> newCateLists = schoolProductCategories.stream().filter(
                        e -> schoolEquipmentLedger.getClassificationCode().equals(e.getClassificationCode())).collect(Collectors.toList());
                if (newCateLists.size()<=0) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、分类编码不存在，请你重新输入！");
                }
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共" + failureNum + "条数据格式不正确，错误如下：");
            throw new BaseException(failureMsg.toString());
        }
    }

    /**
     * 获取用户
     * @return
     */
    @Override
    public List<Map<String, Object>> getUser(SysUser sysUser) {
        List<Map<String, Object>> userList = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("userId",-1);
        map1.put("userName","物理实验室");
        userList.add(map1);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("userId",-2);
        map2.put("userName","化学实验室");
        userList.add(map2);
        Map<String, Object> map3 = new HashMap<>();
        map3.put("userId",-3);
        map3.put("userName","生物实验室");
        userList.add(map3);
        Map<String, Object> map4 = new HashMap<>();
        map4.put("userId",-4);
        map4.put("userName","技术部门");
        userList.add(map4);
        Map<String, Object> map5 = new HashMap<>();
        map5.put("userId",-5);
        map5.put("userName","艺术");
        userList.add(map5);
        Map<String, Object> map6 = new HashMap<>();
        map6.put("userId",-6);
        map6.put("userName","级部");
        userList.add(map6);
        userList.addAll(equipmentLedgerMapper.getUser(sysUser));
        return userList;
    }

    /**
     * 打印设备条码信息
     * @param ids
     * @return
     */
    @Override
    public List<Map<String, Object>> getEquipmentledger(Long[] ids) {
        return equipmentLedgerMapper.getEquipmentledger(ids);
    }
}
