package com.ecep.contract.service;

import java.io.File;
import java.time.LocalDate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.ecep.contract.MessageHolder;
import com.ecep.contract.SpringApp;
import com.ecep.contract.VendorType;
import com.ecep.contract.constant.CompanyVendorConstant;
import com.ecep.contract.model.VendorCatalog;
import com.ecep.contract.util.CompanyUtils;
import com.ecep.contract.util.FileUtils;
import com.ecep.contract.util.MyStringUtils;
import com.ecep.contract.util.ParamUtils;
import com.ecep.contract.vm.CompanyVendorViewModel;
import com.ecep.contract.vo.VendorVo;
import com.ecep.contract.vo.CompanyVo;
import com.ecep.contract.vo.ContractVo;

@Service
@CacheConfig(cacheNames = "vendor")
public class VendorService extends QueryService<VendorVo, CompanyVendorViewModel> {
    @Autowired
    private CompanyService companyService;
    @Autowired
    private CompanyFileService companyFileService;
    @Autowired
    private VendorFileService vendorFileService;

    private File basePath;

    public File getBasePath() {
        if (basePath == null) {
            basePath = new File(
                    SpringApp.getBean(SysConfService.class).getString(CompanyVendorConstant.KEY_BASE_PATH));
        }
        return basePath;
    }
    
    public File getVendorApprovedListTemplate() {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Unimplemented method 'getVendorApprovedListTemplate'");
    }

    public VendorCatalog findCatalogById(Integer id) {
        throw new UnsupportedOperationException("Unimplemented method 'findCatalogById'");
    }

    @Cacheable(key = "'company-'+#p0.id")
    public VendorVo findByCompany(CompanyVo company) {
        Page<VendorVo> page = findAll(ParamUtils.equal("company", company.getId()), Pageable.ofSize(1));
        if (page.isEmpty()) {
            return null;
        }
        return page.getContent().getFirst();
    }

    public boolean reBuildingFiles(VendorVo companyVendor, MessageHolder messageHolder) {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Unimplemented method 'reBuildingFiles'");
    }

    public void verify(ContractVo contract, MessageHolder holder) {
        CompanyVo company = companyService.findById(contract.getCompanyId());
        if (company == null) {
            holder.error("合同未关联公司");
            return;
        }
        VendorVo companyVendor = findByCompany(company);
        if (companyVendor == null) {
            holder.error("合同未关联供应商");
            return;
        }
        if (companyVendor.getType() == null) {
            holder.error("供应商未设置类型");
            return;
        }
        VendorType vendorType = companyVendor.getType();
        if (vendorType == VendorType.UNQUALIFIED) {
            holder.error("不合格供应商");
            return;
        }
        if (vendorType == VendorType.QUALIFIED) {
            holder.debug(VendorType.QUALIFIED.name());
            return;
        }
        if (vendorType == VendorType.TYPICALLY) {
            if (verifyAsTypicallyVendor(companyVendor, contract.getSetupDate(), holder)) {
                return;
            }
        }

        companyFileService.verify(company, contract.getSetupDate(), holder);

        vendorFileService.verify(companyVendor, contract.getSetupDate(), holder);
    }

    private boolean verifyAsTypicallyVendor(VendorVo companyVendor, LocalDate verifyDate, MessageHolder holder) {
        boolean valid = false;
        CompanyVo company = companyService.findById(companyVendor.getCompanyId());
        // 检查营业状态
        String entStatus = company.getEntStatus();
        if (StringUtils.hasText(entStatus)) {
            if (entStatus.contains("注销")) {
                holder.error("营业状态异常：" + entStatus + ", 自动设置为不合格");
                companyVendor.setType(VendorType.UNQUALIFIED);
                companyVendor.setDescription(MyStringUtils.appendIfAbsent(companyVendor.getDescription(),
                        "自动检测到营业状态为" + entStatus + ",设置为不合格供应商."));
                valid = true;
            }
        } else {
            holder.error("营业状态异常：" + entStatus);
            valid = true;
        }

        if (!StringUtils.hasText(companyVendor.getPurchase())) {
            holder.error("未设置采购的产品");
            valid = true;
        }

        if (!StringUtils.hasText(companyVendor.getPath())) {
            holder.error("未设置文件夹");
            valid = true;
        }
        return valid;
    }

    public boolean makePathAbsent(VendorVo companyVendor) {
        String path = companyVendor.getPath();
        if (StringUtils.hasText(path)) {
            File file = new File(path);
            if (file.exists()) {
                return false;
            }
        }

        File dir = makePath(companyVendor);
        if (dir == null) {
            return false;
        }
        if (!dir.exists()) {
            return false;
        }
        companyVendor.setPath(dir.getAbsolutePath());
        return true;
    }

    public File makePath(VendorVo companyVendor) {
        File basePath = getBasePath();
        CompanyVo company = companyService.findById(companyVendor.getCompanyId());
        String companyName = company.getName();
        String fileName = CompanyUtils.formatCompanyVendorId(companyVendor.getId()) + "-"
                + FileUtils.escapeFileName(companyName);

        File dir = new File(basePath, fileName);
        if (!dir.exists()) {
            if (!dir.mkdir()) {
                return null;
            }
        }
        return dir;
    }

    @Override
    @Cacheable(key = "#p0")
    public VendorVo findById(Integer id) {
        return super.findById(id);
    }

    @Override
    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'company-'+#p0.companyId")
    })
    public VendorVo save(VendorVo entity) {
        return super.save(entity);
    }

    @Override
    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'company-'+#p0.companyId")
    })
    public void delete(VendorVo entity) {
        super.delete(entity);
    }
}
