package com.bonus.hn.bearing.capacity.backstage.project.service;

import com.alibaba.fastjson.JSONObject;
import com.bonus.hn.bearing.capacity.backstage.dataindex.entity.ProjectBean;
import com.bonus.hn.bearing.capacity.backstage.manager.utils.ImportNoPhotoExcelHelper;
import com.bonus.hn.bearing.capacity.backstage.manager.utils.ListHelper;
import com.bonus.hn.bearing.capacity.backstage.manager.utils.StringHelper;
import com.bonus.hn.bearing.capacity.backstage.manager.utils.UserUtil;
import com.bonus.hn.bearing.capacity.backstage.personnelPool.dao.PersonnelPoolDao;
import com.bonus.hn.bearing.capacity.backstage.personnelPool.entity.SubsidiaryCompanyBean;
import com.bonus.hn.bearing.capacity.backstage.project.dao.TowerProjectDao;
import com.bonus.hn.bearing.capacity.backstage.project.entity.TowerProjectBean;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.bonus.hn.bearing.capacity.backstage.manager.utils.StringHelper.coordinateTransform;

/**
 * APP登录记录表(AppLoginAudit)表服务实现类
 *
 * @author makejava
 * @since 2022-12-12 13:57:46
 */
@Service("TowerProjectService")
public class towerProjectImpl implements TowerProjectService {
    @Resource
    private TowerProjectDao dao;
    @Resource
    private PersonnelPoolDao ppdao;

    @Override
    public List<TowerProjectBean> getFirmList(TowerProjectBean o) {
        o.setLevel(UserUtil.getLoginUser().getLevel());
        o.setOrgIds(UserUtil.getLoginUser().getOrgId());
        return dao.getFirmList(o);
    }

    @Override
    public int addProjectInfo(TowerProjectBean bean) {
        String coordinates = coordinateTransform(Double.parseDouble(bean.getLongitude()), Double.parseDouble(bean.getLineLength()),"114");
        String[] parts = coordinates.split(",");
        // 大地经度
        String geodeticLon = parts[0];
        // 大地纬度
        String geodeticLat = parts[1];
        bean.setGeodeticLon(geodeticLon);
        bean.setGeodeticLat(geodeticLat);
        return dao.addProjectInfo(bean);
    }

    @Override
    public TowerProjectBean getListProject(String id) {
        return dao.getListProject(id);
    }

    @Override
    public int updateProject(TowerProjectBean bean) {
        String coordinates = coordinateTransform(Double.parseDouble(bean.getLongitude()), Double.parseDouble(bean.getLineLength()),"114");
        String[] parts = coordinates.split(",");
        // 大地经度
        String geodeticLon = parts[0];
        // 大地纬度
        String geodeticLat = parts[1];
        bean.setGeodeticLon(geodeticLon);
        bean.setGeodeticLat(geodeticLat);
        return dao.updateProject(bean);
    }

    @Override
    public int delProjectById(String id) {
        Map<String, Object> paramMap = new HashMap<>(100);
        paramMap.put("ids", Arrays.asList(id.split(",")));
        return dao.delProjectByIds(id);
    }

    @Override
    public int delProjectId(String id) {
        return dao.delProjectId(id);
    }

    @Override
    public String towerListImport(HttpServletRequest request, MultipartFile file, String engineerId) {
        int successCount = 0;
        int errorCount = 0;
        String fileName = file.getOriginalFilename();
        String res = "";
        try {
            TowerProjectBean entity = new TowerProjectBean();
            entity.setTowerName(request.getParameter("towerName"));
            entity.setGeodeticLon(request.getParameter("geodeticLon"));
            entity.setGeodeticLat(request.getParameter("geodeticLat"));

            List<JSONObject> lstObj = (List<JSONObject>) ImportNoPhotoExcelHelper.readExcel(file, TowerProjectBean.class);
            List<TowerProjectBean> list = new ArrayList<>();
            int i = 0;
            boolean active = false;
            String towerName = "";
            String geodeticLon = "";
            String geodeticLat = "";
            if (lstObj != null && lstObj.size() > 0) {
                for (JSONObject obj : lstObj) {
                    i++;
                    TowerProjectBean bean = new TowerProjectBean();
                    towerName = String.valueOf(obj.getString("towerName"));
                    bean.setTowerName(towerName.trim());
                    if (StringHelper.isEmpty(towerName) ||  "0.0".equals(towerName.trim())) {
                        res += "第" + i + "行杆塔为空;";
                        active = true;
                    }
                    geodeticLon = String.valueOf(obj.getString("geodeticLon"));
                    bean.setGeodeticLon(geodeticLon.trim());
                    if (StringHelper.isEmpty(geodeticLon) ||  "0.0".equals(geodeticLon.trim())) {
                        res += "第" + i + "行大地经度为空;";
                        active = true;
                    }
                    geodeticLat = String.valueOf(obj.getString("geodeticLat"));
                    bean.setGeodeticLat(geodeticLat.trim());
                    if (StringHelper.isEmpty(geodeticLat) ||  "0.0".equals(geodeticLat.trim())) {
                        res += "第" + i + "行大地纬度为空;";
                        active = true;
                    }
                    list.add(bean);
                }
            }else {
                return "数据为空";
            }
            if (active) {
                String[] arr = res.split(";");
                String code = "<pre>" +
                        "导入数据错误提示：<br/>";
                for (int j = 0; j < arr.length; j++) {
                    if (j % 2 == 0){
                        if (arr[j].indexOf("检查所见异常结果") != -1){
                            code += arr[j] + ";\t";
                        }else if(arr[j].indexOf("分公司") != -1 || arr[j].indexOf("姓名") != -1 || arr[j].indexOf("姓别") != -1 || arr[j].indexOf("身份证") != -1
                                || arr[j].indexOf("执照情况") != -1 || arr[j].indexOf("职称/技能等级") != -1){
                            code += arr[j] + ";\t\t\t";
                        }else {
                            code += arr[j] + ";\t\t";
                        }

                    }else {
                        code += arr[j] + "<br/>";
                    }
                }
                return code+ "<pre>";
            }
            int complete = dao.getCompletionWork(engineerId);
            if (complete > 0){
                return "该工程已完成，不能导入杆塔";
            }else {
                if (ListHelper.isNotEmpty(list)) {
                    for (TowerProjectBean vo : list) {
                        System.out.println("vo="+vo.toString());
                        vo.setEngineerIds(engineerId);
                        int num = dao.getTowerNum(vo);
                        String centralMeridian = dao.getCentralMeridian(vo);
                        String coordinates = coordinateTransform(Double.parseDouble(StringHelper.replaceSpace(vo.getGeodeticLat())), Double.parseDouble(StringHelper.replaceSpace(vo.getGeodeticLon())),centralMeridian);
                        String[] parts = coordinates.split(",");
                        String lat = parts[1];
                        String lon = parts[0];
                        vo.setGeodeticLat(StringHelper.replaceSpace(vo.getGeodeticLat()));
                        vo.setGeodeticLon(StringHelper.replaceSpace(vo.getGeodeticLon()));
                        vo.setLat(lat);
                        vo.setLon(lon);
                        if (num > 0) {
                            dao.updataTowerImportExcel(vo);
                        }else {
                            dao.addTowerImportExcel(vo);
                        }
                        successCount++;
                    }
                }
            }
            res = "导入成功";
        } catch (Exception e) {
            if (e.getMessage().indexOf("模板错误，请重新选择模板！") != -1){
                res = "模板错误，请重新选择模板！";
            }else {
                res = "导入失败";
            }
            e.printStackTrace();
        }
        SubsidiaryCompanyBean bean = new SubsidiaryCompanyBean();
        bean.setFileName(fileName);
        bean.setDataVolume(String.valueOf(successCount));
        bean.setIdName(UserUtil.getLoginUser().getId().toString());
        ppdao.addImportRecord(bean);
        Map<String, Integer> obj = new HashMap<>(100);
        obj.put("成功导入数量", successCount);
        obj.put("导入异常记录数量", errorCount);
        return res;
    }

}
