package com.sifang.modules.site.fittingManager.web;

import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.order.entity.CrmOrder;
import com.sifang.modules.order.service.OrderService;
import com.sifang.modules.order.service.SiteSettlementRecordService;
import com.sifang.modules.platform.service.RecevierAddressService;
import com.sifang.modules.site.fittingManager.service.SiteFittingApplyService;
import com.sifang.modules.site.fittingManager.service.SiteFittingRefundService;
import com.sifang.modules.sunshine.SystemSetting.service.SiteReceiptInformationService;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.fittingManager.entity.CrmPlantformFittingRefundMsg;
import com.sifang.modules.sunshine.fittingManager.entity.CrmPlatformFittingRefund;
import com.sifang.modules.sunshine.fittingManager.entity.CrmSiteFittingApply;
import com.sifang.modules.sunshine.fittingManager.service.FittingApplyService;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.entity.CrmPlatformAnnouncement;
import com.sifang.modules.sys.service.CrmPlatformAnnouncementService;
import com.sifang.modules.sys.util.CrmSiteUtils;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.TrimStrMap;
import com.sifang.modules.sys.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
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.util.List;
import java.util.Map;

/**
 * @author lzp
 * @date 2019/10/11 14:28
 * 服务商备件申请调用接口 controller层
 */
@Controller
@RequestMapping("${adminPath}/siteFitting/apply")
public class SiteFittingApplyController extends BaseController {
    @Autowired
    private SiteFittingApplyService sitefittingApplyService;

    @Autowired
    private FittingApplyService fittingApplyService;

    @Autowired
    private SiteFittingRefundService siteRefundService;

    @Autowired
    private SiteSettlementRecordService siteSettlementRecordService;


    @Autowired
    private OrderService orderService;
    @Autowired
    CrmPlatformAnnouncementService crmPlatformAnnouncementService;

    @Autowired
    SiteReceiptInformationService erpCashOutService;
    @Autowired
    private RecevierAddressService recevierAddressService;

    /**
     * 备件申请数据
     * request参数：{
     * page:页码
     * limit:每页条数
     * status:申请状态：0.申请待审核 1.审核通过
     * }
     *
     * @param request
     */
    @ResponseBody
    @RequestMapping("getlAllApplyData")
    public Object getlAllApplyData(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        String pageNo = map.get("page");
        String pageSize = map.get("rows");
        LayuiPage<Record> page = new LayuiPage<>(request);
        if (StringUtil.isNotBlank(pageNo)) {
            page.setPage(Integer.parseInt(pageNo));
        }
        if (StringUtil.isNotBlank(pageSize)) {
            page.setLimit(Integer.parseInt(pageSize));
        }
        String userId = map.get("userId");
        if (StringUtil.isBlank(userId)) {
            return null;
        }
        //工程师
        Record rd = CrmUtils.getEmployeId(userId);
        if (rd != null) {
            map.put("employeId", rd.getStr("id"));
        }

        return sitefittingApplyService.getAllApplyList(page, map, map.get("status"), map.get("siteId"));
    }

    /**
     * 删除标签(request参数： ids: 备件申请id;creator:操作人 )
     *
     * @param request
     */
    @ResponseBody
    @RequestMapping("delFittingApply")
    public Object delFittingApply(HttpServletRequest request) {
        Map<String, Object> map = Maps.newHashMap();
        String id = request.getParameter("id");
        String creator = request.getParameter("creator");
        //小程序中的参数
        String userId = request.getParameter("userId");
        if (StringUtil.isBlank(id)) {
            map.put("code", "401");
            return map;
        }
        Record emp = CrmUtils.getEmployeId(userId); //获取工程师信息
        if (emp == null) {
            return Result.fail("");
        }
        map.put("creator", emp.getStr("name"));
        try {
            Record employe = CrmUtils.getEmployeId(userId); //获取工程师信息
            creator = employe.getStr("name");
            return sitefittingApplyService.delFittingAppply(id, creator);

        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", "404");
        }
        return map;
    }

    /**
     * 获取备件申请详细信息
     * request参数：申请表id
     */
    @ResponseBody
    @RequestMapping("getFittingDetail")
    public Object getFittingDetail(HttpServletRequest request) {
        String id = request.getParameter("id");
        Record re = fittingApplyService.getApplyDetail(id);
        return re;
    }


    /**
     * 在途备件-服务商确认到货
     *
     * @param request {
     *                ids:申请id 的“,”号拼接
     *                creator:操作人姓名
     *                }
     */
    @ResponseBody
    @RequestMapping("confToTheSite")
    public Object confToTheSite(HttpServletRequest request) {
        Map<String, Object> map = Maps.newHashMap();
        try {
            String ids = request.getParameter("ids");
            String creator = request.getParameter("creator");
            //小程序中的参数
            String userType = request.getParameter("userType");
            String userId = request.getParameter("userId");

            Record employe = CrmUtils.getEmployeId(userId); //获取工程师信息
            creator = employe.getStr("name");

            String code = sitefittingApplyService.confirmToTheSite(ids, creator);
            map.put("code", code);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", "404");
        }
        return map;
    }

    /**
     * 服务商备件返厂记录
     */
    @ResponseBody
    @RequestMapping(value = "getsiteFittingResundPage")
    public Object getsiteFittingResundPage(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        String pageNo = map.get("page");
        String pageSize = map.get("rows");
        LayuiPage<Record> page = new LayuiPage<>(request);
        if (StringUtil.isNotBlank(pageNo)) {
            page.setPage(Integer.parseInt(pageNo));
        }
        if (StringUtil.isNotBlank(pageSize)) {
            page.setLimit(Integer.parseInt(pageSize));
        }
        return siteRefundService.getSiteFittingRefund(page, map);
    }


    /**
     * 服务商结算明细
     */
    @ResponseBody
    @RequestMapping(value = "getSiteSettlementList")
    public Object getSiteSettlementList(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        String pageNo = map.get("page");
        String pageSize = map.get("rows");
        LayuiPage<Record> page = new LayuiPage<>(request);
        if (StringUtil.isNotBlank(pageNo)) {
            page.setPage(Integer.parseInt(pageNo));
        }
        if (StringUtil.isNotBlank(pageSize)) {
            page.setLimit(Integer.parseInt(pageSize));
        }
        TrimStrMap parasMap = new TrimStrMap(map);
        siteSettlementRecordService.listData(parasMap, page);
        List<Map<String, Object>> mapx = CrmUtils.returnListMap(page.getData());
        Map<String, Object> sitemap = Maps.newHashMap();
        sitemap.put("count", page.getCount());
        sitemap.put("list", mapx);
        return sitemap;
    }

    /**
     * 结算汇总
     */
    @ResponseBody
    @RequestMapping(value = "getTotalCosts")
    public Object getTotalCosts(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        TrimStrMap parasMap = new TrimStrMap(map);
        Record rd = siteSettlementRecordService.getTotalCosts(parasMap);
        return rd;
    }


    /**
     * 服务商修改备件申请信息
     */
    @ResponseBody
    @RequestMapping(value = "siteUpdateFittingApply")
    public Object siteUpdateFittingApply(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        String id = map.get("id");
        if (StringUtil.isBlank(id)) {
            return Result.fail("203", "");
        }
        String userId = request.getParameter("userId");
        if (StringUtil.isNotBlank(userId)) {

            String name = "";
            String userType = request.getParameter("userType");
            if (User.USER_TYPE_HUI.equals(userType)) {
                Record employe = CrmUtils.getEmployeId(userId); //获取工程师信息
                name = employe.getStr("name");
            } else if (User.USER_TYPE_FWS.equals(map.get("userType"))) {
                String siteId = request.getParameter("siteId");
                Record site = CrmSiteUtils.getSiteBySiteId(siteId);
                if (site != null) {
                    name = site.getStr("name");
                }
            }
            map.put("name", name);
        }

        return sitefittingApplyService.siteUpdateApplyFitting(map);
    }

    /**
     * 获取返厂备件收货地址信息
     */
    @ResponseBody
    @RequestMapping(value = "getReturnFactory")
    public Object getReturnFactory(HttpServletRequest request) {
        String id = request.getParameter("id");
        if (StringUtil.isBlank(id)) {
            return null;
        }
        Record record = fittingApplyService.getApplyDetail(id);
        return record;
    }


    /**
     * 服务商旧件登记
     */
    @ResponseBody
    @RequestMapping(value = "batcholdFitRefundWith")
    public Object batcholdFitRefundWith(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        Map<String, String> maps = Maps.newHashMap();
        Result result = siteRefundService.batcholdFitRefundWith(map);
        maps.put("code", result.getCode());
        return maps;
    }


    /**
     * 删除标签(request参数： ids: 返厂记录id;creator:操作人 )
     *
     * @param request
     */
    @ResponseBody
    @RequestMapping("batchdelectOldFitting")
    public Object batchdelectOldFitting(HttpServletRequest request) {
        Map<String, Object> map = Maps.newHashMap();
        String ids = request.getParameter("ids");
        String creator = request.getParameter("creator");
        if (StringUtil.isBlank(ids)) {
            map.put("code", "401");
            return map;
        }
        String userId = request.getParameter("userId");
        String userType = request.getParameter("userType");
        if (StringUtil.isNotBlank(userId)) {
            String siteId = request.getParameter("siteId");
            if (User.USER_TYPE_HUI.equals(userType)) {
                Record employe = CrmUtils.getEmployeId(userId);
                if (employe != null) {
                    creator = employe.getStr("name");
                }
            } else {
                Record rdsd = CrmSiteUtils.getSiteBySiteId(siteId);
                if (rdsd != null) {
                    creator = rdsd.getStr("name");
                }
            }
        }
        String code = siteRefundService.batchdelectOldFitting(ids, creator);
        map.put("code", code);
        return map;
    }

    /**
     * 查询返厂记录详情
     */
    @ResponseBody
    @RequestMapping(value = "getFittingRefund")
    public Object getFittingRefund(HttpServletRequest request) {
        Map<String, Object> map = Maps.newHashMap();
        String id = request.getParameter("id");
        CrmPlatformFittingRefund fun = siteRefundService.getById(id);
        map.put("refund", fun);
        map.put("sendTime", DateUtils.formatDateTime(fun.getSendTime()));
        map.put("logisticsImgs", fun.getLogisticsImgs());
        CrmPlantformFittingRefundMsg msg = siteRefundService.getByFunId(id);
        if (msg != null) {
            map.put("message", msg.getUpdateDetail());
        }

        if (StringUtil.isNotBlank(fun.getOrderId())) {
            CrmOrder orfde = orderService.getOrderById(fun.getOrderId());
            map.put("order", orfde);
        }
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "uodateRefundFit")
    public Object uodateRefundFit(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        Map<String, Object> maps = Maps.newHashMap();

        String update_name = request.getParameter("update_name");
        String userId = request.getParameter("userId");
        String userType = request.getParameter("userType");
        if (StringUtil.isNotBlank(userId)) {
            String siteId = request.getParameter("siteId");
            if (User.USER_TYPE_HUI.equals(userType)) {
                Record employe = CrmUtils.getEmployeId(userId);
                if (employe != null) {
                    update_name = employe.getStr("name");
                }
            } else {
                Record rdsd = CrmSiteUtils.getSiteBySiteId(siteId);
                if (rdsd != null) {
                    update_name = rdsd.getStr("name");
                }
            }
            map.put("update_name", update_name);
        }

        Result result = siteRefundService.uodateRefundFit(map);

        maps.put("code", result.getCode());
        return maps;
    }


    /**
     * ++
     * 跳转到申请备件页面
     *
     * @return
     */
    @RequestMapping("toAddFitApplyPage")
    public String toAddFitApplyPage(HttpServletRequest request, Model model) {
        String orderId = request.getParameter("orderId");
        String selectAddress = request.getParameter("selectAddress");//选择的地址类型1.自定义地址 2.用户地址 3.网点地址
        if (StringUtil.isBlank(selectAddress)) {
            selectAddress = "3";
        }
        CrmOrder order = orderService.getOrderById(orderId);
        //	Record siteRecord = CrmSiteUtils.getSiteById(order.getSiteId());
        Record orderRecord = CrmSiteUtils.getUserAddress(orderId);//获取用户地址信息
        Record autoRecord = CrmSiteUtils.getAutoInfo(orderId);//获取自定义地址信息
        model.addAttribute("order", order);
        //	model.addAttribute("siteRecord",siteRecord);
        model.addAttribute("autoRecord", autoRecord);
        List<Record> list = recevierAddressService.getSiteRecevierAddress(order.getSiteId());
        if (selectAddress.equals("1")) {//自定义信息
            model.addAttribute("contactsInfo", autoRecord.getStr("delivery_name"));//自定义--收货人
            model.addAttribute("mobileInfo", autoRecord.getStr("delivery_mobile"));//自定义--联系方式
            model.addAttribute("addressInfo", autoRecord.getStr("delivery_address"));//自定义--收货地址
        } else if (selectAddress.equals("2")) {
            model.addAttribute("contactsInfo", orderRecord.getStr("customer_name"));//用户信息--收货人
            model.addAttribute("mobileInfo", orderRecord.getStr("customer_mobile"));//用户信息--联系方式
            model.addAttribute("addressInfo", orderRecord.getStr("province") + orderRecord.getStr("city") + orderRecord.getStr("area") +
                    orderRecord.getStr("customer_address"));//用户信息--收货地址
        } else {
            if (list.size() > 0) {
                Record siteRecord = list.get(0);
                model.addAttribute("contactsInfo", siteRecord.getStr("receiver"));//网点信息--收货人
                model.addAttribute("mobileInfo", siteRecord.getStr("mobile"));//网点信息--联系方式
                model.addAttribute("addressInfo", siteRecord.getStr("siteAddress"));//网点信息--收货地址
            }
        }
        model.addAttribute("sitelist", list);
        model.addAttribute("selectAddress", selectAddress);
        return "modules/factory/fittingManager/fittingApply/addFitApplyPage";
    }

    /**
     * 工程师申请备件
     */
    @ResponseBody
    @RequestMapping(value = "siteApplyFitting")
    public Object siteApplyFitting(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        Result result = sitefittingApplyService.siteApplyFitting(map);

        return result;

    }

    /**
     * 旧件登记详情数据
     */
    @ResponseBody
    @RequestMapping(value = "getFittingApplyOld")
    public Object getFittingApplyOld(HttpServletRequest request) {
        String id = request.getParameter("id");
        System.out.println("配件申请id : " + id);
        if (StringUtil.isEmpty(id)) {
            return Result.fail("201", "id为空");
        }
        CrmSiteFittingApply apply = sitefittingApplyService.getById(id);
        Map<String, Object> map = Maps.newHashMap();
        Map<String, String> appmap = Maps.newHashMap();
        appmap.put("id", apply.getId());
        appmap.put("number", apply.getNumber());
        appmap.put("siteId", apply.getSiteId());
        appmap.put("employeName", apply.getEmployeName());
        appmap.put("employeId", apply.getEmployeId());
        appmap.put("employeFeedback", apply.getEmployeFeedback());
        appmap.put("auditor", apply.getAuditor());
        appmap.put("auditorId", apply.getAuditorId());
        appmap.put("orderId", apply.getOrderId());
        appmap.put("orderNumber", apply.getOrderNumber());
        appmap.put("status", apply.getStatus());
        appmap.put("fittingId", apply.getFittingId());
        appmap.put("fittingCode", apply.getFittingCode());
        appmap.put("fittingVersion", apply.getFittingVersion());
        appmap.put("fittingName", apply.getFittingName());
        appmap.put("fittingImg", StringUtil.isNotEmpty(apply.getFittingImg()) ? apply.getFittingImg() : "");
        appmap.put("fittingApplyNum", apply.getFittingApplyNum().toString());
        appmap.put("fittingAuditNum", apply.getFittingAuditNum() != null ? apply.getFittingAuditNum().toString() : "0");
        appmap.put("oldFittingFlag", apply.getOldFittingFlag());
        appmap.put("createTime", DateUtils.formatDateTime(apply.getCreateTime()));
        appmap.put("auditTime", DateUtils.formatDateTime(apply.getAuditTime()));
        appmap.put("creator", apply.getCreator());
        appmap.put("updateTime", DateUtils.formatDateTime(apply.getUpdateTime()));
        appmap.put("updateName", apply.getUpdateName());
        appmap.put("refuseReason", apply.getRefuseReason());
        appmap.put("auditMarks", apply.getAuditMarks());
        appmap.put("returnFitting", apply.getReturnFitting());
        appmap.put("customerPrice", apply.getCustomerPrice().toString());
        map.put("fitting", appmap);
        map.put("order", orderService.getOrderById(apply.getOrderId()));
        return map;
    }


    /**
     * 服务商申请备件
     */
    @ResponseBody
    @RequestMapping(value = "platApplyFitting")
    public Object platApplyFitting(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        User user = UserUtils.getUser();
        String name = CrmUtils.getUserXM(user);
        map.put("applicantName", name);
        map.put("creator", name);
        map.put("applicantId", user.getId());
        map.put("applicant_type", "3");
        Result result = sitefittingApplyService.siteApplyFitting(map);
        return result;

    }

    /**
     * 服务商删除申请备件
     */
    @ResponseBody
    @RequestMapping(value = "siteDeleteApplyFitting")
    public Object siteDeleteApplyFitting(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        Result result = sitefittingApplyService.siteDeleteApplyFitting(map);
        return result;

    }

    /***
     * 服务商获取通知公告
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "siteGetAnncement")
    public Object getAnncement(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        String pageNo = map.get("page");
        String pageSize = map.get("rows");
        LayuiPage<Record> page = new LayuiPage<>(request);
        if (StringUtil.isNotBlank(pageNo)) {
            page.setPage(Integer.parseInt(pageNo));
        }
        if (StringUtil.isNotBlank(pageSize)) {
            page.setLimit(Integer.parseInt(pageSize));
        }
        TrimStrMap parasMap = new TrimStrMap(map);
        crmPlatformAnnouncementService.listMessageData(parasMap, page);
        Map<String, Object> sitemap = Maps.newHashMap();
        sitemap.put("count", page.getCount());
        sitemap.put("list", page.getData());
        return sitemap;

    }

    /****
     * 服务商获得通知公告的详情
     */
    @ResponseBody
    @RequestMapping(value = "showDetail")
    public Object showDetail(HttpServletRequest request) {
        CrmPlatformAnnouncement announcement = crmPlatformAnnouncementService.get(request.getParameter("id"));
        Map<String, Object> sitemap = Maps.newHashMap();
        sitemap.put("announcement", announcement);
        sitemap.put("hasRead", crmPlatformAnnouncementService.hasRead(request.getParameter("id")));
        return sitemap;
    }

    /*****
     * 未读的通知公告标记已读
     */
    @RequestMapping(value = "markMsgAsRead")
    @ResponseBody
    public Object markMsgAsRead(HttpServletRequest request) {
        String ids = request.getParameter("id");
        Result<Void> ok = crmPlatformAnnouncementService.markMsgAsRead(ids);
        Map<String, Object> sitemap = Maps.newHashMap();
        sitemap.put("code", ok.getCode());
        return sitemap;
    }

    /**
     * 获取服务商的可请款金总额  ***
     */


    @ResponseBody
    @RequestMapping(value = "getSiteInformation")
    public Object getSiteInformation(HttpServletRequest request) {
        return erpCashOutService.getSiteInformation(request.getParameter("siteId"));
    }


    @ResponseBody
    @RequestMapping(value = "getSiteReceiptInformation")
    public Object getSiteReceiptInformation(HttpServletRequest request) {
        return erpCashOutService.getBySiteId(request.getParameter("siteId"));
    }


    /**
     * 获取服务商的请款记录  ***
     */
    @ResponseBody
    @RequestMapping(value = "getSiteCashOutRecord")
    public Object getSiteCashOutRecord(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        String pageNo = map.get("page");
        String pageSize = map.get("rows");
        LayuiPage<Record> page = new LayuiPage<>(request);
        if (StringUtil.isNotBlank(pageNo)) {
            page.setPage(Integer.parseInt(pageNo));
        }
        if (StringUtil.isNotBlank(pageSize)) {
            page.setLimit(Integer.parseInt(pageSize));
        }
        return erpCashOutService.getAllApplyList(page, map, map.get("siteId"));
    }

}
