package com.mvc.service.setup;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mvc.dao.TSetupMapper;
import com.mvc.entity.TSetup;
import com.mvc.entity.TSetupExample;
import com.mvc.model.CorrectMap;
import com.mvc.model.StationAccModel;
import com.mvc.model.TSetupModel;
import com.mvc.model.TSetupPicModel;
import com.mvc.netty.dealconstant.ResourcePath;
import com.mvc.netty.dealconstant.ResourceTag;
import com.mvc.service.taizhang.StationAccService;
import com.mvc.utils.FileUtil;
import com.mvc.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class TSetupService {

    @Resource
    private TSetupMapper tSetupMapper;

    @Resource
    private TSetupPicService tSetupPicService;

    @Resource
    private StationAccService stationAccService;

    @Resource
    private Environment env;

    public Map<String, Object> findAllTSetup(TSetupModel queryModel) {
        List<TSetupModel> resList = new ArrayList<>();
        Map<String, Object> resMap = new CorrectMap();
        TSetupExample example = new TSetupExample();
        TSetupExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(queryModel.getSetupMan())) {
            criteria.andSetupManEqualTo(queryModel.getSetupMan());
        }
        if (StringUtils.isNotEmpty(queryModel.getStationCode())) {
            criteria.andStationCodeEqualTo(queryModel.getStationCode());
        }
        if (queryModel.getSetupTime() != null) {//自动生成维护记录时使用此条件 2023-08-02 guozhao
            criteria.andSetupTimeGreaterThan(queryModel.getSetupTime());
        }

        if (StringUtils.isNotEmpty(queryModel.getUnitCode())) {
            List<StationAccModel> accModels = stationAccService.findAllStationAccListByUnitCode(queryModel.getUnitCode());
            List<String> stations = accModels.stream()
                    .map(StationAccModel::getStationCode)
                    .collect(Collectors.toList());
            if (stations.size() > 0) {
                criteria.andStationCodeIn(stations);
            } else {
                resMap.put("total", 0);
                resMap.put("list", resList);
                return resMap;
            }
        }

        example.setOrderByClause("SETUP_TIME desc");

        Page<Object> pageObject = PageHelper.startPage(queryModel.getPage(), queryModel.getRows());
        List<TSetup> tSetupList = tSetupMapper.selectByExample(example);

        for (TSetup tSetup : tSetupList) {
            TSetupModel setupModel = new TSetupModel();
            BeanUtils.copyProperties(tSetup, setupModel);
            setupModel.setPicList(tSetupPicService.findSetupPicsBySetupId(tSetup.getSetupId()));
            resList.add(setupModel);
        }
        resMap.put("total", pageObject.getTotal());
        resMap.put("list", resList);
        return resMap;
    }

    public TSetupModel findTSetupBySetupId(String setupId) {
        TSetupExample example = new TSetupExample();
        TSetupExample.Criteria criteria = example.createCriteria();
        criteria.andSetupIdEqualTo(setupId);
        List<TSetup> setups = tSetupMapper.selectByExample(example);
        if (setups.size() > 0) {
            TSetupModel setupModel = new TSetupModel();
            BeanUtils.copyProperties(setups.get(0), setupModel);
            return setupModel;
        }
        return null;
    }

    public TSetupModel saveTSetup(TSetupModel model) {
        model.setFinishedFlag("0");
        model.setSetupId(StringUtil.getUuid());
        model.setSetupTime(new Date());
        TSetup tSetup = new TSetup();
        BeanUtils.copyProperties(model, tSetup);

        /*if(model.getPicList()!=null){
            for (TSetupPicModel picModel:model.getPicList()){
                tSetupPicService.saveTSetupPic(picModel);
            }
        }*/
        int insert = tSetupMapper.insert(tSetup);
        model.setId(tSetup.getId());
        model.setPicList(tSetupPicService.findSetupPicsBySetupId(tSetup.getSetupId()));

        return model;
    }

    public TSetupModel updateTSetup(TSetupModel model) {
        TSetup tSetup = tSetupMapper.selectByPrimaryKey(model.getId());
        BeanUtils.copyProperties(model, tSetup);
        int i = tSetupMapper.updateByPrimaryKey(tSetup);
        model.setPicList(tSetupPicService.findSetupPicsBySetupId(tSetup.getSetupId()));
        return model;
    }

    public TSetupModel finishTSetup(TSetupModel model) {
        if (model.getFinishedFlag().equals("1")) {
            model.setFinishedTime(new Date());
        } else {
            model.setFinishedTime(null);
        }
        TSetup tSetup = tSetupMapper.selectByPrimaryKey(model.getId());
        BeanUtils.copyProperties(model, tSetup);
        int i = tSetupMapper.updateByPrimaryKey(tSetup);
        model.setPicList(tSetupPicService.findSetupPicsBySetupId(tSetup.getSetupId()));
        if (i > 0 && model.getFinishedFlag().equals("1")) {//安装完成后更新安装状态 2022-11-04 guozhao
            stationAccService.updateSetupStatus(model);
        }

        return model;
    }

    public int deleteTSetup(int id, String setupId) {
        int result1 = tSetupMapper.deleteByPrimaryKey(id);
        int result2 = tSetupPicService.deleteTSetupPicBySetupId(setupId);
        return (result1 > 0) ? 1 : 0;
    }

    /**
     * 根据站点编码获取最新安装记录
     *
     * @param stationCode
     * @return
     */
    public TSetupModel findTSetupByStationCode(String stationCode, String deviceSn) {
        if (StringUtils.isEmpty(stationCode) || StringUtils.isEmpty(deviceSn)) return null;
        TSetupExample example = new TSetupExample();
        TSetupExample.Criteria criteria = example.createCriteria();
        criteria.andStationCodeEqualTo(stationCode);
        criteria.andDeviceSnEqualTo(deviceSn);
        example.setOrderByClause("SETUP_TIME desc");
        List<TSetup> setups = tSetupMapper.selectByExample(example);
        if (setups.size() > 0) {
            TSetupModel setupModel = new TSetupModel();
            BeanUtils.copyProperties(setups.get(0), setupModel);
            return setupModel;
        }
        return null;
    }

    /**
     * 根据主键ID获取Model
     *
     * @param id
     * @return
     */
    public TSetupModel findTSetupById(int id) {
        TSetup setup = tSetupMapper.selectByPrimaryKey(id);
        if (setup != null) {
            TSetupModel setupModel = new TSetupModel();
            BeanUtils.copyProperties(setup, setupModel);
            return setupModel;
        }
        return null;
    }

    public void downSetupPicture(HttpServletResponse response,int id){
        TSetup setup = tSetupMapper.selectByPrimaryKey(id);
        List<TSetupPicModel> picList = tSetupPicService.findSetupPicsBySetupId(setup.getSetupId());

        List<String> list =new ArrayList<>();
        for (TSetupPicModel picModel:picList){
            String url = picModel.getPicUrl().replace(env.getProperty(ResourceTag.ResourceUrlTag.getTag()),env.getProperty(ResourceTag.UploadPathTag.getTag()));
            url = url.replace(ResourcePath.Image.getPath(),"");
            list.add(url);
        }

        byte[] bytes = FileUtil.zipFile(list);
        try{
            String fileName = setup.getStationCode() + ".zip";
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.close();
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
