package com.sifang.modules.sunshine.fittingManager.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.SourceConstants;
import com.sifang.modules.order.utils.WebPageFunUtils;
import com.sifang.modules.platform.controller.form.ComplaintReply;
import com.sifang.modules.platform.fittingManager.dao.PlatformFittingDao;
import com.sifang.modules.platform.fittingManager.entity.PlatformFitting;
import com.sifang.modules.platform.service.RecevierAddressService;
import com.sifang.modules.site.fittingManager.dao.SiteFittingApplyMsgDao;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.fittingManager.dao.CrmPlatformFittingApplyDao;
import com.sifang.modules.sunshine.fittingManager.dao.CrmSiteFittingApplyDao;
import com.sifang.modules.sunshine.fittingManager.dao.CrmSiteFittingDao;
import com.sifang.modules.sunshine.fittingManager.dao.PlantformFittingApplyMsgDao;
import com.sifang.modules.sunshine.fittingManager.entity.CrmPlantformFittingApply;
import com.sifang.modules.sunshine.fittingManager.entity.CrmSiteFitting;
import com.sifang.modules.sunshine.fittingManager.entity.PlantformFittingApplyMsg;
import com.sifang.modules.sunshine.fittingManager.entity.SiteFittingApplyMsg;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class CrmSiteFittingService extends BaseService {

    @Autowired
    CrmSiteFittingDao crmSiteFittingDao;
    @Autowired
    CrmPlatformFittingApplyDao crmPlatformFittingApplyDao;
    @Autowired
    PlatformFittingDao platformFittingDao;
    @Autowired
    PlantformFittingApplyMsgDao plantformFittingApplyMsgDao;
    @Autowired
    RecevierAddressService recevierAddressService;


    public LayuiPage getSiteFittingPage(LayuiPage pagee, Map<String,String> map){
        String siteId = CrmUtils.getSiteId(UserUtils.getUser());
        pagee.setData(crmSiteFittingDao.getFittingList(pagee,map,siteId));
        pagee.setCount(crmSiteFittingDao.getFittingCount(map,siteId));
        return pagee;
    }

    public LayuiPage getPlatformFittingPage(LayuiPage pagee, Map<String,String> map){
        pagee.setData(crmSiteFittingDao.getPlatformFittingList(pagee,map));
        pagee.setCount(crmSiteFittingDao.getPlatformFittingCount(map));
        return pagee;
    }

    public List<Record> getSiteFitting(String ids ){
        String sql =" select * from crm_site_fitting where id in ("+ StringUtil.joinInSql(ids.split(","))+") ";
        return Db.find(sql);
    }

    public List<Record> getPlatformFitting(String ids ){
        String sql =" select * from crm_platform_fitting where id in ("+ StringUtil.joinInSql(ids.split(","))+") ";
        return Db.find(sql);
    }

    /**
     * 备件申请保存
     */
    @SuppressWarnings("unchecked")
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> fittingInstockSave(HttpServletRequest request) {
        User user = UserUtils.getUser();
        String siteId = CrmUtils.getSiteId(user);
        String jsonStr = request.getParameter("data1");
        JSONObject json = JSON.parseObject(jsonStr);
        if (json.size()==0) {
            Result.fail("401", "请选择数据");
        }
        String name = CrmUtils.getUserXM(user);
     /*   Record data = recevierAddressService.getAddress(siteId);
        if (data==null) {
            return Result.fail("402");
        }*/
        for (Map.Entry<String, Object> js : json.entrySet()) {
            Map<String, String> map = (Map<String, String>) js.getValue();
            String fitId = map.get("fitId");
            String num = map.get("amount");
            String remarks = map.get("remarks");
            CrmPlantformFittingApply apply = new CrmPlantformFittingApply();
            CrmSiteFitting fitting = crmSiteFittingDao.get(fitId);
            Record fit = platformFittingDao.getFittingByCode(fitting.getCode());
            apply.setNumber(CrmUtils.no());
            apply.setSiteId(siteId);
            apply.setSiteName(name);
            apply.setApplicantId(user.getId());
            apply.setApplicantName(name);
            apply.setApplicantType(SourceConstants.ZERO);
            apply.setApplyMarks(remarks);
            apply.setFittingId(fitting.getPlatformFittingId());
            apply.setFittingCode(fitting.getCode());
            apply.setFittingName(fitting.getName());
            apply.setFittingVersion(fitting.getVersion());
            apply.setFittingImg(fitting.getImg());
            apply.setSuitPrinter(fitting.getSuitPrinter());
            apply.setApplyNum(new BigDecimal(num));
            apply.setCreateTime(new Date());
            apply.setCreator(name);
            apply.setDeliveryName(request.getParameter("receiver"));
            apply.setDeliveryMobile(request.getParameter("mobile"));
            apply.setDeliveryAddress(request.getParameter("province")+request.getParameter("city")+request.getParameter("area")+request.getParameter("address"));
            apply.setSitePrice(fit.getBigDecimal("site_price"));
            crmPlatformFittingApplyDao.save(apply);
            PlantformFittingApplyMsg msg = new PlantformFittingApplyMsg();
            if(msg == null){
                msg = new PlantformFittingApplyMsg();
                msg.setFittingApplyId(apply.getId());
                msg.setSiteId(apply.getSiteId());
            }
            ComplaintReply tamd = new ComplaintReply();
            tamd.setT(DateUtils.getDateTime());
            tamd.setP(name);
            tamd.setC(name + " 申请 - 向平台申请备件;");
            String strmsg = WebPageFunUtils.appendProcessDetail(tamd, msg.getMessage());
            msg.setMessage(strmsg);
            msg.setSiteId(CrmUtils.getSiteId(user));
            msg.setFittingApplyId(apply.getId());
            plantformFittingApplyMsgDao.save(msg);
        }
        return Result.ok("申请成功！");
    }

    /**
     * 备件申请保存
     */
    @SuppressWarnings("unchecked")
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> fittingApplySave(HttpServletRequest request) {
        User user = UserUtils.getUser();
        String siteId = CrmUtils.getSiteId(user);
       /* Record data = recevierAddressService.getAddress(siteId);
        if (data==null) {
            return Result.fail("402");
        }*/
        String jsonStr = request.getParameter("data1");
        JSONObject json = JSON.parseObject(jsonStr);
        if (json.size()==0) {
            Result.fail("401", "请选择数据");
        }
        String name = CrmUtils.getUserXM(user);
        for (Map.Entry<String, Object> js : json.entrySet()) {
            Map<String, String> map = (Map<String, String>) js.getValue();
            String fitId = map.get("fitId");
            String num = map.get("amount");
            String remarks = map.get("remarks");
            CrmPlantformFittingApply apply = new CrmPlantformFittingApply();
            PlatformFitting fitting = platformFittingDao.get(fitId);
            apply.setNumber(CrmUtils.no());
            apply.setSiteId(siteId);
            apply.setSiteName(name);
            apply.setApplicantId(user.getId());
            apply.setApplicantName(name);
            apply.setApplicantType(SourceConstants.ZERO);
            apply.setApplyMarks(remarks);
            apply.setFittingId(fitId);
            apply.setFittingCode(fitting.getCode());
            apply.setFittingName(fitting.getName());
            apply.setFittingVersion(fitting.getVersion());
            apply.setFittingImg(fitting.getImg());
            apply.setSuitPrinter(fitting.getSuitPrinter());
            apply.setOldFittingFlag(fitting.getRefundOldFlag());
            apply.setApplyNum(new BigDecimal(num));
            apply.setCreateTime(new Date());
            apply.setCreator(name);
            apply.setDeliveryName(request.getParameter("receiver"));
            apply.setDeliveryMobile(request.getParameter("mobile"));
            apply.setDeliveryAddress(request.getParameter("province")+request.getParameter("city")+request.getParameter("area")+request.getParameter("address"));
            apply.setSitePrice(fitting.getSitePrice());
            apply.setCustomerPrice(fitting.getCustomerPrice());
            crmPlatformFittingApplyDao.save(apply);
            PlantformFittingApplyMsg msg = new PlantformFittingApplyMsg();
            if(msg == null){
                msg = new PlantformFittingApplyMsg();
                msg.setFittingApplyId(apply.getId());
                msg.setSiteId(apply.getSiteId());
            }
            ComplaintReply tamd = new ComplaintReply();
            tamd.setT(DateUtils.getDateTime());
            tamd.setP(name);
            tamd.setC(name + " 申请 - 向平台申请备件;");
            String strmsg = WebPageFunUtils.appendProcessDetail(tamd, msg.getMessage());
            msg.setMessage(strmsg);
            msg.setSiteId(CrmUtils.getSiteId(user));
            msg.setFittingApplyId(apply.getId());
            plantformFittingApplyMsgDao.save(msg);
        }
        return Result.ok("申请成功！");

    }


    public Record getApplyDetail(String id){
        StringBuilder sb = new StringBuilder();
        sb.append("select a.* ");
        sb.append(" from crm_site_fitting a ");
        sb.append(" where a.id=? ");
        return Db.findFirst(sb.toString(), id);
    }


    public Record getPlatformApplyDetail(String id){
        StringBuilder sb = new StringBuilder();
        sb.append("select a.* from crm_platform_fitting a where a.id=?");
        return Db.findFirst(sb.toString(), id);
    }

    public Record getSiteittingByCode(String siteId,String code ){
        String sql = "SELECT * FROM crm_site_fitting WHERE site_id=? AND CODE like '%"+code+"%' AND STATUS='1' ";
        return Db.findFirst(sql,siteId);
    }
}
