package com.sifang.modules.customer.Service;

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.PartnerConstants;
import com.sifang.modules.customer.dao.CrmCustomerEntryStockDao;
import com.sifang.modules.customer.dao.CustomerEntryComponentDao;
import com.sifang.modules.customer.dao.CustomerEntryDao;
import com.sifang.modules.customer.entity.CrmCustomerEntryStock;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.sunshine.SystemSetting.dao.PlanMaterialEntryDao;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.stock.dao.SupplyMaterialDao;
import com.sifang.modules.supply.stock.entity.SupplyMaterial;
import com.sifang.modules.supply.stock.utils.MaterialUtils;
import com.sifang.modules.supply.warehouse.dao.CrmSupplyBarcodeDao;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyBarcode;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.youkua.service.NhPowerStationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OneDealService extends BaseService {

    @Autowired
    CustomerEntryDao customerDao;

    @Autowired
    PlanMaterialEntryDao entryDao;

    @Autowired
    private CustomerEntryService entryService;

    @Autowired
    private CrmCustomerEntryStockDao entryStockDao;

    @Autowired
    private NhPowerStationService stationService;

    @Autowired
    private CrmSupplyBarcodeDao barcodeDao;

    @Autowired
    SupplyMaterialDao materialDao;

    @Autowired
    PlanMaterialEntryDao planMaterialEntryDao;

    @Autowired
    CustomerEntryComponentDao componentDao;

    //将广发存量电站 之前已使用物料条码 迁移到增量电站中 需要先匹配物料将条码导入系统 再使用物料
    @Transactional(rollbackFor = Exception.class)
    public String movOldMaterialRecords(String powerStationCode) {
        Date now = DateUtils.getNowDate();
        //获取基础数据
        CustomerEntry entry = entryService.findCustomerEntryById(powerStationCode);
        if (entry == null) {
            return "未找到增量电站";
        }
        if (!PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())) {
            return "不是广发电站";
        }
        CrmCustomerEntryStock stock = entryStockDao.findOneById(powerStationCode);
        if (stock == null) {
            return "未找到历史电站";
        }
        Long count = planMaterialEntryDao.findCountByEntryId(entry.getId(), "组件");
        if (count != null && count > 0) {
            return "已使用组件无需迁移";
        }
        List<Record> zjList = stationService.findZjList(stock.getId());
        if (zjList.isEmpty()) {
            return "未找到已使用的物料条码";
        }
        //匹配物料 检索条码
        Map<String, String>  barcodeRecordM = new HashMap<>();
        Map<String, CrmSupplyBarcode>  barcodeM = new HashMap<>();
        SupplyMaterial material = null;
        for (Record r :zjList) {
            String code = r.getStr("barcode");
            if (barcodeRecordM.containsKey(code)) {
                return code+"存在重复记录";
            }
            if (material == null) {
                material = materialDao.findSpecialZJBySpecBrand(r.getStr("brand"), r.getStr("spec"));
            }

            CrmSupplyBarcode oneByBarcode = barcodeDao.findOneByBarcode(code);
            if (oneByBarcode != null && "0".equals(oneByBarcode.getStatus())) {
                if (!"2".equals(oneByBarcode.getBarcodeStatus())) {
                    return code+"条码已使用";
                }
                if (material == null) {
                    material = materialDao.getById(oneByBarcode.getMaterialId());
                }
                else if (!material.getId().equals(oneByBarcode.getMaterialId())){
                    return code+"与其他条码匹配不属于同一个物料";
                }
                barcodeM.put(code, oneByBarcode);
                barcodeRecordM.put(code, oneByBarcode.getId());
            }
        }
        if (material == null) {
            return "未匹配上系统现有物料";
        }
        // 匹配设计方案的组件 是否满足要求
        Record zjInfo = componentDao.findZJByEntryId(entry.getId());
        if (zjInfo == null) {
            return "未匹配设计方案";
        }
        if (!material.getMaterialSpecs().equals(zjInfo.getStr("specs"))) {
            return "历史记录组件规格与设计方案不一致";
        }
        if (zjInfo.getInt("num") < zjList.size()) {
            return "设计组件数量低于迁移组件数量";
        }
        //处理逻辑
        for (Record r :zjList) {
            String code = r.getStr("barcode");
            CrmSupplyBarcode oneByBarcode = barcodeM.get(code);
            // 1.生成条码记录 并使用
            if (oneByBarcode == null) {
                oneByBarcode = new CrmSupplyBarcode();
                oneByBarcode.setMaterialId(material.getId());
                oneByBarcode.setMaterialBarcode(code);
                oneByBarcode.setBatchCode(null);
                oneByBarcode.setBatchCodeNote(null);
                oneByBarcode.setBarcodeStatus("1");
                oneByBarcode.setStatus("0");
                oneByBarcode.setCreateBy("1");
                oneByBarcode.setCreateTime(now);
                barcodeDao.save(oneByBarcode);
            }
            else {
                oneByBarcode.setBarcodeStatus("1");
                barcodeDao.save(oneByBarcode);
            }

            // 2.生成电站物料使用记录
            if("04".equals(entry.getPartnerId())){
                String projectIds[] = entry.getProjectId().split(",");
                for(String projectId : projectIds){
                    entryDao.createOne(material.getId(), "组件", material.getCode(), material.getMaterialName(),
                            material.getMaterialSpecs(), material.getUnitName(), oneByBarcode.getMaterialBarcode(),
                            1, now, entry.getId(),material.getMaterialModel(),projectId);
                }
            }else {
                entryDao.createOne(material.getId(), "组件", material.getCode(), material.getMaterialName(),
                        material.getMaterialSpecs(), material.getUnitName(), oneByBarcode.getMaterialBarcode(),
                        1, now, entry.getId(),material.getMaterialModel(),entry.getProjectId());
            }
        }
        return null;
    }
}
