package com.yeejoin.equipmanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yeejoin.amos.boot.biz.common.dto.OrgMenuDto;
import com.yeejoin.equipmanage.common.entity.*;
import com.yeejoin.equipmanage.common.enums.BillContentEnum;
import com.yeejoin.equipmanage.common.enums.FileTypeEnum;
import com.yeejoin.equipmanage.mapper.*;
import com.yeejoin.equipmanage.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.utils.Bean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author wujiang
 * @date 2020-07-07
 */
@Service
public class EquipmentDetailServiceImpl extends ServiceImpl<EquipmentDetailMapper, EquipmentDetail>
        implements IEquipmentDetailService {

    @Autowired
    private EquipmentDetailMapper equipmentDetailMapper;

    @Autowired
    private EquipmentMapper equipmentMapper;

    @Autowired
    private EquipmentCategoryMapper equipmentCategoryMapper;

    @Autowired
    private EquPropertyMapper equPropertyMapper;

    @Autowired
    private IEquPropertyService iEquPropertyService;

    @Autowired
    private ManufacturerInfoMapper manufacturerInfoMapper;

    @Autowired
    private IEquipmentCategoryService iEquipmentCategoryService;

    @Autowired
    private IEquipmentService iEquipmentService;

    @Autowired
    private IUnitService iUnitService;

    @Autowired
    private IUploadFileService iUploadFileService;
    @Autowired
    private EquipmentOnCarMapper equipmentOnCarMapper;
    @Autowired
    private IEquipmentSpecificIndexSerivce equipmentSpecificIndexSerivce;
    @Autowired
    JCSRemoteService jcsRemoteService;


    @Value("${fileserver_domain}")
    private String fileServer;

    @Value("${auth-key-fire-equip:fire_equip_info}")
    private String authKey;


    @Autowired
    private ISystemDicService iSystemDicService;

    @Override
    public EquipmentDetail saveOne(EquipmentDetail equipmentDetail) {
        Equipment equipment = equipmentMapper.selectById(equipmentDetail.getEquipmentId());
        equipmentDetail.setCode(equipment.getCode());
        this.save(equipmentDetail);
        saveFile(equipmentDetail);
        return equipmentDetail;
    }

    private List<UploadFile> fillFileList(List<UploadFile> list, Long id, String type) {
        if (list == null) {
            return new ArrayList<>();
        }
        list.forEach(item -> {
            item.setUrl(item.getUrl());
            item.setFileType(type);
            item.setObjectType(BillContentEnum.ZB.getKey());
            item.setObjectId(id);
        });
        return list;
    }

    @Override
    public Page<EquipmentDetail> page(Page<EquipmentDetail> pageBean, EquipmentDetail equipmentDetail) {
        List<EquipmentDetail> list = equipmentDetailMapper.page(pageBean.offset(), pageBean.getSize(), equipmentDetail);
        int count = equipmentDetailMapper.count(equipmentDetail);
        pageBean.setRecords(list);
        pageBean.setTotal(count);
        return pageBean;
    }

    @Override
    public EquipmentDetail getOneById(long id) {
        EquipmentDetail equipmentDetail = equipmentDetailMapper.selectById(id);
        if (equipmentDetail == null) {
            return null;
        }
        Equipment equipment = equipmentMapper.selectById(equipmentDetail.getEquipmentId());
        EquipmentCategory equipmentCategory = equipmentCategoryMapper.selectById(equipment.getCategoryId());
        equipment.setEquipmentCategory(equipmentCategory);
        Unit unit = iUnitService.getById(equipment.getUnitId());
        equipment.setUnit(unit);
        equipmentDetail.setEquipment(equipment);
        List<EquProperty> equPropertyList = equPropertyMapper.queryListByEquipDetailId(equipmentDetail.getId());
        equipmentDetail.setEquPropertyList(equPropertyList);
        ManufacturerInfo manufacturerInfo = manufacturerInfoMapper.selectById(equipmentDetail.getManufacturerId());
        if (manufacturerInfo != null) {
            manufacturerInfo.setImg(manufacturerInfo.getImg());
        }
        equipmentDetail.setManufacturerInfo(manufacturerInfo);
        equipmentDetail.setImg(getEquipFileList(id, FileTypeEnum.image.toString()));
        equipmentDetail.setVideo(getEquipFileList(id, FileTypeEnum.video.toString()));
        equipmentDetail.setCertification(getEquipFileList(id, FileTypeEnum.certificate.toString()));
        equipmentDetail.setInstruction(getEquipFileList(id, FileTypeEnum.instruction.toString()));
        if (equipmentDetail.getCountry() != null) {
            equipmentDetail.setCountryName(
                    iSystemDicService.getOne(new QueryWrapper<SystemDic>().eq("id", equipmentDetail.getCountry())).getName());
        }
        return equipmentDetail;
    }

    private List<UploadFile> getEquipFileList(Long id, String type) {
        List<UploadFile> list = iUploadFileService.list(new QueryWrapper<UploadFile>().eq("object_id", id)
                .eq("object_type", BillContentEnum.ZB.getKey()).eq("file_type", type));
        list.forEach(item -> {
            item.setUrl(item.getUrl());
        });
        return list;
    }

    @Override
    public boolean updateOneById(Long equipmentSpecificId, EquipmentDetail equipmentDetail) {
        //TODO 页面装备定义调整可编辑，新增逻辑，装备定义id变化时，删除性能指标表，插入新的性能指标
        //1.更新或者插入设备实例的性能指标
        EquipmentDetail dbEquip = this.getOneById(equipmentDetail.getId());
        if (!dbEquip.getEquipmentId().equals(equipmentDetail.getEquipmentId())) {
            //编辑逻辑
            Equipment equipment = equipmentMapper.selectById(equipmentDetail.getEquipmentId());
            equipmentDetail.setCode(equipment.getCode());
            equipmentDetail.setEquipmentName(equipment.getName());
            equipmentSpecificIndexSerivce.remove(new LambdaQueryWrapper<EquipmentSpecificIndex>().eq(EquipmentSpecificIndex::getEquipmentSpecificId, equipmentSpecificId));
            List<EquProperty> equPropertyList = equipmentDetail.getEquPropertyList();
            List<EquipmentSpecificIndex> equipmentSpecificIndexs = equPropertyList.stream().map(p -> {
                EquipmentSpecificIndex specificIndex = new EquipmentSpecificIndex();
                Bean.copyExistPropertis(p, specificIndex);
                specificIndex.setEquipmentSpecialName(equipmentDetail.getName());
                specificIndex.setEquipmentSpecificId(equipmentSpecificId);
                return specificIndex;
            }).collect(Collectors.toList());
            if (!equipmentSpecificIndexs.isEmpty()) {
                equipmentSpecificIndexSerivce.saveBatch(equipmentSpecificIndexs);
            }
        } else {
            //修改指标值逻辑
            List<EquProperty> equPropertyList = equipmentDetail.getEquPropertyList();
            List<EquipmentSpecificIndex> equipmentSpecificIndexs = equPropertyList.stream().map(p -> {
                EquipmentSpecificIndex specificIndex = new EquipmentSpecificIndex();
                Bean.copyExistPropertis(p, specificIndex);
                specificIndex.setEquipmentSpecialName(equipmentDetail.getName());
                specificIndex.setEquipmentSpecificId(equipmentSpecificId);
                specificIndex.setValue(p.getValue());
                return specificIndex;
            }).collect(Collectors.toList());
            if (!equipmentSpecificIndexs.isEmpty()) {
                equipmentSpecificIndexSerivce.updateIndexValueBatchByUniqueKey(equipmentSpecificId, equipmentSpecificIndexs);
            }
        }
        //2.更新Detail表
        equipmentDetailMapper.updateById(equipmentDetail);
        //3.保存图片
        iUploadFileService.remove(new QueryWrapper<UploadFile>().eq("object_type", BillContentEnum.ZB.getKey())
                .eq("object_id", equipmentDetail.getId()));
        saveFile(equipmentDetail);
        return true;
    }

    private void saveFile(EquipmentDetail equipmentDetail) {
        List<UploadFile> fileList = new ArrayList<>();
        fileList.addAll(fillFileList(equipmentDetail.getImg(), equipmentDetail.getId(), FileTypeEnum.image.toString()));
        fileList.addAll(fillFileList(equipmentDetail.getVideo(), equipmentDetail.getId(), FileTypeEnum.video.toString()));
        fileList.addAll(fillFileList(equipmentDetail.getCertification(), equipmentDetail.getId(), FileTypeEnum.certificate.toString()));
        fileList.addAll(fillFileList(equipmentDetail.getInstruction(), equipmentDetail.getId(), FileTypeEnum.instruction.toString()));
        iUploadFileService.saveBatch(fileList);
    }

    @Override
    public boolean removeOneById(long id) {
        equipmentDetailMapper.deleteById(id);
        Map<String, Object> columnMap = new HashMap<String, Object>();
        columnMap.put("equipment_detail_id", id);
        iEquPropertyService.removeByMap(columnMap);
        return true;
    }

    @Override
    public Page<EquipmentDetail> page(Page<EquipmentDetail> pageBean, String category) {
        char[] chars = category.toCharArray();
        String newcategory = "";
        for (int i = chars.length - 1; i >= 0; i--) {
            if ("0".equals(String.valueOf(chars[i]))) {
                newcategory = category.substring(0, i);
            } else {
                break;
            }
        }
        List<EquipmentCategory> categoryList = iEquipmentCategoryService
                .list(new QueryWrapper<EquipmentCategory>().likeRight("code", newcategory));
        List<EquipmentDetail> list = equipmentDetailMapper.pageCategory(pageBean.offset(), pageBean.getSize(),
                categoryList);
        list.forEach(item -> {
            Equipment equipment = iEquipmentService.getById(item.getEquipmentId());
            Unit unit = iUnitService.getById(equipment.getUnitId());
            equipment.setUnit(unit);
            item.setEquipment(equipment);
        });
        int count = equipmentDetailMapper.countCategory(pageBean.offset(), pageBean.getSize(), categoryList);
        Page<EquipmentDetail> page = new Page<EquipmentDetail>(pageBean.getCurrent(), pageBean.getSize());
        page.setRecords(list);
        page.setTotal(count);
        return page;
    }

    @Override
    public boolean removeBatchById(List<Long> idList) {
        idList.forEach(x -> {
            QueryWrapper<EquipmentOnCar> wrapper = new QueryWrapper<>();
            wrapper.eq("equipment_detail_id", x);
            if (equipmentOnCarMapper.selectCount(wrapper) > 0) {
                throw new RuntimeException("已装备的设备不能删除");


            }
        });
        return this.removeByIds(idList);
    }

    @Override
    public boolean quotaUpdate(List<EquProperty> e) {
        for (EquProperty a : e) {
            equipmentDetailMapper.quotaUpdate(a);
        }
        return false;
    }

    @Override
    public String getPref(String id) {
        return equipmentDetailMapper.getPref(id);
    }

    @Override
    public String checkDelete(List<Long> ids) {
        String res = "";
        for (Long id : ids) {
            String s = equipmentDetailMapper.checkDelete(id);
            if (s != null && !("").equals(s)) {
                res = res + s + " , ";
            }
        }
        return res;
    }

    @Override
    public List<OrgMenuDto> companyDeptTree() {
        return jcsRemoteService.getCompanyDeptTreeWithAuth(authKey, null);
    }
}
