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

import com.alibaba.fastjson.JSONObject;
import com.bonus.hn.bearing.capacity.backstage.dataindex.dao.DataIndexDao;
import com.bonus.hn.bearing.capacity.backstage.dataindex.entity.DataHomeBean;
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 org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xliu
 * @date 2023/11/10 13:28
 */
@Service("DataIndexService")
public class DataIndexServiceimlp implements  DataIndexService{

    @Resource
    private DataIndexDao dataIndexDao;
    @Resource
    private PersonnelPoolDao dao;
    @Override
    public ProjectBean getProjectStatus(ProjectBean bean) {
        return dataIndexDao.getProjectStatus(bean);
    };

    @Override
    public ProjectBean getBranchOfficeTeamStatus(ProjectBean projectBean) {
        String keyWord = projectBean.getKeyWord();
        if("一".equals(keyWord)){
            projectBean.setKeyWord("2");
        }else if("二".equals(keyWord)){
            projectBean.setKeyWord("3");
        }else if("大力".equals(keyWord)){
            projectBean.setKeyWord("4");
        }else{
            projectBean.setKeyWord("0");
        }
        return dataIndexDao.getBranchOfficeTeamStatus(projectBean);
    }

    @Override
    public ProjectBean getSubTeamStatus(ProjectBean projectBean) {
        return dataIndexDao.getSubTeamStatus(projectBean);
    }

    @Override
    public ProjectBean getOwnTeamStatus(ProjectBean projectBean) {
        return dataIndexDao.getOwnTeamStatus(projectBean);
    }


    @Override
    public ProjectBean getToolStatus(ProjectBean bean) {
        return dataIndexDao.getToolStatus(bean);
    }

    @Override
    public ProjectBean getSubTeamType(ProjectBean projectBean) {
        return dataIndexDao.getSubTeamType(projectBean);
    }


    @Override
    public Map<String, List<String>> getProjectProgress(DataHomeBean bb) {
        bb.setLevel(UserUtil.getLoginUser().getLevel());
        bb.setOrgId(UserUtil.getLoginUser().getOrgId());
        long time1 = System.currentTimeMillis();
        List<DataHomeBean> list = dataIndexDao.getProjectMessage(bb);
        String[] arr = new String[]{"1","2","3"};
        List<String> proName = new ArrayList<>();
        List<String> proId = new ArrayList<>();
        List<String> data0 = new ArrayList<>();
        List<String> data1 = new ArrayList<>();
        List<String> data2 = new ArrayList<>();
        Map<String,List<String>> map = new HashMap<String,List<String>>(100);
        for (DataHomeBean bean:list ) {
            String id = bean.getId();
            //项目名称
            String dataKey = bean.getDataKey();
            //架线百分比
            String dataNum = bean.getDataNum();
            //所有杆塔个数
            String allNum = bean.getAllNum();
            proName.add(dataKey);
            proId.add(id);
            for (String str:arr) {
                String count = dataIndexDao.getTowerMessageByProId(id,str);
                if("1".equals(str)){
                    if(!"0".equals(allNum)){
                        BigDecimal a = new BigDecimal(count);
                        BigDecimal b = new BigDecimal(allNum);
                        BigDecimal num = a.divide(b, 2, RoundingMode.HALF_UP);
                        System.err.println("num====="+num);
                        data0.add(num.multiply(new BigDecimal(100))+"");
                    }else{
                        data0.add("0");
                    }
                }else if("2".equals(str)){
                    if(!"0".equals(allNum)){
                        BigDecimal a = new BigDecimal(Float.parseFloat(count));
                        BigDecimal b = new BigDecimal(Float.parseFloat(allNum));
                        BigDecimal num = a.divide(b,2, RoundingMode.HALF_UP);
                        System.err.println("num====="+num);
                        data1.add(num.multiply(new BigDecimal(100))+"");
                    }else{
                        data1.add("0");
                    }
                }else{
                    data2.add(dataNum);
                }
            }

        }
        map.put("proName",proName);
        map.put("proId",proId);
        map.put("data0",data0);
        map.put("data1",data1);
        map.put("data2",data2);
        long time2 = System.currentTimeMillis();
        System.err.println("查询工程进度所用时间："+(time2-time1));
        return map;
    }


    @Override
    public Map<String, Object> getReal() {
        Map<String,Object> map = new HashMap<String,Object>(100);
        DataHomeBean bean = dataIndexDao.getRealBar();
        List<DataHomeBean> listBean = dataIndexDao.getRealLine();
        map.put("bar",bean);
        map.put("line",listBean);
        return map;
    }

    @Override
    public Map<String, Object> getTool() {
        Map<String,Object> map = new HashMap<String,Object>(100);
        DataHomeBean bean = dataIndexDao.getToolsBar();
        List<DataHomeBean> listBean = dataIndexDao.getToolsLine();
        map.put("bar",bean);
        map.put("line",listBean);
        return map;
    }

    @Override
    public List<ProjectBean> getToolList(ProjectBean o) {
        return dataIndexDao.getToolList(o);
    }

    @Override
    public int addToolInfo(ProjectBean bean) {
        return dataIndexDao.addToolInfo(bean);
    }

    @Override
    public int updateTool(ProjectBean bean) {
        return dataIndexDao.updateTool(bean);
    }

    @Override
    public ProjectBean getListTool(String id) {
        return dataIndexDao.getListTool(id);
    }

    @Override
    public int delToolsById(String id) {
        int num = dao.getBindingOrNot(id);
        if (num > 0){
            return 0;
        }else {
            dataIndexDao.delToolsById(id);
            return 1;
        }
    }

    @Override
    public List<ProjectBean> getActiveList(ProjectBean o) {
        return dataIndexDao.getActiveList(o);
    }

    @Override
    public int delActiveById(ProjectBean bean) {
        bean.setUserId(UserUtil.getLoginUser().getId().toString());
        int cb = dataIndexDao.delUseNum(bean);
        return dataIndexDao.delActiveById(bean);
    }

    @Override
    public int addActive(ProjectBean bean) {
        bean.setUserId(UserUtil.getLoginUser().getId().toString());
        int cb = 0;
        ProjectBean o = dao.getIsExistThisDevice(bean);
        if (o != null) {
            //修改
            cb = dataIndexDao.updateNum(bean);
            dataIndexDao.addUseNum(bean);
        }else {
            cb =  dataIndexDao.addActive(bean);
            dataIndexDao.addUseNum(bean);
        }

        return cb;
    }

    @Override
    public List<ProjectBean> getToolLists(ProjectBean b) {
        return dataIndexDao.getToolLists(b);
    }

    @Override
    public String toolListImport(HttpServletRequest request, MultipartFile file) {
            int successCount = 0;
            int errorCount = 0;
            String fileName = file.getOriginalFilename();
            String res = "";
            try {
                ProjectBean entity = new ProjectBean();
                entity.setToolsProcesName(request.getParameter("toolsProcesName"));
                entity.setToolsName(request.getParameter("toolsName"));
                entity.setToolsModel(request.getParameter("toolsModel"));
                entity.setToolsUnit(request.getParameter("toolsUnit"));
                entity.setToolsNum(request.getParameter("toolsNum"));
                entity.setNotes(request.getParameter("notes"));

                List<JSONObject> lstObj = (List<JSONObject>) ImportNoPhotoExcelHelper.readExcel(file, ProjectBean.class);
                List<ProjectBean> list = new ArrayList<>();
                int i = 0;
                boolean active = false;
                String toolsProcesName = "";
                String toolsName = "";
                String toolsModel = "";
                String toolsNum = "";
                if (lstObj != null && lstObj.size() > 0) {
                    for (JSONObject obj : lstObj) {
                        i++;
                        ProjectBean bean = new ProjectBean();
                        toolsProcesName = String.valueOf(obj.getString("toolsProcesName"));
                        String toolsProcess = dao.ToolsProcesName(toolsProcesName.trim());
                        bean.setToolsProcesName(toolsProcess);
                        if (StringHelper.isEmpty(toolsProcesName) ||  "0.0".equals(toolsProcesName.trim())) {
                            res += "第" + i + "行工序为空;";
                            active = true;
                        }
                        toolsName = String.valueOf(obj.getString("toolsName"));
                        bean.setToolsName(toolsName.trim());
                        if (StringHelper.isEmpty(toolsName) ||  "0.0".equals(toolsName.trim())) {
                            res += "第" + i + "行设备名称为空;";
                            active = true;
                        }
                        toolsModel = String.valueOf(obj.getString("toolsModel"));
                        bean.setToolsModel(toolsModel.trim());
                        if (StringHelper.isEmpty(toolsModel) ||  "0.0".equals(toolsModel.trim())) {
                            res += "第" + i + "行设备型号为空;";
                            active = true;
                        }
                        toolsNum = String.valueOf(obj.getString("toolsNum"));
                        bean.setToolsNum(toolsNum.trim());
                        if (StringHelper.isEmpty(toolsNum) ||  "0.0".equals(toolsNum.trim())) {
                            res += "第" + i + "行设备数量为空;";
                            active = true;
                        }
                        List<ProjectBean> dataList = dataIndexDao.getSelfOwnedRepeat(bean);
                        if (dataList != null && !dataList.isEmpty()){
                            System.out.println(Integer.parseInt(dataList.get(0).getUseNums()));
                            if (Integer.parseInt(toolsNum.trim()) < Integer.parseInt(dataList.get(0).getUseNums()))
                            {
                                res += "第" + i + "行该设备更新数量小于目前使用数量;";
                                active = true;
                            }
                        }
                        bean.setToolsUnit(String.valueOf(obj.getString("toolsUnit")));
                        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>";
                }
                if (ListHelper.isNotEmpty(list)) {
                    for (ProjectBean vo : list) {
                        System.out.println("vo="+vo.toString());
                        int num = dao.getRepeatNum(vo);
                        if (num > 0) {
                            dataIndexDao.updataSelfOwnedImportExcel(vo);
                        }else {
                            dataIndexDao.addSelfOwnedimportExcel(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());
            dao.addImportRecord(bean);
            Map<String, Integer> obj = new HashMap<>(100);
            obj.put("成功导入数量", successCount);
            obj.put("导入异常记录数量", errorCount);
            return res;
    }

    @Override
    public ProjectBean getSurplusQuantity(String id) {
        return dao.getSurplusQuantity(id);
    }
}
