package com.yeejoin.equipmanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.equipmanage.common.entity.DynamicFormGroup;
import com.yeejoin.equipmanage.common.entity.EquipmentManageEntity;
import com.yeejoin.equipmanage.common.entity.publics.BaseEntity;
import com.yeejoin.equipmanage.common.vo.EquipmentManageVo;
import com.yeejoin.equipmanage.common.vo.FileUploadVo;
import com.yeejoin.equipmanage.mapper.EquipmentManageMapper;
import com.yeejoin.equipmanage.remote.RemoteSecurityService;
import com.yeejoin.equipmanage.service.EquipmentManageService;
import com.yeejoin.equipmanage.service.IEqDynamicFormGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务类
 *
 * @author zjw
 * @date 2020-09-04
 */
@Service
public class EquipmentManageServiceImpl extends ServiceImpl<EquipmentManageMapper, EquipmentManageEntity> implements EquipmentManageService {

    @Autowired
    EquipmentManageMapper equipmentManageMapper;


    @Autowired
    private RemoteSecurityService remoteSecurityService;


    @Autowired
    IEqDynamicFormGroupService iEqDynamicFormGroupService;


    @Value("${equipment.fire.systemid}")
    private String fireSystemId;

    @Override
    public Map<String, Object> queryEquipmenInfoAndCount(String equimentName, String equimentCode, String construction, String maintenance,
                                                         String bizOrgCode, String formGroupId, int current, int pageSize,String controBoxBuildId,String companyCode, String nameOrCode) {
        HttpServletRequest request = null;
        Map map = new HashMap<String, Object>();
        map.put("equimentName", equimentName);
        map.put("equimentCode", equimentCode);
        map.put("construction", construction);
        map.put("maintenance", maintenance);
        map.put("spage", current);
        map.put("pageSize", pageSize);
        map.put("bizOrgCode", bizOrgCode);
        map.put("companyCode", companyCode);
        map.put("formGroupId", formGroupId);
        map.put("controBoxBuildId",controBoxBuildId);
        map.put("nameOrCode", nameOrCode);
        List<EquipmentManageVo> dataList = equipmentManageMapper.queryEquipmenInfo(map);
        Long count = equipmentManageMapper.queryEquipmenCount(map);
        map.clear();
        map.put("dataList", dataList);
        map.put("count", count);
        map.put("current", current);
        map.put("pageSize", pageSize);
        return map;
    }

    @Override
    public Map<String, Object> getUtils(String  orgCode) {
        Map map = new HashMap<String, Object>();
        List<EquipmentManageVo> utils = equipmentManageMapper.getUtils();

        List<DynamicFormGroup> list = iEqDynamicFormGroupService.list(new LambdaQueryWrapper<DynamicFormGroup>()
                //.eq(DynamicFormGroup::getOrgCode, orgCode)  任务 7480
                .eq(DynamicFormGroup::getParentId, 0)
                .orderByDesc(BaseEntity::getCreateDate));
     // List<EquipmentManageVo> systemList = equipmentManageMapper.getSystemList();
        map.put("utils", utils);
        map.put("systemType", list);
        return map;
    }

    @Override
    public Map<String, Object> getUsers() {
        Map map = new HashMap<String, Object>();
        AgencyUserModel agencyUser = remoteSecurityService.getAgencyUser();
        List<AgencyUserModel> agencyUserModels = remoteSecurityService.listUserByCompanyId(String.valueOf(agencyUser.getCompanys().get(0).getSequenceNbr()));
        map.put("user", agencyUserModels);
        return map;
    }

    @Override
    public List<EquipmentManageVo> getSystemList(){

        return equipmentManageMapper.getSystemList();
    }
    @Override
    public Map<String, Object> deleteById(List<EquipmentManageVo> list) {
        Map<String, Object> result = new HashMap();
        String stringresult = "";
        int count = 0;
        for (EquipmentManageVo model : list) {
            try {
                int i = equipmentManageMapper.deleteByid(model.getId());
                if (i == 1) {
                    count++;
                } else {
                    stringresult = stringresult + ("线路：" + model.getName() + ",");
                }
            } catch (Exception e) {

            }
        }
        if (count == list.size()) {
            result.put("result", "数据删除成功");
            result.put("message", "success");
        } else {
            result.put("result", stringresult + "数据删除失败");
            result.put("message", "error");
        }
        return result;
    }

    @Override
    public String checkCode(String param) {
        int num = (int) (Math.random() * 900 + 100);
        ;
        String val = param;
        val += String.valueOf(num);
        int i = equipmentManageMapper.checkCode(val);
        if (i == 0) {
            return val;
        } else {
            return checkCode(param);
        }
    }

    @Override
    public Map<String, Object> addEquipment(EquipmentManageVo vo) {
        Map<String, Object> result = new HashMap();
        String userId = remoteSecurityService.getAgencyUser().getUserId();
        String s = String.valueOf(System.currentTimeMillis());
        vo.setId(s);
        vo.setRecUserId(userId);
        vo.setSort(s);
        if (vo.getSystemType().equals(fireSystemId)) {
            vo.setSort("0");
        }
        int i = equipmentManageMapper.insertEquipment(vo);

        List<FileUploadVo> faceimg = vo.getFaceimg();
        for (FileUploadVo f:faceimg) {
            f.setId(String.valueOf(System.currentTimeMillis()));
            f.setUserId(userId);
            f.setFileType("face");
            f.setObjectId(s);
             equipmentManageMapper.insertFile(f);
        }
        FileUploadVo video = vo.getVideo();
        video.setId(String.valueOf(System.currentTimeMillis()));
        video.setUserId(userId);
        video.setFileType("video");
        video.setObjectId(s);
        equipmentManageMapper.insertFile(video);

        List<FileUploadVo> instruction = vo.getInstruction();
        for (FileUploadVo f:instruction) {
            f.setId(String.valueOf(System.currentTimeMillis()));
            f.setUserId(userId);
            f.setFileType("instruction");
            f.setObjectId(s);
            equipmentManageMapper.insertFile(f);
        }

        List<FileUploadVo> asser = vo.getAsser();
        for (FileUploadVo f:asser) {
            f.setId(String.valueOf(System.currentTimeMillis()));
            f.setUserId(userId);
            f.setFileType("certificate");
            f.setObjectId(s);
            equipmentManageMapper.insertFile(f);
        }
            result.put("result", "数据添加成功");
            result.put("message", "success");

        return result;
    }

    @Override
    public Map<String, Object> getFiles(String id) {
        Map<String, Object> result = new HashMap();
        List<FileUploadVo> image = equipmentManageMapper.getFiles(id, "image");
        List<FileUploadVo> video = equipmentManageMapper.getFiles(id, "video");
        List<FileUploadVo> instruction = equipmentManageMapper.getFiles(id, "instruction");
        List<FileUploadVo> certificate = equipmentManageMapper.getFiles(id, "certificate");
        List<FileUploadVo> face = equipmentManageMapper.getFiles(id, "face");
        List<FileUploadVo> spotimg = equipmentManageMapper.getFiles(id, "spotimg");
        List<FileUploadVo> tdmod = equipmentManageMapper.getFiles(id, "tdmod");
        result.put("image", image);
        result.put("video", video);
        result.put("instruction", instruction);
        result.put("certificate", certificate);
        result.put("face", face);
        result.put("spotimg", spotimg);
        result.put("tdmod", tdmod);
        return result;
    }

    @Override
    public Map<String, Object> updateEquipment(EquipmentManageVo vo) {
        Map<String, Object> result = new HashMap();
        String userId = remoteSecurityService.getAgencyUser().getUserId();
        vo.setRecUserId(userId);
        int i = equipmentManageMapper.updateEquipment(vo);
        String sequenceNbr = vo.getId();
        equipmentManageMapper.deleteFilre(sequenceNbr);

        List<FileUploadVo> faceimg = vo.getFaceimg();
        for (FileUploadVo f:faceimg) {
            f.setId(String.valueOf(System.currentTimeMillis()));
            f.setUserId(userId);
            f.setFileType("face");
            f.setObjectId(sequenceNbr);
            equipmentManageMapper.insertFile(f);
        }
        FileUploadVo video = vo.getVideo();
        video.setId(String.valueOf(System.currentTimeMillis()));
        video.setUserId(userId);
        video.setFileType("video");
        video.setObjectId(sequenceNbr);
        equipmentManageMapper.insertFile(video);

        List<FileUploadVo> instruction = vo.getInstruction();
        for (FileUploadVo f:instruction) {
            f.setId(String.valueOf(System.currentTimeMillis()));
            f.setUserId(userId);
            f.setFileType("instruction");
            f.setObjectId(sequenceNbr);
            equipmentManageMapper.insertFile(f);
        }

        List<FileUploadVo> asser = vo.getAsser();
        for (FileUploadVo f:asser) {
            f.setId(String.valueOf(System.currentTimeMillis()));
            f.setUserId(userId);
            f.setFileType("certificate");
            f.setObjectId(sequenceNbr);
            equipmentManageMapper.insertFile(f);
        }

        result.put("result", "数据修改成功");
        result.put("message", "success");

        return result;
    }

    @Override
    public void downLoad(FileUploadVo vo, HttpServletResponse response) {
        String fileName = vo.getName() ;
        ServletOutputStream out;
        response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
        response.setHeader("Access-Control-Expose-Headers", "access_token");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setContentType("multipart/form-data");
        try {
            InputStream inputStream =  getInputStreamFromURL(vo.getUrl());

            //3.通过response获取ServletOutputStream对象(out)
            out = response.getOutputStream();

            int b = 0;
            byte[] buffer = new byte[512];
            while (b != -1){
                b = inputStream.read(buffer);
                //4.写到输出流(out)中
                out.write(buffer,0,b);
            }
            inputStream.close();
            out.close();
            out.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Map<String,Object> chekcName(EquipmentManageVo vo) {
        Map<String, Object> result = new HashMap();
        if (equipmentManageMapper.chekcName( vo) != 0){
            result.put("result", "系统名称重复！");
            result.put("message", "error");
        }
        return result;
    }


    public static InputStream getInputStreamFromURL(String destUrl){
        HttpURLConnection httpUrl = null;
        URL url = null;
        InputStream in = null;
        try {
            url = new URL(destUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            in = httpUrl.getInputStream();
            return in;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
