package com.sifang.modules.order.controller;

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.order.dao.OrdeCallbackDao;
import com.sifang.modules.order.dao.OrderCollectionsDao;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.financialManagement.dao.CrmOrderSiteSettlementDao;
import com.sifang.modules.sunshine.financialManagement.entity.CrmOrderSiteSettlement;
import com.sifang.modules.order.controller.form.OrderAdjustmentRecord;
import com.sifang.modules.order.entity.CrmOrder;
import com.sifang.modules.order.service.OrdeCallbackService;
import com.sifang.modules.order.service.OrderService;
import com.sifang.modules.order.service.SiteSettlementRecordService;
import com.sifang.modules.order.utils.OrderUtils;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.StringUtil;
import com.sifang.modules.sys.util.CrmSiteUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.TranslationUtils;
import com.sifang.modules.sys.util.TrimStrMap;
import com.sifang.modules.sys.web.DjxBaseController;
import com.sun.xml.bind.v2.model.core.ID;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 服务商结算明细、结算汇总。
 */
@Controller
@RequestMapping("${adminPath}/settlement/site/stat/")
public class SiteSettlementRecordController extends DjxBaseController {

    @Autowired
    SiteSettlementRecordService siteSettlementRecordService;
    @Autowired
    OrderService orderService;

    @Autowired
    private OrdeCallbackService callService;
    @Autowired
    private OrdeCallbackDao ordeCallbackDao;
    @Autowired
    CrmOrderSiteSettlementDao crmOrderSiteSettlementDao;
    /**
     * 结算明细列表。
     */
    @RequestMapping(value = "list")
    public String list(HttpServletRequest request, Model model) {
        model.addAttribute("sites", CrmSiteUtils.getSiteConcise());

        return "modules/order/settlement/record/list";
    }

    /**
     * 结算明细列表数据。
     */
    @RequestMapping(value = "listData")
    @ResponseBody
    public String listData(HttpServletRequest request) {
        LayuiPage<Record> page = new LayuiPage<>(request);
        TrimStrMap parasMap = new TrimStrMap(getParasMap(request));
        siteSettlementRecordService.listData(parasMap, page);
        List<Record> data = page.getData();
        for (Record r : data) {
            r.set("_warranty_type", TranslationUtils.transWarrantyType(r.getStr("warranty_type")));
        }

        return page.renderJson();
    }

    /**
     * 结算汇总列表。
     */
    @RequestMapping(value = "summaryList")
    public String summaryList(Model model) {
        model.addAttribute("sites", CrmSiteUtils.getSiteConcise());
        return "modules/order/settlement/record/summaryList";
    }



    /**
     * 结算总额页面。
     */
    @RequestMapping(value = "costDetail")
    public String costDetail(HttpServletRequest request, Model model) {
        String id = request.getParameter("id");
        String total_costs = request.getParameter("total_costs");
        CrmOrderSiteSettlement c = crmOrderSiteSettlementDao.get(id);
        model.addAttribute("c", c);
        model.addAttribute("total_costs", total_costs);
        return "modules/order/settlement/record/costDetail";
    }

    /**
     * 结算调整。
     */
    @RequestMapping(value = "orderAdjustment")
    @ResponseBody
    public Result<Void> orderAdjustment(@Valid OrderAdjustmentRecord r, BindingResult result) {
        if (result.hasErrors()) {
            throw new RuntimeException("form binding error");
        }

        return siteSettlementRecordService.orderAdjustment(r);
    }

    /**
     * 结算汇总列表数据。
     */
    @RequestMapping(value = "summaryListData")
    @ResponseBody
    public String summaryListData(HttpServletRequest request) {
        LayuiPage<Record> page = new LayuiPage<>(request);
        TrimStrMap parasMap = new TrimStrMap(getParasMap(request));
        siteSettlementRecordService.summaryListData(parasMap, page);
        return page.renderJson();
    }

    /**
     * 结算汇总列表合计行数据。
     */
    @RequestMapping(value = "summaryData")
    @ResponseBody
    public Object summaryData(HttpServletRequest request) {
        TrimStrMap parasMap = new TrimStrMap(getParasMap(request));
        return siteSettlementRecordService.totalRowData(parasMap);
    }

    @Autowired
    private OrderCollectionsDao orderCollectionsDao;
    /**
     *平台给服务商结算
    */
    @RequestMapping(value = "getSettlement")
    public String getSettlement(HttpServletRequest request,Model model){
        String orderId = request.getParameter("orderId");
        if(StringUtil.isNotBlank(orderId)){
            CrmOrder order = orderService.getOrderById(orderId);
            Map<String ,Object> map = callService.getMileagePayment(order,"2");
            model.addAttribute("map",map);
            model.addAttribute("order",order);
            /*long hour= DateUtils.pastHour(order.getEndTime(),order.getSiteProcessTime());*/
            if(order.getEndTime() !=null && order.getProcessTime() !=null){
                String hour= DateUtils.pastHour(order.getEndTime(),order.getProcessTime());
                model.addAttribute("hour",hour);
            }else{
                model.addAttribute("hour",0);
            }
            //服务商结算方案
            BigDecimal serviceCosts = new BigDecimal("0.00");
           Record record = siteSettlementRecordService.getSiteSettlementTemplate(order,order.getServiceMeasures());
            if(record != null){
                serviceCosts = record.getBigDecimal("charge_amount");
                if("安装".equals(order.getServiceType())){
                    BigDecimal capacity = order.getApplianceCapacity();
                    serviceCosts = serviceCosts.multiply(capacity);
                }
           }
            model.addAttribute("settle",record);
            model.addAttribute("serviceCosts",serviceCosts.setScale(2,BigDecimal.ROUND_HALF_UP));
            //查询工单回访信息
            model.addAttribute("call", ordeCallbackDao.getOrderCallback(orderId));
            //工单的收款凭证
            model.addAttribute("collectionVoucher" ,siteSettlementRecordService.getOrderCollection(orderId));
        }
          return "modules/order/platform/setelOrder";
    }
    /**
     *平台重新给服务商结算
    */
    @RequestMapping(value = "siteAgainSettle")
    public String siteAgainSettle(HttpServletRequest request,Model model){
        String orderId = request.getParameter("orderId");
        if(StringUtil.isNotBlank(orderId)){
            CrmOrder order = orderService.getOrderById(orderId);
            Map<String ,Object> map = callService.getMileagePayment(order,"2");
            model.addAttribute("order",order);
            model.addAttribute("map",map);
            //long hour= DateUtils.pastHour(order.getEndTime(),order.getSiteProcessTime());
            if(order.getEndTime() !=null && order.getProcessTime() !=null){
                String hour= DateUtils.pastHour(order.getEndTime(),order.getProcessTime());
                model.addAttribute("hour",hour);
            }else{
                model.addAttribute("hour",0);
            }
            CrmOrderSiteSettlement settle = orderService.getOrderSiteSettlementByOrderId(orderId);
            model.addAttribute("siteSet",settle);
            //查询工单回访信息
            model.addAttribute("call", ordeCallbackDao.getOrderCallback(orderId));
            //服务商结算方案
            Record list = siteSettlementRecordService.getSiteSettlementTemplate(order,order.getServiceMeasures());
            model.addAttribute("list",list);
            //工单的收款凭证
            model.addAttribute("collectionVoucher" ,siteSettlementRecordService.getOrderCollection(orderId));
        }
          return "modules/order/platform/againSetelOrder";
    }


    /**
     * 获取服务商结算方案下具体收费项金额
     * 服务商
     */
    @ResponseBody
    @RequestMapping(value = "getSiteTemplateByNumber")
    public Object getSiteTemplateByNumber(HttpServletRequest request){
        String number = request.getParameter("number");
        String category = request.getParameter("category");
        List<Record> rds =  siteSettlementRecordService.getSiteTemplateByNumber(number,category);
        return rds;
    }


    /**
     * 获取结算方案
    */
    @ResponseBody
    @RequestMapping(value = "getSiteServiceMeasuresByStep")
    public Object getSiteServiceMeasuresByStep(HttpServletRequest request){
        String orderId = request.getParameter("orderId");
        String serviceStep = request.getParameter("serviceStep");
        if(StringUtil.isBlank(orderId) || StringUtil.isBlank(serviceStep)){
            return null;
        }
        CrmOrder order = orderService.getOrderById(orderId);
        Record  list = siteSettlementRecordService.getSiteSettlementTemplate(order,serviceStep);
        return list;
    }

    /**
     * 平台给服务商结算
    */
    @RequestMapping(value = "saveSettlementOrder")
    @ResponseBody
    public Object saveSettlementOrder(HttpServletRequest request,CrmOrderSiteSettlement set){
        Map<String,String> map = getParams(request);
        Result result = new Result();
        try{
            result =  siteSettlementRecordService.saveSiteSettlement(set,map);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode("402");
        }

        return result;
    }


    /**
     * 平台给服务商重新结算
    */
    @RequestMapping(value = "saveAgainSettlementOrder")
    @ResponseBody
    public Object saveAgainSettlementOrder(HttpServletRequest request,CrmOrderSiteSettlement set){
        Map<String,String> map = getParams(request);
        Result result =  siteSettlementRecordService.saveAgainSettlementOrder(set,map);
        return result;
    }

    /**
     * 根据服务类型获取服务措施
    */
    @ResponseBody
    @RequestMapping(value = "getOrderServiceMeasures")
    public Object getOrderServiceMeasures(HttpServletRequest request){
        String type= request.getParameter("type");
        List<Record> list = OrderUtils.getOrderServiceMeasures(type);
        return  list ;
    }


}
