package com.huigou.topsun.customer.application.Impl;


import cn.hutool.core.bean.BeanUtil;
import com.huigou.data.query.model.QueryDescriptor;
import com.huigou.data.query.model.QueryModel;
import com.huigou.topsun.customer.application.*;
import com.huigou.topsun.customer.domain.*;
import com.huigou.topsun.customer.domain.query.CustomerQueryRequest;
import com.huigou.topsun.customer.domain.vo.CustomerContactVo;
import com.huigou.topsun.customer.domain.vo.CustomerListVo;
import com.huigou.topsun.customer.domain.vo.CustomerVo;
import com.huigou.topsun.customer.domain.vo.ReturnCustomerListVo;
import com.huigou.topsun.customer.repository.*;
import com.huigou.uasp.bmp.common.application.BaseApplication;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


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


@Service
public class CustomerApplicationImpl extends BaseApplication implements CustomerApplication {
    public static final String QUERY_XML_FILE_PATH = "config/topsun/customer/customerMapper.xml";
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private CustomerBaseInfoApplication customerBaseInfoApplication;
    @Autowired
    private CustomerBankRepository customerBankRepository;
    @Autowired
    private CustomerContactRepository customerContactRepository;
    @Autowired
    private CustomerContactApplication customerContactApplication;
    @Autowired
    private CustomerDebtContactRepository CustomerDebtContactRepository;
    @Autowired
    private CustomerDebtContactApplication customerDebtContactApplication;
    @Autowired
    private CustomerRelatedRepository customerRelatedRepository;
    @Autowired
    private CustomerRelatedApplication customerRelatedApplication;
    @Autowired
    private CustomerPayInfoRepository customerPayInfoRepository;
    @Autowired
    private CustomerPayInfoApplication customerPayInfoApplication;
    @Autowired
    private CustomerOrderRepository customerOrderRepository;


    /**
     * 分页查询客户信息数据
     *
     * @param customerQueryRequest
     * @return
     */
    @Override
    public Map<String, Object> findCustomerByPage(CustomerQueryRequest customerQueryRequest) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "customerList");
        QueryModel model = this.sqlExecutorDao.getQueryModel(queryDescriptor, customerQueryRequest);
        return this.sqlExecutorDao.executeSlicedQuery(model);
    }

    /**
     * 分页查询联系人信息
     *
     * @param customerId
     * @return
     */
    @Override
    public List<CustomerContact> findContactByPage(String customerId) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "contactList");
        List<CustomerContact> customerContactList = this.sqlExecutorDao.queryToList(queryDescriptor.getSql(), CustomerContact.class, customerId);
        return customerContactList;
    }

    /**
     * 根据单个id删除
     *
     * @param id
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void deleteContactById(String id) {
        customerContactRepository.delete(id);
    }

    /**
     * 批量进行删除
     *
     * @param ids
     */

    @Override
    @Transactional
    public void deleteContactByIds(List<String> ids) {
        ids.forEach(this::deleteContactById);
    }

    /**
     * 保存客户信息（多表保存）
     *
     * @param customerVo
     * @param customerContactList
     * @param baoshenEmailList
     * @param customerEmailList
     * @param customerRelatedList
     * @param customerPayInfoList
     * @return
     */

    @Override
    public CustomerVo saveCustomer(CustomerVo customerVo, List<CustomerContact> customerContactList, List<CustomerDebtContact> baoshenEmailList, List<CustomerDebtContact> customerEmailList, List<CustomerRelated> customerRelatedList, List<CustomerPayInfo> customerPayInfoList) {
        Customer customer = getCustomer(customerVo);
        CustomerBank customerBank = getCustomerBank(customerVo);
        CustomerOrder customerOrder = getCustomerOrder(customerVo);
        Customer saveCustomer = customerRepository.saveAndFlush(customer);
        String customerId = saveCustomer.getCustomerId();
        customerBank.setCustomerId(customerId);
        CustomerBank saveCustomerBank = customerBankRepository.saveAndFlush(customerBank);
        customerOrder.setCustomerId(customerId);
        CustomerOrder saveCustomerOrder = customerOrderRepository.saveAndFlush(customerOrder);
        customerContactList.forEach(customerContact -> {
            customerContact.setCustomerId(customerId);
            customerContactRepository.saveAndFlush(customerContact);
        });
//        for (CustomerDebtContact customerDebtContact : baoshenEmailList) {
//            customerDebtContact.setCustomerEmailType("1");
//            CustomerDebtContactRepository.saveAndFlush(customerDebtContact);
//        }
        customerEmailList.forEach(customerDebtContact -> {
            customerDebtContact.setCustomerId(customerId);
            customerDebtContact.setCustomerEmailType("1");
            CustomerDebtContactRepository.saveAndFlush(customerDebtContact);
        });
        baoshenEmailList.forEach(customerDebtContact -> {
            customerDebtContact.setCustomerId(customerId);
            customerDebtContact.setCustomerEmailType("0");
            CustomerDebtContactRepository.saveAndFlush(customerDebtContact);
        });
        customerRelatedList.forEach(customerRelated -> {
            customerRelated.setCustomerId(customerId);
            customerRelatedRepository.saveAndFlush(customerRelated);
        });
        customerPayInfoList.forEach(customerPayInfo -> {
            customerPayInfo.setCustomerId(customerId);
            customerPayInfoRepository.saveAndFlush(customerPayInfo);
        });
        CustomerVo saveCustomerVo = new CustomerVo();
        BeanUtils.copyProperties(saveCustomer, saveCustomerVo);
        BeanUtils.copyProperties(saveCustomerBank, saveCustomerVo);
        BeanUtils.copyProperties(saveCustomerOrder, saveCustomerVo);
        return saveCustomerVo;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void deleteCustomerAndAffiliatedInfoByCustomerId(List<String> customerIds) {

        for (String customerId : customerIds) {
            customerRepository.delete(customerId);
            customerBaseInfoApplication.deleteByCustomerId(customerId);
            customerContactApplication.deleteByCustomerId(customerId);
            customerDebtContactApplication.deleteByCustomerId(customerId);
            customerRelatedApplication.deleteByCustomerId(customerId);
            customerPayInfoApplication.deleteByCustomerId(customerId);
        }

    }

    @Override
    public List<CustomerListVo> getCustomerList() {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "getCustomerList");
        List<CustomerListVo> customerListVoList = this.sqlExecutorDao.queryToList(queryDescriptor.getSql(), CustomerListVo.class);

        return customerListVoList;
    }

    @Override
    public List<ReturnCustomerListVo> getReturnCustomerListVoList(List<CustomerListVo> customerListVoList) {
        List<ReturnCustomerListVo> returnCustomerListVoList = new ArrayList<>();
        List<String> customerIdList = new ArrayList<>();
        for (CustomerListVo customerListVo : customerListVoList) {
            if (!BeanUtil.isEmpty(customerListVo)) {
                String customerId = customerListVo.getCustomerId();
                customerIdList.add(customerId);
            }
        }
        List<String> idList = customerIdList.stream().distinct().collect(Collectors.toList());

        for (String s : idList) {
            ReturnCustomerListVo returnCustomerListVo = new ReturnCustomerListVo();
            List<CustomerContactVo> customerContactVoList = new ArrayList<>();
            for (CustomerListVo customerListVo : customerListVoList) {
                if (!BeanUtil.isEmpty(customerListVo)) {
                    if (s.equals(customerListVo.getCustomerId())) {
                        CustomerContactVo customerContactVo = new CustomerContactVo();
                        BeanUtil.copyProperties(customerListVo, customerContactVo);
                        customerContactVoList.add(customerContactVo);
                        returnCustomerListVo.setCustomerContactVoList(customerContactVoList);
//                        BeanUtil.copyProperties(returnCustomerListVo,customerContactVo);
                        String provinceCode = customerListVo.getProvinceCode();
                        Map<String,String> provinceMap = customerBaseInfoApplication.findByProvinceCode(provinceCode);
                        StringBuffer provinceInfoStringBuffer = new StringBuffer();
                        if (provinceMap.get("grandParentProvince")!=null) {
                            provinceInfoStringBuffer.append(provinceMap.get("grandParentProvince"));
                        }
                        if (provinceMap.get("parentProvince")!=null) {
                            provinceInfoStringBuffer.append(provinceMap.get("parentProvince"));
                        }
                        if (provinceMap.get("province")!=null) {
                            provinceInfoStringBuffer.append(provinceMap.get("province"));
                        }

                        String provinceInfo = provinceInfoStringBuffer.toString();
                        BeanUtils.copyProperties(customerListVo, returnCustomerListVo);
                        returnCustomerListVo.setBelongArea(provinceInfo);
                    }
                }
            }
            returnCustomerListVoList.add(returnCustomerListVo);
        }
        return returnCustomerListVoList;

    }


    public Customer getCustomer(CustomerVo customerVo) {
        Customer customer = new Customer();
        BeanUtils.copyProperties(customerVo, customer);
        return customer;
    }

    public CustomerBank getCustomerBank(CustomerVo customerVo) {
        CustomerBank customerBank = new CustomerBank();
        BeanUtils.copyProperties(customerVo, customerBank);
        return customerBank;
    }

    public CustomerOrder getCustomerOrder(CustomerVo customerVo) {
        CustomerOrder customerOrder = new CustomerOrder();
        BeanUtils.copyProperties(customerVo, customerOrder);
        return customerOrder;
    }
}
