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

import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.utils.StringUtils;
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.ExcelData;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.front.EquipmentCodeVO;
import com.zfire.mall.manager.bean.k3.K3CustomerBean;
import com.zfire.mall.manager.bean.k3.RequestApiBean;
import com.zfire.mall.manager.bean.listV2.K3CustomerJiaXianVO;
import com.zfire.mall.manager.bean.listV2.K3CustomerVO;
import com.zfire.mall.manager.commonmapper.CommonCountMapper;
import com.zfire.mall.manager.commonmapper.listV2.CommonCMapper;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.constant.KingDeeCons;
import com.zfire.mall.manager.enums.IsEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.OperatorLogic;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.wallet.WalletLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.KingDeeCategoryService;
import com.zfire.mall.manager.plus.service.KingDeeCustomerCategoryService;
import com.zfire.mall.manager.plus.service.KingDeeCustomerService;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.mall.manager.zfire.util.FieldUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class K3CustomerLogic {

    @Autowired
    K3Logic k3Logic;
    @Autowired
    CommonLogic commonLogic;
    @Autowired
    WalletLogic walletLogic;
    @Autowired
    KingDeeCustomerCategoryService kingDeeCustomerCategoryService;
    @Autowired
    KingDeeCategoryService kingDeeCategoryService;
    @Autowired
    KingDeeCustomerService kingDeeCustomerService;
    @Autowired
    CommonCountMapper commonCountMapper;
    @Autowired
    CommonCMapper commonCMapper;

    @Value("${gongdan.url}")
    private String k3CloudURL;

    @Value("${equipment.code.url}")
    private String equipmentCodeUrl;





//    @Transactional(propagation = Propagation.REQUIRES_NEW)
//    public void allSync(String orgId, String orgNumber, String startTime, String endTime) throws Exception {
//        //String filterStr = "FDocumentStatus = 'C' AND FApproveDate > '%s' AND FApproveDate <= '%s'";
//
//        // 登录成功调客户接口
//        RequestApiBean request = k3Logic.getInstance(orgId, orgNumber, KingDeeCons.CUSTOMER_INFO, startTime, endTime);
//        String filterStr = "FDocumentStatus = 'C' AND FUseOrgId.FNUMBER = %s " + k3Logic.supplySql(request.getStartTime(), request.getEndTime());
//        request.setFieldKeys("FCUSTID,FNUMBER,FNAME,FUseOrgId,FUseOrgId.FNUMBER,FUseOrgId.FName,FTEL,FSALDEPTID.FNumber,FSALDEPTID.FName," +
//                "FINVOICETITLE,FTAXREGISTERCODE,FINVOICEBANKNAME,FINVOICEBANKACCOUNT,FINVOICETEL,FINVOICEADDRESS,FEMail,FPROVINCE,FCITY,FPROVINCIAL,F_kls_Text");
//        request.setFilterString(String.format(filterStr, orgNumber));
//        request.setOrderString("FCUSTID ASC");
//
//
//        String[] fields = new String[]{"id","number","name","useOrgId","useOrgNumber","useOrgName","mobile","saleDeptNumber","saleDeptName",
//        "invoiceTitle","taxNo","bank","bankAccount","invoicePhone","invoiceAddress","email","province","city","region","secondCustomerNumber"};
//        List<KingDeeCustomer> objects = k3Logic.allSync(request, fields, KingDeeCustomer.class);
//        if (!org.springframework.util.CollectionUtils.isEmpty(objects)) {
//            kingDeeCustomerService.saveOrUpdateBatch(objects);
//
//            //初始化钱包
//            for(KingDeeCustomer kingDeeCustomer :objects){
//                    walletLogic.initByK3Customer(kingDeeCustomer.getId());
//            }
//
//        }
//    }

    /**
     * 经销商列表-v2
     * @param zfireParamBean
     * @return
     */
    public IPage<K3CustomerVO> listV2(ZfireParamBean zfireParamBean){
        zfireParamBean = FieldUtils.supplyParam(zfireParamBean);
        IPage<K3CustomerVO> k3CustomerVOIPage = commonCMapper.queryK3CutomerList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        return k3CustomerVOIPage;
    }


    /**
     * 所有经销商
     * @return
     */
    public List<KingDeeCustomer> allList(){
        return kingDeeCustomerService.list();
    }


    /**
     * 获取客户所属集团的所有客户id，如果没有集团则只返回自己
     * @return
     */
    public List<String> getGroupCustomerId(String customerId){
        //最大提货组数,限制经销商/集团 最多可以下当前政策多少单
        KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(customerId);
        List<String> customerIds = new ArrayList<>();
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(kingDeeCustomer.getParentId())){
            List<KingDeeCustomer> groupCustomers = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getParentId, kingDeeCustomer.getParentId()).list();
            customerIds = groupCustomers.stream().map(KingDeeCustomer::getId).collect(Collectors.toList());
        }
        customerIds.add(customerId);
        return customerIds.stream().distinct().collect(Collectors.toList());
    }


    /**
     * 经销商列表-v1
     * @param keyword
     * @param region
     * @param bindUser
     * @param isGroupCompany
     * @param websitNumber
     * @param adminUserId
     * @param pageNum
     * @param pageSize
     * @return
     */
    public IPage<KingDeeCustomer> list(String keyword,String region,Boolean bindUser,Boolean isGroupCompany,String websitNumber,
                                       String adminUserId,Integer pageNum,Integer pageSize,String jianXianType){
        AdminUserCom adminUser = commonLogic.getAdminUser();

        AdminUser notFilterCustomer = commonLogic.getAdminUser(adminUserId);
        String notFilterCustomerId = notFilterCustomer != null ? notFilterCustomer.getCustomerId() : "";

        String customerId = adminUser.getIsCustomer()? adminUser.getCustomerId():"";
        IPage<KingDeeCustomer> page = commonCountMapper.queryKingDeeCustomer(new Page(pageNum, pageSize), keyword, region,
                bindUser, isGroupCompany, customerId,websitNumber,notFilterCustomerId,jianXianType);
        return page;
    }


    /**
     * 经销商详情
     * @param id
     * @return
     */
    public K3CustomerBean detail(String id){
        KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(id);
        if(kingDeeCustomer == null){
            return null;
        }
        K3CustomerBean k3CustomerBean = new K3CustomerBean();
        BeanUtils.copyProperties(kingDeeCustomer,k3CustomerBean);

        List<CustomerWallet> list = walletLogic.queryCustomerWalletByCustomerId(k3CustomerBean.getId());
        k3CustomerBean.setCustomerWallets(list);
        if(k3CustomerBean.getIsGroupCompany()){
            //查询子经销商
            List<KingDeeCustomer> list1 = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getParentId, id).list();
            k3CustomerBean.setKingDeeCustomers(list1);
        }
        k3CustomerBean.setKingDeeCustomerCategories(kingDeeCustomerCategoryService.lambdaQuery()
                .eq(KingDeeCustomerCategory::getCustomerId,kingDeeCustomer.getId())
                .eq(KingDeeCustomerCategory::getType,1).list());
        k3CustomerBean.setKingDeeCustomerCategoriesFront(kingDeeCustomerCategoryService.lambdaQuery().eq(KingDeeCustomerCategory::getCustomerId,kingDeeCustomer.getId())
                .eq(KingDeeCustomerCategory::getType,2).list());

        return k3CustomerBean;
    }


    public KingDeeCustomer bindUser(String customerId){
        KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(customerId);
        kingDeeCustomer.setBindUser(true);
        kingDeeCustomer.updateById();
        return kingDeeCustomer;
    }


    /**
     * 集团经销商
     */
    public List<KingDeeCustomer> groupCompanyList(){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getCustomerId();
        KingDeeCustomer customer = kingDeeCustomerService.getById(customerId);
        String parentId = customer != null ? customer.getParentId() : "";

        List<KingDeeCustomer> list = kingDeeCustomerService.lambdaQuery()
                .eq(customer != null,KingDeeCustomer::getId, customerId)
                .or()
                .eq(StringUtils.isNotEmpty(parentId),KingDeeCustomer::getParentId,parentId)
                .list();

        return list;
    }


    public ExcelData export(List<KingDeeCustomer> kingDeeCustomers) {
        String[] titles = new String[]{"经销商编码", "经销商名称", "联系电话", "使用组织名称"
                , "是否为集团公司","集团公司","是否拥有转折让钱包权限"};
        List<List<Object>> rows = new ArrayList<>();
        for (KingDeeCustomer kingDeeCustomer : kingDeeCustomers) {
            List<Object> row = new ArrayList<>();
            row.add(kingDeeCustomer.getNumber());
            row.add(kingDeeCustomer.getName());
            row.add(kingDeeCustomer.getMobile());
            row.add(kingDeeCustomer.getUseOrgName());
            row.add(kingDeeCustomer.getIsGroupCompany() ? "是" : "否" );
            if(StringUtils.isNotEmpty(kingDeeCustomer.getParentId())){
                KingDeeCustomer k = kingDeeCustomerService.getById(kingDeeCustomer.getParentId());
                row.add(k == null ? "" : k.getName());
            }else{
                row.add("");
            }
            row.add(kingDeeCustomer.getIsZr() ? "是" : "否");
            //row.add(kingDeeCustomer.getIsFront()?"是":"否");
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }

    public void update(String id, Boolean isFront) {
        KingDeeCustomer kingDeeCustomer = new KingDeeCustomer();
        kingDeeCustomer.setId(id);
        kingDeeCustomer.setIsFront(isFront);
        kingDeeCustomer.updateById();
    }

    public void importCustomer(List<Object> objects) {

        //导入修改是否是前置仓
        List<KingDeeCustomer> kingDeeCustomers = kingDeeCustomerService.lambdaQuery().list();
        List<KingDeeCategory> kingDeeCategories = kingDeeCategoryService.lambdaQuery().list();

        List<KingDeeCustomerCategory> kingDeeCustomerCategories = new ArrayList<>();
        List<String> customerId = new ArrayList<>();
        for(Object o : objects) {
            List<Object> row = (List<Object>) o;
            if (row.get(0) == null)
                continue;
            List<KingDeeCustomer> collect = kingDeeCustomers.stream().filter(item -> item.getNumber().equals(row.get(0))).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(collect))
                continue;

            customerId.add(collect.get(0).getId());

            List<KingDeeCategory> kingDeeCategories1 = kingDeeCategories.stream().filter(item -> item.getName().equals(row.get(2))).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(kingDeeCategories1))
                continue;
            if (row.get(3).equals(IsEnum.YES.getValue())) {
                KingDeeCustomerCategory kingDeeCustomerCategory = new KingDeeCustomerCategory();
                kingDeeCustomerCategory.setType(2);
                kingDeeCustomerCategory.setCategoryName(kingDeeCategories1.get(0).getName());
                kingDeeCustomerCategory.setCategoryId(kingDeeCategories1.get(0).getId());
                kingDeeCustomerCategory.setCustomerId(collect.get(0).getId());
                kingDeeCustomerCategories.add(kingDeeCustomerCategory);
            }

            if (row.get(4).equals(IsEnum.YES.getValue())) {
                KingDeeCustomerCategory kingDeeCustomerCategory = new KingDeeCustomerCategory();
                kingDeeCustomerCategory.setType(1);
                kingDeeCustomerCategory.setCategoryName(kingDeeCategories1.get(0).getName());
                kingDeeCustomerCategory.setCategoryId(kingDeeCategories1.get(0).getId());
                kingDeeCustomerCategory.setCustomerId(collect.get(0).getId());
                kingDeeCustomerCategories.add(kingDeeCustomerCategory);
            }

        }
        kingDeeCustomerCategoryService.lambdaUpdate().in(KingDeeCustomerCategory::getCustomerId,customerId).remove();
        kingDeeCustomerCategoryService.saveBatch(kingDeeCustomerCategories);

    }

    public void updatePick(String id, Boolean isFront, Boolean isPick, List<String> pickCategory,List<String> frontCategory) {
        KingDeeCustomer kingDeeCustomer = new KingDeeCustomer();
        kingDeeCustomer.setId(id);
        kingDeeCustomer.setIsFront(isFront);
        kingDeeCustomer.setIsPick(isPick);
        kingDeeCustomer.setFrontPickType(true);
        kingDeeCustomer.updateById();
        List<KingDeeCustomerCategory> kingDeeCustomerCategories = new ArrayList<>();
        kingDeeCustomerCategoryService.lambdaUpdate().eq(KingDeeCustomerCategory::getCustomerId,id).remove();
        if (CollectionUtils.isNotEmpty(pickCategory))
        {
            for (String s : pickCategory) {
                KingDeeCategory kingDeeCategory = kingDeeCategoryService.getById(s);
                KingDeeCustomerCategory kingDeeCustomerCategory = new KingDeeCustomerCategory();
                kingDeeCustomerCategory.setCustomerId(id);
                kingDeeCustomerCategory.setCategoryId(s);
                kingDeeCustomerCategory.setCategoryName(kingDeeCategory.getName());
                kingDeeCustomerCategories.add(kingDeeCustomerCategory);
            }

        }

        if (CollectionUtils.isNotEmpty(frontCategory))
        {
            for (String s : frontCategory) {
                KingDeeCategory kingDeeCategory = kingDeeCategoryService.getById(s);
                KingDeeCustomerCategory kingDeeCustomerCategory = new KingDeeCustomerCategory();
                kingDeeCustomerCategory.setCustomerId(id);
                kingDeeCustomerCategory.setCategoryId(s);
                kingDeeCustomerCategory.setCategoryName(kingDeeCategory.getName());
                kingDeeCustomerCategory.setType(2);
                kingDeeCustomerCategories.add(kingDeeCustomerCategory);
            }

        }
        kingDeeCustomerCategoryService.saveBatch(kingDeeCustomerCategories);


        commonLogic.saveLog(id);
    }

    public void updateSystem(String id, String afterNumber) {

            try {
                HashMap<String, Object> paramToken = new HashMap<>();
                paramToken.put("key", equipmentCodeUrl);
                String bodyParam = HttpRequest.get(k3CloudURL + Constant.SUPPLY_EXTERNAL_CODE_GET_TOKEN)
                        .form(paramToken).execute().body();
                Map<String, Object> smsRspParam = JSON.parseObject(bodyParam);

                HashMap<String, Object> paramMap = new HashMap<>();
                paramMap.put("websitNumber", afterNumber);

                String body = HttpRequest.get(k3CloudURL + Constant.SUPPLY_EXTERNAL_CODE_IS_WEBSIT)
                        .header("token", smsRspParam.get("data").toString())
                        .form(paramMap).execute().body();

                Map<String, Object> smsRsp = JSON.parseObject(body);
                //获取数据
                Object data = smsRsp.get("data");
                if (!Convert.toBool(data))
                    throw new RemoteServiceException("没有对应网点");

                AdminUserCom adminUser = commonLogic.getAdminUser();
                KingDeeCustomer kingDeeCustomer = new KingDeeCustomer();
                kingDeeCustomer.setId(id);
                kingDeeCustomer.setAfterNumber(afterNumber);
                kingDeeCustomer.setBinding("YES");
                kingDeeCustomer.setBindingName(adminUser.getNickName());
                kingDeeCustomer.setBindingTime(new Date());
                kingDeeCustomer.updateById();
            } catch (Exception e) {
                throw new RemoteServiceException(e.getMessage());
            }

    }

    public IPage<K3CustomerJiaXianVO> jiaXianV2(ZfireParamBean zfireParam) {
        zfireParam = FieldUtils.supplyParam(zfireParam);
        IPage<K3CustomerJiaXianVO> k3CustomerVOIPage = commonCMapper.jiaXianV2(new Page(zfireParam.getPageNum(), zfireParam.getPageSize()), zfireParam);
        List<KingDeeCategory> list = kingDeeCategoryService.lambdaQuery().list();
        List<KingDeeCustomerCategory> kingDeeCustomerCategories = kingDeeCustomerCategoryService.lambdaQuery().list();

        List<K3CustomerJiaXianVO> k3 = new ArrayList<>();
        for (K3CustomerJiaXianVO record : k3CustomerVOIPage.getRecords()) {
            for (KingDeeCategory kingDeeCategory : list) {
                K3CustomerJiaXianVO k3CustomerJiaXianVO = new K3CustomerJiaXianVO();
                k3CustomerJiaXianVO.setName(record.getName());
                k3CustomerJiaXianVO.setNumber(record.getNumber());
                k3CustomerJiaXianVO.setCategoryName(kingDeeCategory.getName());

                k3CustomerJiaXianVO.setPick(CollectionUtils.isNotEmpty(kingDeeCustomerCategories.stream()
                        .filter(item -> item.getCustomerId().equals(record.getId()) && item.getType().equals(2)
                        && item.getCategoryId().equals(kingDeeCategory.getId())).collect(Collectors.toList()))?"是":"否"
                );
                k3CustomerJiaXianVO.setPickZiTi(CollectionUtils.isNotEmpty(kingDeeCustomerCategories.stream()
                        .filter(item -> item.getCustomerId().equals(record.getId()) && item.getType().equals(1)
                                && item.getCategoryId().equals(kingDeeCategory.getId())).collect(Collectors.toList()))?"是":"否");
                k3.add(k3CustomerJiaXianVO);
            }
        }
        k3CustomerVOIPage.setRecords(k3);
        return k3CustomerVOIPage;
    }
}
