package com.zhongdao.jlr.business.service.impl;

import com.util.UtilTools;
import com.util.Vo;
import com.zhongdao.jlr.business.dao.EnterpriseDao;
import com.zhongdao.jlr.business.service.EnterpriseService;
import com.zhongdao.jlr.business.vo.EnterpriseExcelVO;
import com.zhongdao.jlr.pojo.BaseUser;
import com.zhongdao.jlr.pojo.EnterpriseJlr;
import com.zhongdao.jlr.util.GeoAddressCenter;
import jodd.util.BCrypt;
import org.apache.http.util.TextUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/***
 * 处理经销商维护的业务
 */
@Service(value = "enterpriseServiceImpl")
public class EnterpriseServiceImpl implements EnterpriseService {

    @Autowired
    private EnterpriseDao enterpriseDao;

    @Override
    public Vo searchEnterprise(String name, String abbrCode,
                              Integer page, Integer rows) {
        return enterpriseDao.searchEnterprise(name,abbrCode,page, rows);
    }

    @Override
    public boolean deleteById(String id) {
        return enterpriseDao.deleteById(id);
    }

    @Override
    public boolean putEnterprise(EnterpriseJlr enterprise, String newPassword, String confirmPassword,String UID) throws
            Exception {
        //声明一个用户对象
        List<BaseUser> systemUser =new ArrayList<>();
        String sql=null;
        //根据供应商id获取用户信息
        if(UID == null) {
                sql = "select id from jlr_user where enterprise_id is not null and enterprise_id = "+ enterprise.getId();
        }else{
                sql = "select id from jlr_user where  enterprise_id is not null and enterprise_id= "+ enterprise.getId()+ " and id = "+UID;
        }
        List list=enterpriseDao.getRsBySql(sql);
        for (int i = 0; i < list.size(); i++) {
            //声明一个菜单对象并将信息放入对象里面
            BaseUser baseUser = new BaseUser();
            baseUser.setId((Integer)list.get(i));
            //将对象放入集合中
            systemUser.add(baseUser);
        }
        //如果没有供应商id说明此操作为添加
        if (enterprise.getId() == null || enterprise.getId() < 1) {
            //临时主键生成
            enterprise.setId(Integer.valueOf((System.currentTimeMillis() / 10 + "").substring(3)));
            //声明一个当前时间的对象
            Date date=new Date();
            enterprise.setCreate_time(date);
        }
        //如果经纬度不为空则根据经纬度获取地区编码，并将其放入供应商对象中
        if (enterprise.getLon() != null && enterprise.getLat() != null) {
            String areaCode = GeoAddressCenter.getGeoAdcode(enterprise.getLon() + "", enterprise.getLat() + "");
            enterprise.setArea_code(areaCode);
        } else {
            return false;
        }
        //如果用户信息不为空则更新用户信息
        if (systemUser != null && !TextUtils.isEmpty(newPassword)) {
            for(BaseUser baseUser:systemUser){
                String password=BCrypt.hashpw(newPassword,BCrypt.gensalt());
                baseUser.setPassword(password);
                enterpriseDao.putSystemUser(baseUser);
            }
        }
        Date updateDate=new Date();
        enterprise.setUpdate_time(updateDate);
        //添加或修改用户信息
        return enterpriseDao.putEnterprise(enterprise);
    }

    @Override
    public EnterpriseJlr getById(String id) {
        return enterpriseDao.getById(id);
    }

    @Override
    public JSONObject expordata(HttpServletRequest request, String name, String abbrCode) {
        //声明一个集合用于存放供应商信息
        List listExcel = new ArrayList();
        StringBuffer hqlSb = new StringBuffer("from EnterpriseJlr where 1=1");
        if (!TextUtils.isEmpty(name)) {
            hqlSb.append(" and name like '%" + name.trim() + "%' ");
        }
        if (!TextUtils.isEmpty(abbrCode)) {
            hqlSb.append(" and abbr_code like '%" + abbrCode.trim() + "%'");
        }
        //声明一个json对象
        JSONObject jsonObject = new JSONObject();
        List list = null;
        try {
            //根据搜索条件获取供应商信息
            list = enterpriseDao.getRsByHql(hqlSb.toString());
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("result", "1");// 0:成功，1失败
            jsonObject.put("msg", "导出失败！");
        }
        if (list != null && list.size() > 0) {
            //声明一个excel表头
            EnterpriseExcelVO header = new EnterpriseExcelVO("VIN码", "经销商名称", "经销商代码", "地址",
                    "24小时联系人1姓名", "24小时联系人1电话", "24小时联系人1职务", "24小时联系人2姓名", "24小时联系人2电话",
                    "24小时联系人2职务", "对账联系人姓名", "对账联系人电话", "对账联系人职务", "邮箱", "服务类型", "车型", "首次销售日期");
            listExcel.add(header);
            //遍历供应商信息并将其放入供应商对象中
            for (int i = 0; i < list.size(); i++) {
                EnterpriseExcelVO enterpriseExcelVO = new EnterpriseExcelVO();
                EnterpriseJlr enterpriseJlr = (EnterpriseJlr) list.get(i);
                enterpriseExcelVO.setVinCode(enterpriseJlr.getVin_code());
                enterpriseExcelVO.setName(enterpriseJlr.getName());
                enterpriseExcelVO.setAbbrCode(enterpriseJlr.getAbbr_code());
                enterpriseExcelVO.setAddress(enterpriseJlr.getAddress());
                enterpriseExcelVO.setContract(enterpriseJlr.getContact());
                enterpriseExcelVO.setJob1(enterpriseJlr.getJob1());
                enterpriseExcelVO.setPhone1(enterpriseJlr.getPhone1());
                enterpriseExcelVO.setContact2(enterpriseJlr.getContact2());
                enterpriseExcelVO.setPhone2(enterpriseJlr.getPhone2());
                enterpriseExcelVO.setJob2(enterpriseJlr.getJob2());
                enterpriseExcelVO.setContact3(enterpriseJlr.getContact3());
                enterpriseExcelVO.setJob3(enterpriseJlr.getJob3());
                enterpriseExcelVO.setPhone3(enterpriseJlr.getPhone3());
                enterpriseExcelVO.setBrands(enterpriseJlr.getBrands());
                enterpriseExcelVO.setServiceQualification(enterpriseJlr.getService_qualification());
                enterpriseExcelVO.setFirstSaleDate(enterpriseJlr.getFirst_sale_date());
                enterpriseExcelVO.setCarType(enterpriseJlr.getCar_type());
                listExcel.add(enterpriseExcelVO);
            }
            //格式转换
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String dateTime = simpleDateFormat.format(new Date());
            //导出路径
            String path = request.getRealPath("attached") + File.separator + "enterprise_" + dateTime + ".xlsx";
            String webUrl = UtilTools.getWebAddress(request) + File.separator + "attached" + File.separator + "enterprise_" + dateTime + ".xlsx";
            //  webUrl = URLEncoder.encode(webUrl, "UTF-8");
            //所有信息保存到excel表中并导出表格
            boolean b = new EnterpriseExcelVO().saveAll(listExcel, path);
            if (b) {
                jsonObject.put("result", "0");// 0:成功，1失败
                jsonObject.put("msg", "导出成功！");
                jsonObject.put("webUrl", webUrl);
            }
        }
        return jsonObject;
    }

}
