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

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
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.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.fittingManager.dao.*;
import com.sifang.modules.sunshine.fittingManager.entity.CrmPlantformFittingApply;
import com.sifang.modules.sunshine.fittingManager.entity.CrmSiteFitting;
import com.sifang.modules.sunshine.fittingManager.entity.CrmSiteFittingkeep;
import com.sifang.modules.sunshine.fittingManager.entity.PlantformFittingApplyMsg;
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.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.Transactional;

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

@Service
public class CrmSiteFittingApplyService extends BaseService {

    @Autowired
    CrmSiteFittingApplyDao crmSiteFittingApplyDao;
    @Autowired
    FittingApplyDao fittingApplyDao;
    @Autowired
    CrmSiteFittingDao crmSiteFittingDao;
    @Autowired
    CrmSiteFittingKeepDao crmSiteFittingKeepDao;
    @Autowired
    PlatformFittingDao platformFittingDao;
    @Autowired
    PlantformFittingApplyMsgDao plantformFittingApplyMsgDao;

    public void getAllApplyList(LayuiPage<Record> page, Map<String, String> map, String status) {
        List<Record> list = crmSiteFittingApplyDao.getAllApplyList(page, map, status);
        page.setData(list);
        page.setCount(crmSiteFittingApplyDao.queryApplyDataCount(map, status));
    }

    public Record getApplyDetail(String id) {
        Record record = Db.findFirst("select * from crm_platform_fitting_apply where id = '"+id+"'");
        return record;
    }

    public List<Record> getAllPlatFitting() {
        List<Record> list = Db.find("select * from crm_platform_fitting where status='1'" );
        return list;
    }

    //保存
    @Transactional(rollbackFor=Exception.class)
    public Result saveApply(String id, String fitId, String fitCode, String fittingName,String fittingVersion,String applyNum,String applyMarks){
        Record record = getApplyByfittingId(fitId);
        if (record != null) {
            if (!record.getStr("id").equals(id)) {
                return Result.fail("401", "已存在该备件申请");
            }
        }
        Record fit = platformFittingDao.getFittingByCode(fitCode);
        User user = UserUtils.getUser();
        String name = CrmUtils.getUserXM(user);
        CrmPlantformFittingApply apply = fittingApplyDao.get(id);
        apply.setFittingId(fit.getStr("id"));
        apply.setFittingCode(fitCode);
        apply.setFittingName(fittingName);
        apply.setFittingVersion(fittingVersion);
        apply.setApplyNum(new BigDecimal(applyNum));
        apply.setApplyMarks(applyMarks);
        apply.setUpdateName(name);
        apply.setUpdateTime(new Date());
        apply.setSitePrice(fit.getBigDecimal("site_price"));
        fittingApplyDao.save(apply);
        PlantformFittingApplyMsg msg =plantformFittingApplyMsgDao.findByApplyId(apply.getId());
        if(msg == null){
            msg = new PlantformFittingApplyMsg();
            msg.setFittingApplyId(id);
            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);
        plantformFittingApplyMsgDao.save(msg);
        return Result.ok();
    }

    public Record getApplyByfittingId(String fitId) {
        Record list = Db.findFirst("select * from crm_platform_fitting_apply where status='1' and fitting_id = '"+fitId+"'" );
        return list;
    }

    //撤销申请
    public Result revokeApply(String id) {
        User user = UserUtils.getUser();
        String name = CrmUtils.getUserXM(user);
        CrmPlantformFittingApply apply = fittingApplyDao.get(id);
        if (!CrmPlantformFittingApply.APPLY_STATUS_UNDELIVERY.equals(apply.getStatus())) {
            return Result.fail("401","撤销失败,该备件申请已审核,请刷新页面");
        }
        apply.setStatus(MaterialConstants.APPLY_STATUS_FIVE);
        apply.setUpdateName(name);
        apply.setUpdateTime(new Date());
        fittingApplyDao.save(apply);
        PlantformFittingApplyMsg msg =plantformFittingApplyMsgDao.findByApplyId(apply.getId());
        if(msg == null){
            msg = new PlantformFittingApplyMsg();
            msg.setFittingApplyId(id);
            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);
        plantformFittingApplyMsgDao.save(msg);
        return Result.ok();
    }

    //保存确认入库
    @Transactional(rollbackFor=Exception.class)
    public Result fittingInStock(String id, String location){
        User user = UserUtils.getUser();
        String name = CrmUtils.getUserXM(user);
        CrmPlantformFittingApply apply = fittingApplyDao.get(id);
        if(!CrmPlantformFittingApply.APPLY_STATUS_FINISHED.equals(apply.getStatus())){
            return Result.fail("401","该备件申请不满足入库条件，请刷新页面");
        }

        apply.setStatus(MaterialConstants.APPLY_STATUS_DELETE);
        apply.setUpdateName(name);
        apply.setUpdateTime(new Date());
        apply.setSendTime(new Date());
        apply.setConfirmStorageId(user.getId());
        apply.setConfirmStorage(name);
        fittingApplyDao.save(apply);
        PlantformFittingApplyMsg msg =plantformFittingApplyMsgDao.findByApplyId(apply.getId());
        if(msg == null){
            msg = new PlantformFittingApplyMsg();
            msg.setFittingApplyId(id);
            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);
        plantformFittingApplyMsgDao.save(msg);
        CrmSiteFitting fitting = crmSiteFittingDao.getByFittingCode(apply.getFittingCode(),apply.getSiteId());
        if (fitting != null) {
            fitting.setWarning(fitting.getWarning().add(apply.getFittingAuditNum()));
            fitting.setLocation(location);
            fitting.setNewestStorageTime(new Date());
            fitting.setSitePrice(apply.getSitePrice());
            fitting.setCustomerPrice(apply.getCustomerPrice());
        } else {
            fitting = new CrmSiteFitting();
            PlatformFitting platformFitting = platformFittingDao.get(apply.getFittingId());
            fitting.setCode(platformFitting.getCode());
            fitting.setName(platformFitting.getName());
            fitting.setImg(platformFitting.getImg());
            fitting.setVersion(platformFitting.getVersion());
            fitting.setRemarks(platformFitting.getRemarks());
            fitting.setUnit(platformFitting.getUnit());
            fitting.setUnitType(platformFitting.getUnitType());
            fitting.setRefundOldFlag(platformFitting.getRefundOldFlag());
            fitting.setStatus(MaterialConstants.NORMAL);
            fitting.setSiteId(CrmUtils.getSiteId(user));
            fitting.setCreateBy(user.getId());
            fitting.setKeyword(platformFitting.getKeyword());
            fitting.setWarning(apply.getFittingAuditNum());
            fitting.setAlertNum(platformFitting.getAlertNum());
            fitting.setSitePrice(platformFitting.getSitePrice());
            fitting.setCustomerPrice(platformFitting.getCustomerPrice());
            fitting.setSuitPrinter(platformFitting.getSuitPrinter());
            fitting.setLocation(location);
            fitting.setNewestStorageTime(new Date());
            fitting.setPlatformFittingId(platformFitting.getId());
        }
        crmSiteFittingDao.save(fitting);
        CrmSiteFittingkeep keep = new CrmSiteFittingkeep();
        keep.setNumber(CrmUtils.no());
        keep.setType(MaterialKeepConstants.TYPE_IN);
        keep.setFittingId(fitting.getId());
        keep.setFittingName(fitting.getName());
        keep.setFittingCode(fitting.getCode());
        keep.setAmount(apply.getFittingAuditNum());
        keep.setPrice(fitting.getSitePrice());
        keep.setEmployePrice(fitting.getEmployePrice());
        keep.setCustomerPrice(fitting.getCustomerPrice());
        keep.setCreateTime(new Date());
        keep.setOperateTime(new Date());
        keep.setApplicant(apply.getApplicantName());
        keep.setConfirmor(name);
        keep.setSiteId(CrmUtils.getSiteId(user));
        keep.setCreateBy(user.getId());
        keep.setRelateRecordId(apply.getId());
        crmSiteFittingKeepDao.save(keep);
        return Result.ok();
    }

}
