package com.ssm.manage.service.impl;

import com.github.pagehelper.PageInfo;
import com.ssm.core.utils.AESUtils;
import com.ssm.core.utils.StoreParaUtils;
import com.ssm.manage.entity.*;
import com.ssm.manage.query.StoreRequest;
import com.ssm.manage.response.DebtDayVo;
import com.ssm.manage.response.StaffResponse;
import com.ssm.manage.service.*;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.SsmDebtDao;
import com.ssm.manage.extendEntity.AchiCommEntity;
import com.ssm.manage.query.DebtListRequest;
import com.ssm.manage.query.StaffRequest;
import com.ssm.manage.response.DebtListResponse;
import com.ssm.manage.utils.Constant;
import com.ssm.util.RedisClient;
import org.springframework.beans.BeanUtils;
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.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@Service
public class SsmDebtServiceImpl extends BaseServiceImpl<DebtList> implements SsmDebtService {

    @Autowired
    private RedisClient<StaffResponse> redisClient;
    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;
    @Autowired
    private SsmProjectService ssmProjectService;
    @Autowired
    private SsmCourseAccountService ssmCourseAccountService;
    @Autowired
    SsmStoreMemberService ssmStoreMemberService;

    @Autowired
    private SsmDebtDao dao;

    @Override
    public SsmDebtDao getDao() {
        return dao;
    }

    @Override

    public PageInfo<DebtListResponse> selectPage(DebtListRequest debtListRequest) throws SmsException {
        List<DebtListResponse> listResponses = new ArrayList<>();
        String mobilePhone = debtListRequest.getMobilePhone();
        //总店ID
        Long storeid=null;
        //当前门店组织
        List<Long> objects = new ArrayList<>();

        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(debtListRequest.getStoreId());
        debtListRequest.setStId(storeRequest.getId());
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            if(null == pagesorganization.getParentId()){
                storeid=pagesorganization.getId();
            }
            objects.add(pagesorganization.getId());
        }
        PageInfo<DebtList> pageInfo=new PageInfo<>();
        if(storeid.equals(debtListRequest.getStoreId())){
            //总店
            if(mobilePhone !=null && mobilePhone.length()>0){
                String phone = AESUtils.encrypt(mobilePhone);
                StoreMemberList storeMemberList = new StoreMemberList();
                storeMemberList.setMobilePhone(phone);
                List<StoreMemberList> select = ssmStoreMemberService.select(storeMemberList);
                if(select==null||select.size()==0){
                    throw new SmsException("50101","会员不存在");
                }
                StoreMemberList memberList = select.get(0);
                debtListRequest.setMemberId(memberList.getId());
            }
            debtListRequest.setIds(objects);
            debtListRequest.setStoreId(null);
           pageInfo = dao.selectPage(debtListRequest);
           debtListRequest.setMobilePhone(mobilePhone);
            for (DebtList debtList : pageInfo.getList()) {
                StoreRequest storeRequest1 = new StoreRequest();
                storeRequest1.setId(debtList.getStoreId());
                BaseStore baseStore = ssmBaseStoreService.selectOne(storeRequest1);
                DebtListResponse debtListResponse = new DebtListResponse();
                debtListResponse.setStoreNum(baseStore.getStoreNum());
                BeanUtils.copyProperties(debtList,debtListResponse);
                //设置业务人员列表
                List<AchiCommEntity> entities = this.getAchiCommList(debtList);
                debtListResponse.setEntities(entities);

                if(debtListResponse.getDocType().equals("promotion_card_use")){
                    CourseAccount courseAccount = new CourseAccount();
                    courseAccount.setPromotionDocId(debtListResponse.getDocId());
                    List<CourseAccount> select = ssmCourseAccountService.select(courseAccount);
                    List<CancelDebtMx> cancelDebtMxes = new ArrayList<>();
                    for (CourseAccount account : select) {
                        if(account.getCourseType().equals("1")){
                            CancelDebtMx cancelDebtMx = new CancelDebtMx();
                            cancelDebtMx.setCourseId(account.getId());
                            cancelDebtMx.setCourseProjectId(account.getCourseProjectId());

                            cancelDebtMx.setCourseProjectName(account.getCourseProjectName());
                            cancelDebtMx.setDebtMoney(account.getUnrecordedAmount().subtract(account.getCancelMoney()));
                            cancelDebtMx.setDebtCount(account.getUnrecordedNumber()-account.getCancelNum());

                            BaseProject baseProject = new BaseProject();
                            baseProject.setId(account.getCourseProjectId());
                            BaseProject baseProject1 = ssmProjectService.selectOne(baseProject);
                            cancelDebtMx.setCourseProjectNum(baseProject1.getProjectNum());
                            cancelDebtMxes.add(cancelDebtMx);
                        }
                    }
                    debtListResponse.setCancelDebtMxes(cancelDebtMxes);
                }
                listResponses.add(debtListResponse);
            }

        }else{
            StoreParament parament = StoreParaUtils.getStorePara(storeid, Constant.refunSpan);
            if ("1".equals(parament.getParamentValue())) {//允许
                debtListRequest.setIds(objects);
                debtListRequest.setStoreId(null);

            }else{
                debtListRequest.setStoreId(debtListRequest.getStoreId());
            }

             pageInfo = dao.selectPage(debtListRequest);
            for (DebtList debtList : pageInfo.getList()) {
                StoreRequest storeRequest1 = new StoreRequest();
                storeRequest1.setId(debtList.getStoreId());
                BaseStore baseStore = ssmBaseStoreService.selectOne(storeRequest1);
                DebtListResponse debtListResponse = new DebtListResponse();
                debtListResponse.setStoreNum(baseStore.getStoreNum());
                BeanUtils.copyProperties(debtList,debtListResponse);
                //设置业务人员列表
                List<AchiCommEntity> entities = this.getAchiCommList(debtList);
                debtListResponse.setEntities(entities);

                if(debtListResponse.getDocType().equals("promotion_card_use")){
                    CourseAccount courseAccount = new CourseAccount();
                    courseAccount.setPromotionDocId(debtListResponse.getDocId());
                    List<CourseAccount> select = ssmCourseAccountService.select(courseAccount);
                    List<CancelDebtMx> cancelDebtMxes = new ArrayList<>();
                    for (CourseAccount account : select) {
                        if(account.getCourseType().equals("1")){
                            CancelDebtMx cancelDebtMx = new CancelDebtMx();
                            cancelDebtMx.setCourseId(account.getId());
                            cancelDebtMx.setCourseProjectId(account.getCourseProjectId());

                            cancelDebtMx.setCourseProjectName(account.getCourseProjectName());
                            cancelDebtMx.setDebtMoney(debtList.getDebtMoney().multiply(account.getPrice().multiply(BigDecimal.valueOf(account.getCourseRestCount())).divide(debtList.getTradeMoney(),4,BigDecimal.ROUND_HALF_UP))
                                    .subtract(account.getCancelMoney()));
                            cancelDebtMx.setDebtCount(account.getUnrecordedNumber()-account.getCancelNum());

                            BaseProject baseProject = new BaseProject();
                            baseProject.setId(account.getCourseProjectId());
                            BaseProject baseProject1 = ssmProjectService.selectOne(baseProject);
                            cancelDebtMx.setCourseProjectNum(baseProject1.getProjectNum());
                            cancelDebtMxes.add(cancelDebtMx);
                        }
                    }
                    debtListResponse.setCancelDebtMxes(cancelDebtMxes);
                }
                listResponses.add(debtListResponse);
            }
        }
        PageInfo<DebtListResponse> p =  new PageInfo<>(listResponses);
        p.setTotal(pageInfo.getTotal());
        return p;
    }
    @Override
    public PageInfo<DebtListResponse> selectPageNew(DebtListRequest debtListRequest) {
        List<DebtListResponse> listResponses = new ArrayList<>();

        List<Long> lists = new ArrayList<>();
        if(debtListRequest.getSelectType()==0){
            lists=debtListRequest.getStoreList();
        }else{
            BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(debtListRequest.getStoreId());
            if(null == baseStore1.getParentId()){
                StoreRequest storeRequest = new StoreRequest();
                storeRequest.setId(debtListRequest.getStoreId());
                List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
                List<Long> collect = pagesorganizations.stream().map(BaseStores::getId).collect(Collectors.toList());
                lists=collect;
            }else{
                lists.add(debtListRequest.getStoreId());
            }
        }
        debtListRequest.setStoreList(lists);
        PageInfo<DebtList> pageInfo = dao.selectPageNew(debtListRequest);
        for (DebtList debtList : pageInfo.getList()) {
            StoreRequest storeRequest1 = new StoreRequest();
            storeRequest1.setId(debtList.getStoreId());
            BaseStore baseStore = ssmBaseStoreService.selectOne(storeRequest1);
            DebtListResponse debtListResponse = new DebtListResponse();
            debtListResponse.setStoreNum(baseStore.getStoreNum());
            BeanUtils.copyProperties(debtList,debtListResponse);
            //设置业务人员列表
            List<AchiCommEntity> entities = this.getAchiCommList(debtList);
            debtListResponse.setEntities(entities);

            if(debtListResponse.getDocType().equals("promotion_card_use")){
                CourseAccount courseAccount = new CourseAccount();
                courseAccount.setPromotionDocId(debtListResponse.getDocId());
                List<CourseAccount> select = ssmCourseAccountService.select(courseAccount);
                List<CancelDebtMx> cancelDebtMxes = new ArrayList<>();
                for (CourseAccount account : select) {
                    if(account.getCourseType().equals("1")){
                        CancelDebtMx cancelDebtMx = new CancelDebtMx();
                        cancelDebtMx.setCourseId(account.getId());
                        cancelDebtMx.setCourseProjectId(account.getCourseProjectId());

                        cancelDebtMx.setCourseProjectName(account.getCourseProjectName());
                        cancelDebtMx.setDebtMoney(account.getUnrecordedAmount().subtract(account.getCancelMoney()));
                        cancelDebtMx.setDebtCount(account.getUnrecordedNumber()-account.getCancelNum());

                        BaseProject baseProject = new BaseProject();
                        baseProject.setId(account.getCourseProjectId());
                        BaseProject baseProject1 = ssmProjectService.selectOne(baseProject);
                        cancelDebtMx.setCourseProjectNum(baseProject1.getProjectNum());
                        cancelDebtMxes.add(cancelDebtMx);
                    }
                }
                debtListResponse.setCancelDebtMxes(cancelDebtMxes);
            }
            listResponses.add(debtListResponse);
        }
        PageInfo<DebtListResponse> p =  new PageInfo<>(listResponses);
        return p;
    }

    /*
     * 业务员列表设置返回值
     * */
    public List<AchiCommEntity> getAchiCommList(DebtList debtList){
        List<AchiCommEntity> entities = new ArrayList<>();
        if (null != debtList.getSaleOneStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setBrandNumber(debtList.getSaleOneNumber());
            achiCommEntity.setSaleStaffId(debtList.getSaleOneStaffId());
            achiCommEntity.setSaleStaffName(debtList.getSaleOneStaffName());
            achiCommEntity.setSaleIdentityCard(debtList.getSaleOneIdentity());
            achiCommEntity.setSaleRatio(debtList.getSaleOneRatio());
            entities.add(achiCommEntity);
        }
        if (null != debtList.getSaleTwoStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setBrandNumber(debtList.getSaleTwoNumber());
            achiCommEntity.setSaleStaffId(debtList.getSaleTwoStaffId());
            achiCommEntity.setSaleStaffName(debtList.getSaleTwoStaffName());
            achiCommEntity.setSaleIdentityCard(debtList.getSaleTwoIdentity());
            achiCommEntity.setSaleRatio(debtList.getSaleTwoRatio());
            entities.add(achiCommEntity);
        }
        if (null != debtList.getSaleThreeStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setBrandNumber(debtList.getSaleThreeNumber());
            achiCommEntity.setSaleStaffId(debtList.getSaleThreeStaffId());
            achiCommEntity.setSaleStaffName(debtList.getSaleThreeStaffName());
            achiCommEntity.setSaleIdentityCard(debtList.getSaleThreeIdentity());
            achiCommEntity.setSaleRatio(debtList.getSaleThreeRatio());
            entities.add(achiCommEntity);
        }
        if (null != debtList.getSaleFourStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setBrandNumber(debtList.getSaleFourNumber());
            achiCommEntity.setSaleStaffId(debtList.getSaleFourStaffId());
            achiCommEntity.setSaleStaffName(debtList.getSaleFourStaffName());
            achiCommEntity.setSaleIdentityCard(debtList.getSaleFourIdentity());
            achiCommEntity.setSaleRatio(debtList.getSaleFourRatio());
            entities.add(achiCommEntity);
        }
        if (null != debtList.getSaleFiveStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setBrandNumber(debtList.getSaleFiveNumber());
            achiCommEntity.setSaleStaffId(debtList.getSaleFiveStaffId());
            achiCommEntity.setSaleStaffName(debtList.getSaleFiveStaffName());
            achiCommEntity.setSaleIdentityCard(debtList.getSaleFiveIdentity());
            achiCommEntity.setSaleRatio(debtList.getSaleFiveRatio());
            entities.add(achiCommEntity);
        }
        if (null != debtList.getSaleSixStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setBrandNumber(debtList.getSaleSixNumber());
            achiCommEntity.setSaleStaffId(debtList.getSaleSixStaffId());
            achiCommEntity.setSaleStaffName(debtList.getSaleSixStaffName());
            achiCommEntity.setSaleIdentityCard(debtList.getSaleSixIdentity());
            achiCommEntity.setSaleRatio(debtList.getSaleSixRatio());
            entities.add(achiCommEntity);
        }
        if (null != debtList.getSaleSevenStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setBrandNumber(debtList.getSaleSevenNumber());
            achiCommEntity.setSaleStaffId(debtList.getSaleSevenStaffId());
            achiCommEntity.setSaleStaffName(debtList.getSaleSevenStaffName());
            achiCommEntity.setSaleIdentityCard(debtList.getSaleSevenIdentity());
            achiCommEntity.setSaleRatio(debtList.getSaleSevenRatio());
            entities.add(achiCommEntity);
        }
        if (null != debtList.getSaleEightStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setBrandNumber(debtList.getSaleEightNumber());
            achiCommEntity.setSaleStaffId(debtList.getSaleEightStaffId());
            achiCommEntity.setSaleStaffName(debtList.getSaleEightStaffName());
            achiCommEntity.setSaleIdentityCard(debtList.getSaleEightIdentity());
            achiCommEntity.setSaleRatio(debtList.getSaleEightRatio());
            entities.add(achiCommEntity);
        }
        return entities;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int addDebt(DebtListRequest debtListRequest) {
        DebtList debtList = new DebtList();
        BeanUtils.copyProperties(debtListRequest,debtList);
        debtList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        //设置业务员
        this.setStaffValue(debtListRequest.getStaffLists(),debtList);
        return dao.saveNotNull(debtList);
    }

    /*
     * 业务员赋值
     * */
    public void setStaffValue(List<StaffRequest> staffLists, DebtList debtList){

        for (int i = 0; i < staffLists.size(); i++) {
            StaffRequest staffRequest = staffLists.get(i);
            if (i == 0){
                debtList.setSaleOneStaffId(staffRequest.getId());
                debtList.setSaleOneStaffName(staffRequest.getStaffName());
                debtList.setSaleOneIdentity(staffRequest.getIdentityCard());
                debtList.setSaleOneRatio(staffRequest.getRatio());
                debtList.setSaleOneNumber(staffRequest.getBrandNumber());
            }else if (i == 1){
                debtList.setSaleTwoStaffId(staffRequest.getId());
                debtList.setSaleTwoStaffName(staffRequest.getStaffName());
                debtList.setSaleTwoIdentity(staffRequest.getIdentityCard());
                debtList.setSaleTwoRatio(staffRequest.getRatio());
                debtList.setSaleTwoNumber(staffRequest.getBrandNumber());
            }else if (i == 2){
                debtList.setSaleThreeStaffId(staffRequest.getId());
                debtList.setSaleThreeStaffName(staffRequest.getStaffName());
                debtList.setSaleThreeIdentity(staffRequest.getIdentityCard());
                debtList.setSaleThreeRatio(staffRequest.getRatio());
                debtList.setSaleThreeNumber(staffRequest.getBrandNumber());
            }else if(i==3){
                debtList.setSaleFourStaffId(staffRequest.getId());
                debtList.setSaleFourStaffName(staffRequest.getStaffName());
                debtList.setSaleFourIdentity(staffRequest.getIdentityCard());
                debtList.setSaleFourRatio(staffRequest.getRatio());
                debtList.setSaleFourNumber(staffRequest.getBrandNumber());
            }else if (i == 4){
                debtList.setSaleFiveStaffId(staffRequest.getId());
                debtList.setSaleFiveStaffName(staffRequest.getStaffName());
                debtList.setSaleFiveIdentity(staffRequest.getIdentityCard());
                debtList.setSaleFiveRatio(staffRequest.getRatio());
                debtList.setSaleFiveNumber(staffRequest.getBrandNumber());
            }else if (i == 5){
                debtList.setSaleSixStaffId(staffRequest.getId());
                debtList.setSaleSixStaffName(staffRequest.getStaffName());
                debtList.setSaleSixIdentity(staffRequest.getIdentityCard());
                debtList.setSaleSixRatio(staffRequest.getRatio());
                debtList.setSaleSixNumber(staffRequest.getBrandNumber());
            }else if (i == 6){
                debtList.setSaleSevenStaffId(staffRequest.getId());
                debtList.setSaleSevenStaffName(staffRequest.getStaffName());
                debtList.setSaleSevenIdentity(staffRequest.getIdentityCard());
                debtList.setSaleSevenRatio(staffRequest.getRatio());
                debtList.setSaleSevenNumber(staffRequest.getBrandNumber());
            }else if (i==7){
                debtList.setSaleEightStaffId(staffRequest.getId());
                debtList.setSaleEightStaffName(staffRequest.getStaffName());
                debtList.setSaleEightIdentity(staffRequest.getIdentityCard());
                debtList.setSaleEightRatio(staffRequest.getRatio());
                debtList.setSaleEightNumber(staffRequest.getBrandNumber());
            }
        }
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public int deleteDebt(DebtListRequest debtListRequest) {
        DebtList debtList = new DebtList();
        BeanUtils.copyProperties(debtListRequest, debtList);
        debtList = dao.selectOne(debtList);
        return dao.deleteByPrimaryKey(debtList.getId());
    }

    @Override
    public int insertBatch(List<DebtList> lists, Long storeId, String storeName) {
//        StaffResponse staffResponse = new StaffResponse();
//        if (redisClient.hasKey(getKey(phone))){
//            staffResponse = redisClient.get(getKey(phone));
//        }
        for (DebtList debtList : lists) {
            debtList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            debtList.setStoreId(storeId);
            debtList.setStoreName(storeName);
            debtList.setState(0);
        }
        return dao.insertBatch(lists);
    }

    @Override
    public List<DebtDayVo> selectByDay(List<Long> storeIds, Date startTime, Date endTime) {
        return dao.selectByDay(storeIds,startTime,endTime);
    }

    @Override
    public List<DebtList> selectList(DebtListRequest debtListRequest) {
        List<DebtList> pageInfo = dao.selectList(debtListRequest);
        return pageInfo;
    }

    @Override
    public List<DebtList> selectLists(DebtList debtListRequest) {
        List<DebtList> pageInfo = dao.selectLists(debtListRequest);
        return pageInfo;
    }

}
