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

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
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.site.fittingManager.dao.SiteFittingApplyDao;
import com.sifang.modules.site.fittingManager.dao.SiteFittingRefundDao;
import com.sifang.modules.site.siteInfo.dao.SiteCompanyInfoDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmSite;
import com.sifang.modules.sunshine.SystemSetting.utils.RandomUtil;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.fittingManager.dao.CrmFactoryFittingRefundDao;
import com.sifang.modules.sunshine.fittingManager.dao.FactoryFittingRefundMsgDao;
import com.sifang.modules.sunshine.fittingManager.entity.CrmPlantformFittingApply;
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.supply.stock.constant.MaterialConstants;
import com.sifang.modules.sys.common.UserUtils;
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.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author lzp
 * @date 2019/10/11 14:28
 */
@Service
public class SiteFittingRefundService extends BaseService {
    @Autowired
    private SiteFittingRefundDao fittingRefundDao;

    @Autowired
    private SiteFittingApplyDao fittingApplyDao;
    @Autowired
    private FactoryFittingRefundMsgDao msgDao;
    @Autowired
    private CrmFactoryFittingRefundDao crmFactoryFittingRefundDao;
    @Autowired
    private FactoryFittingRefundMsgDao fittingRefundMsgDao;
    @Autowired
    private SiteCompanyInfoDao siteDao;

    /**
     * 旧件登记
     *
     * @param map
     */
    @Transactional(rollbackFor = Exception.class)
    public Result batcholdFitRefundWith(Map<String, String> map) {
        String id = map.get("id");
        Result result = new Result();
        if (StringUtil.isBlank(id)) {
            return Result.fail("402", "返厂备件数据有误");
        }
        String userId = map.get("userId");
        String creator = map.get("creator");
        if (StringUtil.isNotBlank(userId)) {
            Record employe = CrmUtils.getEmployeId(userId);
            if (employe != null) {
                creator = employe.getStr("name");
            }
        }
        try {

            CrmSiteFittingApply apply = fittingApplyDao.get(id);
            if (!CrmPlantformFittingApply.OLDFITTINGFLAG_YES.equals(apply.getReturnFitting())) {
                return Result.fail("403", "该申请记录非已完成的申请记录,不可操作返厂"); //该申请记录非已完成的申请记录
            }
            apply.setReturnFitting(MaterialConstants.RETURN_FITTING_YES);
            fittingApplyDao.save(apply);
            CrmSite site = siteDao.get(apply.getSiteId());
            Date now = new Date();
            CrmPlatformFittingRefund refund = new CrmPlatformFittingRefund();
            refund.setNumber(RandomUtil.getBillingNumber());
            refund.setSiteId(apply.getSiteId());
            refund.setSiteName(site.getName());
            refund.setApplyId(id);
            refund.setOrderId(apply.getOrderId());
            refund.setOrderNumber(apply.getOrderNumber());
            //备件信息
            refund.setStatus(CrmPlatformFittingRefund.STATUS_START);
            refund.setFittingVersion(apply.getFittingVersion());
            refund.setFittingCode(apply.getFittingCode());
            refund.setRefundNum(apply.getFittingApplyNum());

            refund.setFittingName(apply.getFittingName());
            refund.setFittingImg(apply.getFittingImg());
            refund.setCreateTime(now);
            refund.setSendTime(new Date());
            refund.setCreatorType(map.get("creator_type") != null ? map.get("creator_type") : "5");
            refund.setCreatorId(map.get("creator_id") != null ? map.get("creator_id") : map.get("userId"));
            refund.setCreator(creator);
            fittingRefundDao.save(refund);

            //旧件记录操作详情
            CrmPlantformFittingRefundMsg msg = new CrmPlantformFittingRefundMsg();
            msg.setSiteId(map.get("siteId"));
            msg.setFittingRefundId(refund.getId());
            ComplaintReply ta = new ComplaintReply();
            ta.setT(DateUtils.getDateTime());
            ta.setP(creator);
            ta.setC(creator + "新增旧件登记记录");
            String str = WebPageFunUtils.appendProcessDetail(ta, "");
            msg.setUpdateDetail(str);
            msgDao.save(msg);
            result.setCode("200");

        } catch (Exception e) {
            result.setCode("404");
            throw e;
        }

        return result;
    }

    /**
     * 修改返厂记录信息
     *
     * @param map
     */
    @Transactional(rollbackFor = Exception.class)
    public Result uodateRefundFit(Map<String, String> map) {
        Result result = new Result();
        String id = map.get("id");
        try {
            CrmPlatformFittingRefund fund = fittingRefundDao.get(id);
            if (!MaterialConstants.NORMAL.equals(fund.getStatus())) {
                //该返厂件已到厂无法修改
                return Result.fail("201", "该返厂件已到厂无法修改");
            }

            CrmPlantformFittingRefundMsg msg = msgDao.getByRefundId(id);
            ComplaintReply ta = new ComplaintReply();
            ta.setT(DateUtils.getDateTime());
            ta.setP(map.get("update_name"));
            /*ta.setC(map.get("update_name") + "修改返厂记录:");*/
            if (msg == null) {
                msg = new CrmPlantformFittingRefundMsg();
                msg.setSiteId(map.get("siteId"));
                msg.setFittingRefundId(fund.getId());
                ta.setC(map.get("update_name") + "修改返厂记录:新增返厂记录");
                String str = WebPageFunUtils.appendProcessDetail(ta, "");
                msg.setUpdateDetail(str);
                msgDao.save(msg);
            } else {
                StringBuilder content = new StringBuilder("");
                if (!fund.getFittingName().equals(map.get("fitting_name"))) {
                    content.append("，备件名称：" + fund.getFittingName() + "修改为：" + map.get("fitting_name"));
                }
                if (!fund.getFittingCode().equals(map.get("fitting_code"))) {
                    content.append("，备件条码：" + fund.getFittingCode() + "修改为：" + map.get("fitting_code"));
                }
                if (fund.getRefundNum().compareTo(new BigDecimal(map.get("refund_num"))) == 0) {
                    content.append("，备件数量:" + fund.getRefundNum() + "修改为：" + map.get("refund_num"));
                }
                if (!fund.getLogisticsNames().equals(map.get("logistics_names"))) {
                    content.append("，物流名称：" + fund.getLogisticsNames() + "修改为：" + map.get("logistics_names"));
                }
                if (!fund.getLogisticsNumber().equals(map.get("logistics_number"))) {
                    content.append("，物流单号：" + fund.getLogisticsNumber() + "修改为：" + map.get("logistics_number"));
                }
                if (StringUtil.isNotBlank(map.get("send_time"))) {
                    content.append("，修改发货时间为：" + map.get("send_time"));
                }
                if (StringUtil.isNotBlank(fund.getMarks()) && !fund.getMarks().equals(map.get("marks"))) {
                    content.append("，备注：" + fund.getMarks() + "修改为：" + map.get("marks"));
                } else if (StringUtil.isBlank(fund.getMarks())) {
                    content.append("，备注：修改为：" + map.get("marks"));
                }
                if (StringUtil.isNotBlank(fund.getLogisticsImgs()) && !fund.getLogisticsImgs().equals(map.get("logistics_imgs"))) {
                    content.append("，修改快递单图片");
                } else if (StringUtil.isBlank(fund.getLogisticsImgs())) {
                    content.append("，修改快递单图片");
                }
                ta.setC(map.get("update_name") + "修改返厂记录:" + content.toString());
                String str = WebPageFunUtils.appendProcessDetail(ta, msg.getUpdateDetail());
                msg.setUpdateDetail(str);
                msgDao.save(msg);
            }

            fund.setFittingCode(map.get("fitting_code"));
            fund.setFittingName(map.get("fitting_name"));
            fund.setRefundNum(new BigDecimal(map.get("refund_num")));
            fund.setLogisticsNames(map.get("logistics_names"));
            fund.setLogisticsNumber(map.get("logistics_number"));
            fund.setLogisticsImgs(map.get("logistics_imgs"));
            fund.setMarks(map.get("marks"));
            fund.setSendTime(DateUtils.parseDate(map.get("send_time")));
            fund.setUpdateName(map.get("update_name"));
            fund.setUpdateTime(new Date());

            fittingRefundDao.save(fund);

            result.setCode("200");
        } catch (Exception e) {
            result.setCode("400");
            throw e;
        }

        return result;
    }

    /**
     * 服务商获取返厂记录信息
     */
    public Map<String, Object> getSiteFittingRefund(LayuiPage<Record> page, Map<String, String> map) {
        List<Record> list = fittingRefundDao.getSIteFittingRefundList(page, map);
        List<Map<String, Object>> mapx = CrmUtils.returnListMap(list);
        Map<String, Object> sitemap = Maps.newHashMap();
        sitemap.put("count", fittingRefundDao.getSIteFittingRefundCount(map));
        sitemap.put("list", mapx);
        return sitemap;
    }

    /**
     * 删除旧件返厂记录
     */
    public String batchdelectOldFitting(String ids, String creator) {
        String code = "200";
        try {
            String[] idArr = ids.split(",");
            List<CrmPlatformFittingRefund> list = Lists.newArrayList();
            List<CrmPlantformFittingRefundMsg> msglist = Lists.newArrayList();
            for (String id : idArr) {
                CrmPlatformFittingRefund hund = fittingRefundDao.get(id);

                CrmSiteFittingApply apply = fittingApplyDao.get(hund.getApplyId());
                fittingApplyDao.save(apply);

                hund.setStatus(SourceConstants.FOUR);
                ComplaintReply ta = new ComplaintReply();
                ta.setT(DateUtils.getDateTime());
                ta.setP(creator);
                ta.setC(creator + "删除返厂记录");
                //	hund.setUpdateDetail(str);
                hund.setUpdateName(creator);
                hund.setUpdateTime(new Date());
                list.add(hund);
                CrmPlantformFittingRefundMsg msg = msgDao.getByRefundId(id);
                String str = WebPageFunUtils.appendProcessDetail(ta, msg.getUpdateDetail());
                msg.setUpdateDetail(str);
                msglist.add(msg);
            }
            fittingRefundDao.save(list);
            msgDao.save(msglist);
        } catch (Exception e) {
            e.printStackTrace();
            code = "400";
            throw e;
        }

        return code;
    }


    public CrmPlatformFittingRefund getById(String id) {
        return fittingRefundDao.get(id);
    }

    public CrmPlantformFittingRefundMsg getByFunId(String id) {
        return msgDao.getByRefundId(id);
    }


    //获取服务商端的旧件信息
    public void getOldFittingList(LayuiPage page, Map<String, String> map) {
        List<Record> list = fittingRefundDao.getOldFittingList(page, map);
        page.setData(list);
        page.setCount(fittingRefundDao.getOldFittingCount(map));
    }

    //服务商端旧件管理页面操作返厂
    public Result backOldFitting(String ids) {
        Result result = new Result();
        String userName = CrmUtils.getUserXM(UserUtils.getUser());
        String[] idArr = ids.split(",");
        Date now = new Date();
        List<CrmPlatformFittingRefund> list = Lists.newArrayList();
        List<CrmPlantformFittingRefundMsg> msgList = Lists.newArrayList();
        try {
            for (String id : idArr) {
                if (StringUtil.isNotBlank(id)) {
                    CrmPlatformFittingRefund crmPlatformFittingRefund = crmFactoryFittingRefundDao.get(id);
                    if (!CrmPlatformFittingRefund.STATUS_START.equals(crmPlatformFittingRefund.getStatus())) {
                        result.setCode("205");   //有工单状态不能操作返厂
                        return result;
                    }
                    crmPlatformFittingRefund.setStatus(MaterialConstants.RETURN_FITTING_STATUS);
                    crmPlatformFittingRefund.setSendTime(now);
                    crmPlatformFittingRefund.setUpdateTime(now);
                    crmPlatformFittingRefund.setUpdateName(userName);
                    crmPlatformFittingRefund.setBackName(userName);
                    list.add(crmPlatformFittingRefund);
                    //返厂记录操作详情
                    CrmPlantformFittingRefundMsg fittingRefundMsg = fittingRefundMsgDao.getByRefundId(id);
                    ComplaintReply ta = new ComplaintReply();
                    ta.setT(DateUtils.getDateTime());
                    ta.setP(userName);
                    String str = null;
                    if (fittingRefundMsg == null) {
                        fittingRefundMsg = new CrmPlantformFittingRefundMsg();
                        fittingRefundMsg.setSiteId(crmPlatformFittingRefund.getSiteId());
                        fittingRefundMsg.setFittingRefundId(id);
                        ta.setC(userName + "修改旧件信息:新建旧件返厂");
                        str = WebPageFunUtils.appendProcessDetail(ta, "");
                    } else {
                        ta.setC(userName + "修改旧件信息:新建旧件返厂");
                        str = WebPageFunUtils.appendProcessDetail(ta, fittingRefundMsg.getUpdateDetail());
                    }
                    fittingRefundMsg.setUpdateDetail(str);
                    msgList.add(fittingRefundMsg);
                }
            }
            fittingRefundMsgDao.save(msgList);
            crmFactoryFittingRefundDao.save(list);
            result.setCode("200");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode("405");
        }

        return result;
    }

    //服务商端旧件管理页面操作撤回
    @Transactional(rollbackFor = Exception.class)
    public Result withdrawFitting(String ids) {
        Result result = new Result();
        String userName = CrmUtils.getUserXM(UserUtils.getUser());
        String[] idArr = ids.split(",");
        Date now = new Date();
        List<CrmPlatformFittingRefund> list = Lists.newArrayList();
        List<CrmPlantformFittingRefundMsg> msgList = Lists.newArrayList();
        try {
            for (String id : idArr) {
                if (StringUtil.isNotBlank(id)) {
                    CrmPlatformFittingRefund crmPlatformFittingRefund = crmFactoryFittingRefundDao.get(id);
                    if (crmPlatformFittingRefund == null) {
                        result.setCode("204");   //必要参数错误
                        return result;
                    }
                    if (!CrmPlatformFittingRefund.STATUS_SHIPED.equals(crmPlatformFittingRefund.getStatus())) {  //未到厂才可操作撤回
                        result.setCode("205");   //有工单状态不能操作撤回
                        return result;
                    }
                    crmPlatformFittingRefund.setStatus(MaterialConstants.RETURN_FITTING_STATUS_ZERO);
                    crmPlatformFittingRefund.setSendTime(null);
                    crmPlatformFittingRefund.setUpdateTime(now);
                    crmPlatformFittingRefund.setUpdateName(userName);
                    crmPlatformFittingRefund.setBackName(null);
                    list.add(crmPlatformFittingRefund);
                    //返厂记录操作详情
                    CrmPlantformFittingRefundMsg fittingRefundMsg = fittingRefundMsgDao.getByRefundId(id);
                    ComplaintReply ta = new ComplaintReply();
                    ta.setT(DateUtils.getDateTime());
                    ta.setP(userName);
                    String str = null;
                    if (fittingRefundMsg == null) {
                        fittingRefundMsg = new CrmPlantformFittingRefundMsg();
                        fittingRefundMsg.setSiteId(crmPlatformFittingRefund.getSiteId());
                        fittingRefundMsg.setFittingRefundId(id);
                        ta.setC(userName + "修改旧件信息:撤回旧件返厂;");
                        str = WebPageFunUtils.appendProcessDetail(ta, "");
                    } else {
                        ta.setC(userName + "修改旧件信息:撤回旧件返厂;");
                        str = WebPageFunUtils.appendProcessDetail(ta, fittingRefundMsg.getUpdateDetail());
                    }
                    fittingRefundMsg.setUpdateDetail(str);
                    msgList.add(fittingRefundMsg);
                }
            }
            fittingRefundMsgDao.save(msgList);
            crmFactoryFittingRefundDao.save(list);
            result.setCode("200");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode("405");
        }

        return result;
    }
}
