package com.zfire.mall.manager.logic.k3;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.k3.RequestApiBean;
import com.zfire.mall.manager.bean.supplier.KingDeeSupplierVO;
import com.zfire.mall.manager.commonmapper.CommonCountMapper;
import com.zfire.mall.manager.constant.KingDeeCons;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.plus.entity.KingDeeCustomer;
import com.zfire.mall.manager.plus.entity.KingDeeSupplier;
import com.zfire.mall.manager.plus.service.KingDeeSupplierService;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.mall.manager.zfire.util.FieldUtils;
import lombok.extern.slf4j.Slf4j;
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.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class K3SupplierLogic {

    @Autowired
    KingDeeSupplierService kingDeeSupplierService;

    @Autowired
    K3Logic k3Logic;

    @Autowired
    CommonCountMapper commonCountMapper;

    public IPage<KingDeeSupplier> list(String number, String name, String useOrgNumber, String useOrgName, String shortName, String groupName, String auditName, Integer pageNum, Integer pageSize) {
       return kingDeeSupplierService.lambdaQuery()
                .eq(StringUtils.isNotBlank(number),KingDeeSupplier::getNumber,number)
                .eq(StringUtils.isNotBlank(name),KingDeeSupplier::getName,name)
                .eq(StringUtils.isNotBlank(useOrgNumber),KingDeeSupplier::getUseOrgNumber,useOrgNumber)
                .eq(StringUtils.isNotBlank(useOrgName),KingDeeSupplier::getUseOrgName,useOrgName)
                .eq(StringUtils.isNotBlank(shortName),KingDeeSupplier::getShortName,shortName)
                .eq(StringUtils.isNotBlank(groupName),KingDeeSupplier::getGroupName,groupName)
                .eq(StringUtils.isNotBlank(auditName),KingDeeSupplier::getAuditName,auditName)
                .page(new Page<>(pageNum,pageSize));
    }


//    public void allSync(String orgId, String orgNumber, String startTime, String endTime) throws Exception {
//        // 调用供应商接口
//        RequestApiBean request = k3Logic.getInstance(orgId, orgNumber, KingDeeCons.SUPPLIER_INFO, startTime, endTime);
//        String filterStr = "FDocumentStatus = 'C' AND FUseOrgId.FNUMBER = %s "+ k3Logic.supplySql("FAuditDate", request.getStartTime(), request.getEndTime());
//        request.setFieldKeys("FSupplierId,FNumber,FName,FUseOrgId,FUseOrgId.FNumber,FUseOrgId.FName,FShortName,FGroup.FNumber,FGroup.FName,FAuditorId.FName,FCreateOrgId.FName,FRegNumber,FCountry,FProvincial," +
//                "FAddress,FZip,FLanguage,FWebSite,FTrade,FFoundDate,FLegalPerson,FRegisterFund,FRegisterCode,FTendPermit,FSOCIALCRECODE,FRegisterAddress,FDeptId.FName,FStaffId.FName,"+
//                "FSupplierClassify,FSupplyClassify,FSupplierGrade,FCompanyClassify,FCompanyNature,FCompanyScale,FCorrespondOrgId.FName");
//        request.setFilterString(String.format(filterStr, orgNumber));
//        request.setOrderString("FSupplierId ASC");
//
//        String[] fields = new String[]{"id", "number", "name", "useOrgId", "useOrgNumber", "useOrgName", "shortName", "groupNumber", "groupName", "auditName", "createOrgName", "regNumber", "country", "provincial",
//               "address", "zip", "language", "webSite", "trade", "foundDate", "legalPerson", "registerFund", "registerCode", "tendPermit","socialCreCode", "registerAddress","deptName", "staffName",
//               "supplierClassify","supplyClassify", "supplierGrade", "companyClassify", "companyNature", "companyScale", "correspondOrgName"};
//        List<KingDeeSupplier> objects = k3Logic.allSync(request, fields, KingDeeSupplier.class);
//        if (CollectionUtils.isNotEmpty(objects)) {
//            kingDeeSupplierService.saveOrUpdateBatch(objects);
//        }
//    }

    public KingDeeSupplier detail(String id) {
        return kingDeeSupplierService.getById(id);
    }

    public IPage<KingDeeSupplierVO> listV2(ZfireParamBean zfireParamBean) {
        zfireParamBean = FieldUtils.supplyParam(zfireParamBean);
        return commonCountMapper.listV2(new Page(zfireParamBean.getPageNum(),zfireParamBean.getPageSize()),zfireParamBean);
    }

    public void add(KingDeeSupplier kingDeeSupplier) {

        if (kingDeeSupplierService.lambdaQuery().eq(KingDeeSupplier::getNumber,kingDeeSupplier.getNumber()).count() > 0)
            throw new RemoteServiceException("供应商编号重复");

        kingDeeSupplier.setId(kingDeeSupplier.getNumber());

        kingDeeSupplier.insert();
    }

    public void updateCustomer(KingDeeSupplier kingDeeSupplier) {
        if (kingDeeSupplierService.lambdaQuery().eq(KingDeeSupplier::getNumber,kingDeeSupplier.getNumber())
                .ne(KingDeeSupplier::getId,kingDeeSupplier.getId()).count() > 0)
            throw new RemoteServiceException("供应商编号重复");

        kingDeeSupplier.setId(kingDeeSupplier.getNumber());

        kingDeeSupplier.updateById();
    }

    @Transactional(rollbackFor = Exception.class)
    public void importData(List<Object> datas) {

        int index = 1;

        List<KingDeeSupplier> kingDeeSuppliers = new ArrayList<>();

        for(Object o : datas) {

            index++;
            List<Object> row = (List<Object>) o;
            if (org.apache.commons.lang3.StringUtils.isEmpty((String) row.get(0)))
                continue;

            KingDeeSupplier kingDeeSupplier = new KingDeeSupplier();
            kingDeeSupplier.setName((String) row.get(0));
            kingDeeSupplier.setNumber((String)row.get(1));
            kingDeeSupplier.setId((String)row.get(1));

            if (com.aliyuncs.utils.StringUtils.isEmpty((String) row.get(0)) || com.aliyuncs.utils.StringUtils.isEmpty((String) row.get(1)))
                throw new RemoteServiceException("第"+index+"行,供应商名称编号有误，请检查");

            kingDeeSupplier.setUseOrgId((String)row.get(2));
            kingDeeSupplier.setUseOrgNumber((String)row.get(3));
            kingDeeSupplier.setUseOrgName((String)row.get(4));


            if (com.aliyuncs.utils.StringUtils.isEmpty((String)row.get(5)))
                throw new RemoteServiceException("第"+index+"行,状态填入有误");

            kingDeeSupplier.setForbidStatus(((String)row.get(5)).equals("启用")?"A":"B");

            kingDeeSupplier.setShortName((String)row.get(6));
            kingDeeSupplier.setGroupNumber((String)row.get(7));
            kingDeeSupplier.setGroupName((String)row.get(8));
            kingDeeSupplier.setRegNumber((String)row.get(9));
            kingDeeSupplier.setCountry((String)row.get(10));
            kingDeeSupplier.setProvincial((String)row.get(11));
            kingDeeSupplier.setAddress((String)row.get(12));
            kingDeeSupplier.setZip((String)row.get(13));
            kingDeeSupplier.setLanguage((String)row.get(14));
            kingDeeSupplier.setWebSite((String)row.get(15));
            kingDeeSupplier.setTrade((String)row.get(16));

            try {
                if (!StringUtils.isEmpty((String) row.get(17))) {
                    DateTime parse = DateUtil.parse((String) row.get(17));
                    kingDeeSupplier.setFoundDate(parse);
                }
            }catch (Exception e){
                throw new RemoteServiceException("第"+index+"行,创立日期填入有误");
            }




            kingDeeSupplier.setLegalPerson((String)row.get(18));

            kingDeeSupplier.setRegisterFund((BigDecimal) row.get(19));

            kingDeeSupplier.setRegisterCode((String)row.get(20));
            kingDeeSupplier.setTendPermit((String)row.get(21));
            kingDeeSupplier.setSocialCreCode((String)row.get(22));
            kingDeeSupplier.setRegisterAddress((String)row.get(23));
            kingDeeSupplier.setDeptName((String)row.get(24));
            kingDeeSupplier.setStaffName((String)row.get(25));
            kingDeeSupplier.setSupplierClassify((String)row.get(26));
            kingDeeSupplier.setSupplyClassify((String)row.get(27));
            kingDeeSupplier.setSupplierGrade((String)row.get(28));
            kingDeeSupplier.setCompanyClassify((String)row.get(29));
            kingDeeSupplier.setCompanyNature((String)row.get(30));
            kingDeeSupplier.setCompanyScale((String)row.get(31));

            kingDeeSuppliers.add(kingDeeSupplier);

        }

        kingDeeSupplierService.saveOrUpdateBatch(kingDeeSuppliers);
    }

    public void del(String id) {
        kingDeeSupplierService.removeById(id);
    }
}
