package com.sifang.modules.customer.controller;

import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.dao.CrmCustomerCommentDao;
import com.sifang.modules.customer.dao.CustomerDao;
import com.sifang.modules.customer.entity.CrmCustomerComment;
import com.sifang.modules.customer.entity.Customer;
import com.sifang.modules.order.dao.OrderDao;
import com.sifang.modules.order.entity.CrmOrder;
import com.sifang.modules.order.utils.GetDistance;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.web.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

@Controller
@RequestMapping(value = "${adminPath}/comment")
public class CrmCustomerCommentController extends BaseController {
    @Value("${sync.sunshine.app.key}")
    private String APPKR;

    @Value("${sync.sunshine.app.prefix}")
    private String prefixUrl;

    private Logger logger = LoggerFactory.getLogger(CrmCustomerCommentController.class);

    @Autowired
    CrmCustomerCommentDao crmCustomerCommentDao;
    @Autowired
    OrderDao orderDao;
    @Autowired
    CustomerDao customerDao;

    @RequestMapping(value = "comment")
    public String CustomerList(HttpServletRequest request, Model model) {
        String orderId = request.getParameter("orderId");
        String userId = request.getParameter("userId");
        model.addAttribute("orderId", orderId);
        model.addAttribute("userId", userId);
        return "modules/yangguang/customer/comment/comment";
    }

    @RequestMapping(value = "commentToDetatil")
    public String commentToDetatil(HttpServletRequest request, Model model) {
        String orderId = request.getParameter("orderId");
        if (orderId!=null) {
            Record record = crmCustomerCommentDao.getbyOrderId(orderId);
            model.addAttribute("comment", record);
        }
        return "modules/yangguang/customer/comment/commentdetail";
    }

    @ResponseBody
    @RequestMapping(value = "saveComment")
    public Result getCustomerList(HttpServletRequest request){
        Result result = new Result();
        String orderId = request.getParameter("orderId");
        String userId = request.getParameter("userId");
        if (StringUtil.isBlank(orderId)) {
            result.setCode("400");
            return result;
        }
        Record record = crmCustomerCommentDao.getbyOrderId(orderId);
        if (record != null) {
            result.setCode("505");
            return result;
        }
        CrmOrder order = orderDao.get(orderId);
        if (order == null) {
            result.setCode("505");
            return result;
        }
        try {
        Customer customer = customerDao.getCustomerBuserId(userId);
      /*  String siteId = CrmUtils.getSiteId(UserUtils.getUser());
        String siteName = CrmUtils.getUserXM(UserUtils.getUser());*/
        String superviseId = request.getParameter("superviseId");
        String ifCharge = request.getParameter("ifcharge");
        String chargeMoney = request.getParameter("money");
        Date createTime = new Date();
        CrmCustomerComment comment = new CrmCustomerComment();
        comment.setOrderId(orderId);
        comment.setOrderNumber(order.getNumber());
            if (customer != null) {
                comment.setCustomerId(customer.getId());
                comment.setCustomerName(customer.getUserAccount());
            }

        comment.setEmployeName(order.getEmployeName());
        comment.setSiteId(order.getSiteId());
        comment.setSiteName(order.getSiteName());
        comment.setSuperviseId(superviseId);
        comment.setIfCharge(ifCharge);
        if(StringUtil.isBlank(chargeMoney)){
            chargeMoney = "0";
        }
        comment.setChargeMoney(new BigDecimal(chargeMoney));
        comment.setCreateTime(createTime);
            crmCustomerCommentDao.save(comment);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Exception e: {} ",e);
            result.setCode("401");
            result.setMsg("提交失败，请联系平台人员");
            return result;
        }
        result.setOk();
        return result;
    }

    @RequestMapping(value = "malfunction")
    public String malfunction(HttpServletRequest request, Model model) {
        Gson gson = new Gson();
       /* String sendGe1 = GetDistance.sendGet("http://api.isolarcloud.com/sungws/AppService","service=login&login_type=1&sys_code=901&user_account=15938552555&user_password=12345678&appkey=047AA5BB868E2D0CBA10A4D638586EEF");
        JsonObject json3 = gson.fromJson(sendGe1, JsonObject.class);
        JsonObject json4 = gson.fromJson(json3.get("result_data"), JsonObject.class);
        String token = json4.get("token").getAsString();*/
        String faultCode = request.getParameter("fault_code");//2740.201907.339df55822195
        //String faultCode = "2740.201907.339df55822195";
        String userId = request.getParameter("userId");
        if (StringUtil.isBlank(userId)) {
            return "modules/yangguang/customer/comment/malfunction";
        }
        Customer customer = customerDao.getCustomerBuserId(userId);

        String token = customer.getToken();
        String sendGet = GetDistance.sendGet("http://api.isolarcloud.com/sungws/AppService","service=getFaultDetail&fault_code="+faultCode+"&token="+token+"&appkey=047AA5BB868E2D0CBA10A4D638586EEF");

        JsonObject json1 = gson.fromJson(sendGet, JsonObject.class);
        String state = json1.get("result_code").getAsString();
        Map<String,String> map = Maps.newHashMap();
        if("1".equals(state)){
            JsonObject json2 = gson.fromJson(json1.get("result_data"), JsonObject.class);
            map.put("fault_name",json2.get("fault_name").getAsString());
            map.put("device_name",json2.get("device_name").getAsString());
            map.put("device_model",json2.get("device_model").getAsString());
            map.put("device_type_name",json2.get("device_type_name").getAsString());
            map.put("fault_time",json2.get("fault_time").getAsString());
            map.put("fault_desc",json2.get("fault_desc").getAsString());
            JsonArray array = json2.get("repair_advise").getAsJsonArray();
            for (JsonElement jsonElement : array) {
                JsonObject object = jsonElement.getAsJsonObject();
                if (object.get("step_number").getAsString().equals("0")) {
                    map.put("reason",object.get("step_content").getAsString());
                } else if (object.get("step_number").getAsString().equals("1")) {
                    map.put("restore", object.get("step_content").getAsString());
                } else {
                    map.put("suggest",object.get("step_content").getAsString());
                }
            }
        }
        model.addAttribute("map", map);
        return "modules/yangguang/customer/comment/malfunction";
    }



}
