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

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.SourceConstants;
import com.sifang.modules.order.dao.OrderDao;
import com.sifang.modules.order.entity.CrmOrder;
import com.sifang.modules.order.utils.WebPageFunUtils;
import com.sifang.modules.platform.controller.form.ComplaintReply;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.site.fittingManager.dao.SiteFittingApplyDao;
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.CrmSiteFittingDao;
import com.sifang.modules.sunshine.fittingManager.entity.CrmPlantformFittingApply;
import com.sifang.modules.sunshine.fittingManager.entity.CrmSiteFitting;
import com.sifang.modules.sunshine.fittingManager.entity.CrmSiteFittingApply;
import com.sifang.modules.sunshine.fittingManager.entity.SiteFittingApplyMsg;
import com.sifang.modules.supply.order.constant.ApplyOrderConstants;
import com.sifang.modules.supply.stock.constant.MaterialConstants;
import com.sifang.modules.supply.warehouse.constant.MaterialKeepConstants;
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.apache.commons.lang3.StringUtils;
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 SiteFittingApplyService extends BaseService {

    @Autowired
    private SiteFittingApplyDao fittingApplyDao;

    @Autowired
    private SiteFittingApplyMsgDao fittingApplyMsgDao;
    @Autowired
    private OrderDao orderDao;

    @Autowired
    CrmSiteFittingDao crmSiteFittingDao;


    public CrmSiteFittingApply getById(String id) {
        return fittingApplyDao.get(id);
    }

    /**
     * 备件申请数据
     *
     * @param status 申请状态：0.申请待审核 1.审核通过
     */
    public Map<String, Object> getAllApplyList(LayuiPage page, Map<String, String> map, String status, String siteId) {
        List<Record> list = fittingApplyDao.getAllApplyList(page, map, status, siteId);
        List<Map<String, Object>> mapx = CrmUtils.returnListMap(list);
        Map<String, Object> sitemap = Maps.newHashMap();
        sitemap.put("count", fittingApplyDao.queryApplyDataCount(map, status, siteId));
        sitemap.put("list", mapx != null ? mapx : Maps.newHashMap());
        return sitemap;
    }


    /**
     * 小程序
     * 删除待发货备件申请
     *
     * @param id
     * @param creator
     */
    public Result delFittingAppply(String id, String creator) {
        Date now = new Date();
        CrmSiteFittingApply apply = fittingApplyDao.get(id);
        if (!CrmPlantformFittingApply.OLDFITTINGFLAG_NO.equals(apply.getStatus())) {//非待发货
            return Result.fail("205", "");//数据中有已审核的备件，不可删除
        }
        apply.setUpdateTime(now);
        apply.setUpdateName(creator);
        apply.setStatus(CrmPlantformFittingApply.APPLY_STATUS_CANCEL);


        fittingApplyDao.save(apply);
        //申请表修改记录
        SiteFittingApplyMsg msg = fittingApplyMsgDao.findByApplyId(id);
        ComplaintReply tamd = new ComplaintReply();
        tamd.setT(DateUtils.getDateTime());
        tamd.setP(creator);
        tamd.setC(creator + "工程师删除配件申请信息;");
        String strmsg = WebPageFunUtils.appendProcessDetail(tamd, msg.getMessage());
        msg.setMessage(strmsg);
        fittingApplyMsgDao.save(msg);
        orderDao.updateFittingFlag(apply.getOrderId(), apply.getSiteId());
        return Result.ok();
    }

    /**
     * 服务商确认到货
     *
     * @param ids     申请记录id“,"号拼接
     * @param creator 确认人姓名
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String confirmToTheSite(String ids, String creator) {
        String[] idArr = ids.split(",");
        Date now = new Date();
        List<CrmSiteFittingApply> list = Lists.newArrayList();
        for (String id : idArr) {
            CrmSiteFittingApply apply = fittingApplyDao.get(id);
            if (!CrmPlantformFittingApply.APPLY_STATUS_DELIVERYED.equals(apply.getStatus())) {
                return "203";//该申请信息状态不是已发货
            }
            apply.setUpdateTime(now);
            apply.setUpdateName(creator);
            apply.setStatus(CrmPlantformFittingApply.APPLY_STATUS_FINISHED);
            list.add(apply);
        }
        fittingApplyDao.save(list);
        //将所有缓冲的数据强制发送到目的地。
        fittingApplyDao.flush();
        return "200";
    }


    /**
     * 服务商修改配件申请信息
     *
     * @param map
     */
    public Result siteUpdateApplyFitting(Map<String, String> map) {
        String id = map.get("id");
        CrmSiteFittingApply app = fittingApplyDao.get(id);
        StringBuilder content = new StringBuilder();
        if (!app.getFittingName().equals(map.get("fitting_name"))) {
            content.append("修改备件名称,原名称为:" + app.getFittingName() + "现名称为：" + map.get("fitting_name"));
            app.setFittingName(map.get("fitting_name"));
        }
        if (!app.getFittingCode().equals(map.get("fitting_code"))) {
            content.append("修改备件条码,原条码为:" + app.getFittingCode() + "现条码为：" + map.get("fitting_code"));
            app.setFittingCode(map.get("fitting_code"));
        }
        app.setFittingImg(map.get("fitting_img"));

        SiteFittingApplyMsg applyMsg = SiteFittingApplyMsgDao.getByApply(fittingApplyMsgDao, app);
        String message = applyMsg.getMessage();

        ComplaintReply ta = new ComplaintReply();
        ta.setT(DateUtils.getDateTime());
        ta.setP(map.get("name"));
        ta.setC(app.getEmployeName() + "服务商修改配件申请信息;" + content.toString());
        String str = WebPageFunUtils.appendProcessDetail(ta, message);
        applyMsg.setMessage(str);
        fittingApplyDao.save(app);
        fittingApplyMsgDao.save(applyMsg);
        return Result.ok();
    }

    /**
     * 工程师申请备件
     */
    @Transactional(rollbackFor = Exception.class)
    public Result siteApplyFitting(Map<String, String> map) {
        Result result = new Result();
        //验证必填项是否为空
        if (!checkRequired(map)) {
            //存在必填项为空
            result.setCode("401");
            return result;
        }
        String fittingId = map.get("fittingId");
        if (StringUtil.isEmpty(fittingId)) {
            result.setCode("401");
            return result;
        }
        String orderId = map.get("orderId");
        String applicantId = map.get("applicantId");
        CrmOrder order = orderDao.get(orderId);
        if(!StringUtil.equalsAny(order.getSiteStatus(),ApplyOrderConstants.SITE_STATUS_DIS,ApplyOrderConstants.SITE_STATUS_RECEIVE,
                ApplyOrderConstants.SITE_STATUS_DOOR,ApplyOrderConstants.SITE_STATUS_SERVICE)){
            result.setCode("501");//该工单状态不可申请备件
            return result;
        }
        if (order.getEmployeId().indexOf(applicantId) == -1) {
            result.setCode("503");//该工单已转派不可申请备件
            result.setMsg("该工单已转派不可申请备件");
            return result;
        }
        try {

            order.setFittingFlag(ApplyOrderConstants.FITTING_FLAG_WAIT);
            orderDao.save(order);
            String creator = map.get("applicantName");

            CrmSiteFitting fi = crmSiteFittingDao.get(fittingId);

            CrmSiteFittingApply apply = new CrmSiteFittingApply();
            apply.setNumber(PlantformUtils.getSiteNumber());

            apply.setEmployeId(map.get("applicantId"));
            apply.setOrderId(orderId);
            apply.setEmployeName(creator);
            apply.setSiteId(map.get("siteId"));
            apply.setEmployeFeedback(map.get("apply_marks"));
            apply.setFittingImg(map.get("fitting_img"));
            apply.setStatus(MaterialConstants.APPLY_STATUS_ZERO);
            apply.setCreateTime(new Date());
            apply.setOldFittingFlag(SourceConstants.ZERO);
            apply.setCreator(map.get("applicantName"));
            apply.setFittingId(fittingId);
            apply.setFittingCode(fi.getCode());
            apply.setFittingName(fi.getName());
            apply.setFittingVersion(fi.getVersion());
            apply.setFittingApplyNum(new BigDecimal(map.get("fittingNum")));
            apply.setCustomerPrice(fi.getCustomerPrice());
            fittingApplyDao.save(apply);

            CrmSiteFitting fitting = crmSiteFittingDao.get(map.get("fittingId"));
            fitting.setAuditedSum(fitting.getAuditedSum().add(new BigDecimal(map.get("fittingNum"))));
            crmSiteFittingDao.save(fitting);

            //申请表修改记录
            SiteFittingApplyMsg msg = new SiteFittingApplyMsg();
            ComplaintReply tamd = new ComplaintReply();
            tamd.setT(DateUtils.getDateTime());
            tamd.setP(creator);
            tamd.setC(creator + "添加配件申请信息;");
            String strmsg = WebPageFunUtils.appendProcessDetail(tamd, "");
            msg.setMessage(strmsg);
            msg.setFittingApplyId(apply.getId());
            msg.setSiteId(apply.getSiteId());
            fittingApplyMsgDao.save(msg);

        } catch (Exception e) {
            logger.error("save fittingapply  e:{}", e);
            e.printStackTrace();
            result.setCode("505");
            return result;
        }

        result.setCode("200");
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result siteDeleteApplyFitting(Map<String, String> map) {
        String id = map.get("id");
        if (StringUtil.isBlank(id)) {
            return Result.fail("500");
        }
        String creator = map.get("creator");
        CrmSiteFittingApply apply = fittingApplyDao.get(id);
        if (!MaterialConstants.APPLY_STATUS_ZERO.equals(apply.getStatus())) {
            return Result.fail("401", "该备件申请不满足删除条件");
        }

        apply.setStatus(MaterialConstants.APPLY_STATUS_FIVE);
        fittingApplyDao.save(apply);
        //申请表修改记录
        SiteFittingApplyMsg msg = fittingApplyMsgDao.findByApplyId(id);
        ComplaintReply tamd = new ComplaintReply();
        tamd.setT(DateUtils.getDateTime());
        tamd.setP(creator);
        tamd.setC(creator + "服务商删除配件申请信息;");
        String strmsg = WebPageFunUtils.appendProcessDetail(tamd, msg.getMessage());
        msg.setMessage(strmsg);
        fittingApplyMsgDao.save(msg);
        orderDao.updateFittingFlag(apply.getOrderId(), apply.getSiteId());
        return Result.ok();
    }

    //校验必填项
    public boolean checkRequired(Map<String, String> map) {

        if (StringUtils.isBlank(map.get("fittingName")) || StringUtils.isBlank(map.get("fittingNum"))) {
            return false;
        }

        if (StringUtils.isBlank(map.get("apply_marks"))) {
            return false;
        }
        if (StringUtils.isBlank(map.get("creator"))) {
            return false;
        }
        return true;
    }

    //工单详情里面的备件信息
    public List<Record> getOrderFitting(String orderId) {
        StringBuffer sb = new StringBuffer();
        sb.append(" SELECT a.* , r.status AS refundStatus ");
        sb.append(" FROM `crm_site_fitting_apply` a  ");
        sb.append(" LEFT JOIN `crm_platform_fitting_refund` r ON r.apply_id=a.id AND r.status!=0 ");
        sb.append(" WHERE a.`order_id`=?  AND a.status IN('0','1') ");
        return Db.find(sb.toString(), orderId);
    }

    //服务商获取出入库明细数据
    public void getSitInAndOutWarehousingData(LayuiPage page, Map<String, String> map) {
        String siteId = CrmUtils.getUserRelId(UserUtils.getUser());
        map.put("siteId", siteId);
        List<Record> list = fittingApplyDao.getSitInAndOutWarehousingList(page, map);
        page.setData(list);
        page.setCount(fittingApplyDao.getSitInAndOutWarehousingCount(map));

    }

    public BigDecimal getEmpFittingByOrderId(String orderId) {
        String sql = "SELECT IFNULL(a.fitting_audit_num,0) AS fitting_audit_num,IFNULL(a.customer_price,0) AS customer_price FROM crm_site_fitting_apply a WHERE a.order_id=? AND a.status='1' ";
        List<Record> list = Db.find(sql, orderId);
        BigDecimal fittingPrice = new BigDecimal("0");
        if (list.size() > 0) {
            for (Record rds : list) {
                fittingPrice = fittingPrice.add(rds.getBigDecimal("fitting_audit_num").multiply(rds.getBigDecimal("customer_price")));
            }
        }

        return fittingPrice;
    }

    public long getEmployeFittingByOrderId(String orderId) {
        String sql = "SELECT COUNT(id) FROM crm_site_fitting_apply a WHERE a.order_id=? AND a.status='0' ";
        return Db.queryLong(sql, orderId);
    }
}
