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

import cn.hutool.core.date.DateUtil;
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.customer.CustomerProductTypeRelaBean;
import com.zfire.mall.manager.bean.listV2.CustomerProductTypeRelaVO;
import com.zfire.mall.manager.bean.wallet.CustomerWalletBean;
import com.zfire.mall.manager.commonmapper.listV2.CommonCMapper;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.admin.AdminUserLogic;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.k3.K3DepartmentLogic;
import com.zfire.mall.manager.logic.k3.K3WalletLogic;
import com.zfire.mall.manager.logic.wallet.WalletLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.*;
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.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CustomerProductTypeLogic {


    @Autowired
    CommonLogic commonLogic;
    @Autowired
    WalletLogic walletLogic;
    @Autowired
    AdminUserLogic adminUserLogic;
    @Autowired
    K3DepartmentLogic k3DepartmentLogic;
    @Autowired
    CustomerProductTypeRelaService customerProductTypeRelaService;
    @Autowired
    AdminUserWebsitRelaService adminUserWebsitRelaService;
    @Autowired
    AdminWebsitService adminWebsitService;
    @Autowired
    KingDeeWalletService kingDeeWalletService;
    @Autowired
    KingDeeCustomerService kingDeeCustomerService;
    @Autowired
    CustomerWalletService customerWalletService;
    @Autowired
    CommonCMapper commonCMapper;


    public IPage<CustomerProductTypeRelaVO> listV2(ZfireParamBean zfireParamBean){
        zfireParamBean = FieldUtils.supplyParam(zfireParamBean);
        IPage<CustomerProductTypeRelaVO> customerProductTypeRelaVOIPage = commonCMapper.queryCustomerProductTypeRela(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        return customerProductTypeRelaVOIPage;
    }

    /**
     * 列表
     * @param customerName
     * @param customerWalletId
     * @param customerWalletName
     * @param pageNo
     * @param pageSize
     * @return
     */
    public IPage<CustomerProductTypeRelaBean> list(String customerName,String customerWalletId,String customerWalletName,Integer pageNo,Integer pageSize){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        IPage page = customerProductTypeRelaService.lambdaQuery()
                .in(CollectionUtils.isNotEmpty(adminUser.getAdminCompanyIds()),CustomerProductTypeRela::getAdminCompanyId,adminUser.getAdminCompanyIds())
                .like(StringUtils.isNotEmpty(customerName), CustomerProductTypeRela::getCustomerName, customerName)
                .like(StringUtils.isNotEmpty(customerWalletId), CustomerProductTypeRela::getCustomerWalletId, customerWalletId)
                .like(StringUtils.isNotEmpty(customerWalletName), CustomerProductTypeRela::getCustomerWalletName, customerWalletName)
                .eq(adminUser.getIsCustomer(),CustomerProductTypeRela::getCustomerId,adminUser.getCustomerId())
                .orderByDesc(CustomerProductTypeRela::getCreateTime)
                .page(new Page<>(pageNo, pageSize));

        List<KingDeeDepartment> kingDeeDepartments = k3DepartmentLogic.list();
        Map<String, String> dpMap = kingDeeDepartments.stream().collect(Collectors.toMap(KingDeeDepartment::getNumber, KingDeeDepartment::getName));

        List<CustomerProductTypeRelaBean> list = new ArrayList<>();
        for(Object o : page.getRecords()){
            CustomerProductTypeRela rela = (CustomerProductTypeRela)o;
            CustomerProductTypeRelaBean bean = new CustomerProductTypeRelaBean();
            BeanUtils.copyProperties(rela,bean);

            bean.setK3OrgName(dpMap.get(rela.getK3OrgNumber()));
            list.add(bean);
        }
        page.setRecords(list);
        return page;
    }

    public void add(CustomerProductTypeRela customerProductTypeRela){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        customerProductTypeRela.setAdminCompanyId(adminUser.getAdminCompanyId());
        if(StringUtils.isEmpty(customerProductTypeRela.getServiceId())){
            throw new RemoteServiceException("业务员不能为空");
        }
        if(StringUtils.isEmpty(customerProductTypeRela.getK3OrgNumber())){
            throw new RemoteServiceException("金蝶部门编号必填");
        }
        Integer count = customerProductTypeRelaService.lambdaQuery()
                .eq(CustomerProductTypeRela::getCustomerWalletId, customerProductTypeRela.getCustomerWalletId())
                .count();
        if(count > 0){
            throw new RemoteServiceException("请勿重复设置相同的关系");
        }
        CustomerWallet customerWallet = customerWalletService.getById(customerProductTypeRela.getCustomerWalletId());
        if(customerWallet != null) {
            customerProductTypeRela.setWalletId(customerWallet.getWalletRebateId());
        }
        customerProductTypeRela.insert();
    }


    public void update(CustomerProductTypeRela customerProductTypeRela){
        if(StringUtils.isEmpty(customerProductTypeRela.getServiceId())){
            throw new RemoteServiceException("业务员不能为空");
        }
        if(StringUtils.isEmpty(customerProductTypeRela.getK3OrgNumber())){
            throw new RemoteServiceException("金蝶部门编号必填");
        }
        Integer count = customerProductTypeRelaService.lambdaQuery()
                .eq(CustomerProductTypeRela::getCustomerWalletId, customerProductTypeRela.getCustomerWalletId())
                .ne(CustomerProductTypeRela::getId,customerProductTypeRela.getId())
                .count();
        if(count > 0){
            throw new RemoteServiceException("请勿重复设置相同的关系");
        }
        CustomerWallet customerWallet = customerWalletService.getById(customerProductTypeRela.getCustomerWalletId());
        if(customerWallet != null) {
            customerProductTypeRela.setWalletId(customerWallet.getWalletRebateId());
        }
        customerProductTypeRela.updateById();
        commonLogic.saveLog(customerProductTypeRela.getId());
    }




    public void delete(List<String> ids){
        customerProductTypeRelaService.lambdaUpdate().in(CustomerProductTypeRela::getId,ids).remove();
    }


    public CustomerProductTypeRelaBean detail(String id){
        CustomerProductTypeRelaBean bean = new CustomerProductTypeRelaBean();

        CustomerProductTypeRela customerProductTypeRela = customerProductTypeRelaService.getById(id);
        BeanUtils.copyProperties(customerProductTypeRela,bean);

        //查询业务员名称
        AdminUser au = adminUserLogic.getById(customerProductTypeRela.getServiceId());
        if(au != null) {
            bean.setServiceName(au.getUserName());
        }
        //查询上一级部门
        List<AdminUserWebsitRela> list = adminUserWebsitRelaService.lambdaQuery()
                .eq(AdminUserWebsitRela::getAdminUserId, au.getAdminUserId()).list();
        String adminWebsitId = list.get(0).getAdminWebsitId();
        AdminWebsit adminWebsit1 = adminWebsitService.getById(adminWebsitId);
        bean.setAdminWebsitId3(adminWebsit1.getAdminWebsitId());
        //查询上上级部门
        if(adminWebsit1 != null){
            AdminWebsit adminWebsit2 = adminWebsitService.getById(adminWebsit1.getParentId());
            if(adminWebsit2 != null) {
                if (adminWebsit2.getParentId().equals("1")){
                    bean.setAdminWebsitId1(adminWebsit2.getAdminWebsitId());
                    bean.setAdminWebsitId2(adminWebsit1.getAdminWebsitId());
                    bean.setAdminWebsitId3(null);

                }else {
                    bean.setAdminWebsitId2(adminWebsit2.getAdminWebsitId());
                    if (adminWebsit2 != null) {
                        AdminWebsit adminWebsit3 = adminWebsitService.getById(adminWebsit2.getParentId());
                        if (adminWebsit3 != null) {
                            bean.setAdminWebsitId1(adminWebsit3.getAdminWebsitId());
                        }
                    }
                }
            }
        }

        return bean;
    }


    /**
     * 导入钱包与业务员的关系
     */
    public void improtData(List<Object> objects){
        if(CollectionUtils.isEmpty(objects)){
            return;
        }
        //所有钱包
        List<KingDeeWallet> list = kingDeeWalletService.list();
        Map<String, KingDeeWallet> walletMap = list.stream().collect(Collectors.toMap(KingDeeWallet::getName, v -> v));
        //所有经销商
        List<KingDeeCustomer> list1 = kingDeeCustomerService.list();
        Map<String, KingDeeCustomer> customerMap = list1.stream().collect(Collectors.toMap(KingDeeCustomer::getNumber, v -> v));
        //所有业务员
        Map<String, AdminUser> userNameMap = adminUserLogic.getUserNameMap();

        for(Object o : objects){
            List<Object> row = (List<Object>)o;
            //经销商编码
            String customerNumber = (String)row.get(0);
            //钱包名称
            String walletName = (String)row.get(1);
            //业务员名称
            String serviceUserName = (String)row.get(2);
            //金蝶部门编号
            String k3OrgNumber = (String)row.get(3);

            KingDeeWallet wallet = walletMap.get(walletName);
            if(wallet == null){
                throw new RemoteServiceException("钱包名称【"+walletName+"】不存在");
            }
            AdminUser adminUser = userNameMap.get(serviceUserName);
            if(adminUser == null){
                throw new RemoteServiceException("业务员帐号【"+serviceUserName+"】不存在");
            }
            KingDeeCustomer customer = customerMap.get(customerNumber);
            if(customer == null){
                throw new RemoteServiceException("经销商编码【"+customerNumber+"】不存在");
            }
            if(StringUtils.isEmpty(k3OrgNumber)){
                throw new RemoteServiceException("经销商编码【"+customerNumber+"】的金蝶部门编号必填");
            }
            CustomerWallet customerWallet = customerWalletService.lambdaQuery()
                    .eq(CustomerWallet::getCustomerId, customer.getId())
                    .eq(CustomerWallet::getWalletRebateId, wallet.getId()).one();
            try {
                CustomerProductTypeRela customerProductTypeRela = customerProductTypeRelaService.lambdaQuery()
                        .eq(CustomerProductTypeRela::getCustomerWalletId, customerWallet.getCustomerWalletId()).one();

                if(customerProductTypeRela == null){
                    customerProductTypeRela = new CustomerProductTypeRela();
                }

                customerProductTypeRela.setAdminCompanyId(adminUser.getAdminCompanyId());
                customerProductTypeRela.setCustomerId(customer.getId());
                customerProductTypeRela.setCustomerName(customer.getName());
                customerProductTypeRela.setCustomerNumber(customer.getNumber());
                customerProductTypeRela.setWalletId(customerWallet.getWalletRebateId());
                customerProductTypeRela.setServiceId(adminUser.getAdminUserId());
                customerProductTypeRela.setServiceName(adminUser.getNickName());
                customerProductTypeRela.setCustomerWalletId(customerWallet.getCustomerWalletId());
                customerProductTypeRela.setCustomerWalletName(customerWallet.getCustomerWalletName());
                customerProductTypeRela.setK3OrgNumber(k3OrgNumber);
                customerProductTypeRela.insertOrUpdate();
            }catch(Exception e){
                log.error("新增钱包与业务员关系失败:"+e.getMessage());
            }
        }
    }

    /**
     * 导出
     */
    public ExcelData export(List<CustomerProductTypeRelaBean> list){
        List<AdminUser> adminUsers = adminUserLogic.allList();
        Map<String, AdminUser> map = adminUsers.stream().collect(Collectors.toMap(AdminUser::getAdminUserId, v -> v));

        String[] titles = new String[]{"经销商编码","钱包名称","业务员帐号","经销商名称","业务员名称","金蝶部门编号"};
        List<List<Object>> rows = new ArrayList<>();
        for (CustomerProductTypeRelaBean bean : list) {
            List<Object> row = new ArrayList<>();
            row.add(bean.getCustomerNumber());
            row.add(bean.getCustomerWalletName());
            AdminUser adminUser = map.get(bean.getServiceId());
            if(adminUser == null){
                row.add("");
            }else {
                row.add(adminUser.getUserName());
            }
            row.add(bean.getCustomerName());
            row.add(bean.getServiceName());
            row.add(bean.getK3OrgNumber());
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        excelData.setName("sheet1");
        return excelData;
    }

    /**
     *  根据钱包获取业务员
     * @param customerWalletId
     * @return
     */
    public AdminUser getService(String customerWalletId){
        CustomerProductTypeRela customerProductTypeRela = this.getByCustomerWalletId(customerWalletId);
        if(customerProductTypeRela == null){
            return null;
        }
        AdminUser adminUser = adminUserLogic.getById(customerProductTypeRela.getServiceId());
        return adminUser;
    }


    public CustomerProductTypeRela getByCustomerWalletId(String customerWalletId){
        CustomerProductTypeRela customerProductTypeRela = customerProductTypeRelaService.lambdaQuery()
                .eq(CustomerProductTypeRela::getCustomerWalletId, customerWalletId).one();
        return customerProductTypeRela;
    }

}
