package com.yihu.jw.base.service.device;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.base.dao.device.DeviceDao;
import com.yihu.jw.base.dao.device.DeviceDetailDao;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.mysql.query.BaseJpaService;
import jxl.Workbook;
import jxl.write.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * Created by Bing on 2021/9/22.
 */
@Service
public class DeviceManageService extends BaseJpaService<DeviceDetail,DeviceDetailDao> {

    @Autowired
    private DeviceDetailDao deviceDetailDao;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private DeviceDao deviceDao;

    public JSONObject saveWlyyDevice(String json)throws Exception{
        JSONObject result = new JSONObject();
        DeviceDetail deviceDetail = objectMapper.readValue(json, DeviceDetail.class);
        String deviceName = deviceDetail.getDeviceName();
        String deviceModel = deviceDetail.getDeviceModel();
        String categoryCode= deviceDetail.getCategoryCode();
        String deviceSn = deviceDetail.getDeviceCode();
        String manufacturer = deviceDetail.getManufacturer();
        if (StringUtils.isBlank(deviceName)||StringUtils.isBlank(deviceModel)||StringUtils.isBlank(categoryCode)||
                StringUtils.isBlank(deviceSn)||StringUtils.isBlank(manufacturer)){
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            result.put(ResponseContant.resultMsg,"数据数据错误,必填字段为空");
            return result;
        }
        String sim = deviceDetail.getSim();
        String iccid = deviceDetail.getIccid();
        String imsi = deviceDetail.getImsi();
        DeviceDetail tmps1 =  deviceDetailDao.findBySn(deviceSn);
        if (tmps1 != null) {
            if (tmps1.getId().longValue()!=deviceDetail.getId().longValue()) {
                result.put(ResponseContant.resultFlag, ResponseContant.fail);
                result.put(ResponseContant.resultMsg, "设备SN码重复");
                return result;
            }
        }
        if (StringUtils.isNotBlank(sim)){
            List<DeviceDetail> tmps = deviceDetailDao.findBySim(sim);
            if (tmps.size()>0){
                if (tmps.get(0).getId().longValue()!=deviceDetail.getId().longValue()) {
                    result.put(ResponseContant.resultFlag,ResponseContant.fail);
                    result.put(ResponseContant.resultMsg,"sim卡号重复");
                    return result;
                }
            }
        }
        if (StringUtils.isNotBlank(iccid)){
            List<DeviceDetail> tmps =  deviceDetailDao.findByIccid(iccid);
            if (tmps.size()>0){
                if (tmps.get(0).getId().longValue()!=deviceDetail.getId().longValue()) {
                    result.put(ResponseContant.resultFlag,ResponseContant.fail);
                    result.put(ResponseContant.resultMsg,"iccid重复");
                    return result;
                }
            }
        }
        if (StringUtils.isNotBlank(imsi)){
            List<DeviceDetail> tmps =  deviceDetailDao.findByImsi(imsi);
            if (tmps.size()>0){
                if (tmps.get(0).getId().longValue()!=deviceDetail.getId().longValue()) {
                    result.put(ResponseContant.resultFlag,ResponseContant.fail);
                    result.put(ResponseContant.resultMsg,"imsi重复");
                    return result;
                }
            }
        }
        //名称、设备类型、设备型号判断
        if (0==deviceDao.findTotalByCategoryCode(categoryCode)){
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            result.put(ResponseContant.resultMsg,"设备类型不存在");
            return result;
        }
        if (0==deviceDao.findTotalByCategoryCodeAndName(categoryCode,deviceName)){
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            result.put(ResponseContant.resultMsg,"设备名称不存在");
            return result;
        }
        if (0==deviceDao.findTotalByCodeNameModel(categoryCode,deviceName,deviceModel)){
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            result.put(ResponseContant.resultMsg,"设备型号不存在");
            return result;
        }
        Device device = deviceDao.findByModel(deviceModel);
        if (device!=null){
            deviceDetail.setDeviceType(device.getDeviceType());
            if ("1".equals(device.getIsMultiUser())){
                deviceDetail.setBindingCount("{\"1\":\"0\",\"2\":\"0\"}");
            }else if ("0".equals(device.getIsMultiUser())){
                deviceDetail.setBindingCount("{\"1\":\"0\"}");
            }
        }
        if (null==deviceDetail.getId()){
            deviceDetail.setContactStatus(1);
        }
        deviceDetailDao.save(deviceDetail);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,"success");
        return result;
    }

    public void initCategoryCode(){
        String sql = " select GROUP_CONCAT(model) model,category_code from dm_device GROUP BY category_code ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        for (Map<String,Object> tmp:list){
            String category = tmp.get("category_code").toString();
            String model = tmp.get("model").toString();
            model = "'"+model.replace(",","','")+"'";
            sql = " UPDATE wlyy_devices set category_code='"+category+"' where device_model in ("+model+") ";
            jdbcTemplate.execute(sql);
        }
    }


    public void write(OutputStream os, List ls) throws Exception {
        write(Workbook.createWorkbook(os), ls);
    }

    public void write(WritableWorkbook wwb, List ls) throws Exception {
        try {
            WritableSheet ws;
            ws = wwb.createSheet("sheet", 1);
            addHeader(ws);
            int i = 1;
            for (DeviceDetail tmp : (List<DeviceDetail>) ls) {
                Map<String, String> map = tmp.getErrorMsgMap();
                addCell(ws, i, 0, tmp.getManufacturer(), map.get("manufacturer"));
                addCell(ws, i, 1, tmp.getDeviceName(), map.get("deviceName"));
                addCell(ws, i, 2, tmp.getDeviceModel(), map.get("deviceModel"));
                addCell(ws, i, 3, tmp.getDeviceCode(), map.get("deviceCode"));
                addCell(ws, i, 4, tmp.getSim(), map.get("sim"));
                addCell(ws, i,5,  tmp.getIccid(), map.get("iccid"));
                addCell(ws, i,6,  tmp.getImsi(), map.get("imsi"));
                i++;
            }
            wwb.write();
            wwb.close();
        } catch (IOException e) {
            e.printStackTrace();
            if (wwb != null) wwb.close();
            throw e;
        }
    }

    public void addHeader(WritableSheet ws) throws WriteException {
        String[] header = {"厂商(必填)", "设备名称(必填)", "设备型号(必填)", "设备SN(必填)", "sim卡号",  "iccid卡号", "imsi卡号"};
        int i = 0;
        for (String h : header) {
            addCell(ws, 0, i, h);//表名，行，列，header
            i++;
        }
    }

    //添加单元格内容
    public void addCell(WritableSheet ws, int row, int column, String data) throws WriteException {
        Label label = new Label(column, row, data);
        ws.addCell(label);
    }

    //添加单元格内容
    public void addCell(WritableSheet ws, int row, int column, String data, String memo) throws WriteException {
        Label label = new Label(column, row, data);
        if (!org.springframework.util.StringUtils.isEmpty(memo)) {
            WritableCellFeatures cellFeatures = new WritableCellFeatures();
            cellFeatures.setComment(memo);
            label.setCellFeatures(cellFeatures);
        }
        ws.addCell(label);
    }

    public JSONObject findDmDeviceDictName(String code, String name) {
        JSONObject result = new JSONObject();
        String deviceSql = "select id, name, model from dm_device where 1=1 ";
        if (StringUtils.isNotBlank(code)){
            deviceSql+=" and category_code = "+ code;
        }
        if (StringUtils.isNotBlank(name)){
            deviceSql+=" and name = " + "'" + name + "'";
        }

        List<Map<String, Object>> deviceName = jdbcTemplate.queryForList(deviceSql);
        result.put("deviceName",deviceName);

        return result;

    }

}
