package com.gree.mall.manager.logic.activity;

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.gree.mall.manager.bean.ExcelData;
import com.gree.mall.manager.bean.activity.PromotionApplyBean;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.enums.UserTypeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PromotionApplyLogic {

    @Autowired
    PromotionApplyService promotionApplyService;
    @Autowired
    AdminWebsitService adminWebsitService;
    @Autowired
    EnterpriseWechatWorkerService enterpriseWechatWorkerService;
    @Autowired
    UserService userService;
    @Autowired
    CommonLogic commonLogic;

    public IPage<PromotionApplyBean> list(String nickName,String websitName,Integer pageNum,Integer pageSize){
        AdminUserCom adminUser =commonLogic.getAdminUser();

        List<AdminWebsit> list = new ArrayList<>();
//        List<AdminWebsit> list = adminWebsitService.lambdaQuery()
//                .like(AdminWebsit::getName, websitName).eq(AdminWebsit::getCorpId,adminUser.getCorpId()).list();
        List<String> websitIds = list.stream().map(AdminWebsit::getWebsitId).collect(Collectors.toList());

        IPage page = promotionApplyService.lambdaQuery()
                .in(CollectionUtils.isNotEmpty(websitIds), PromotionApply::getWebsitId, websitIds)
                .and(StringUtils.isNotEmpty(nickName), v -> v.like(PromotionApply::getWorkerName, nickName).or().like(PromotionApply::getMobile, nickName))
                .orderByDesc(PromotionApply::getCreateTime)
                .page(new Page<>(pageNum, pageSize));

        List<PromotionApplyBean> datas = new ArrayList<>();
        for(Object o : page.getRecords() ){
            PromotionApply promotionApply = (PromotionApply)o;
            PromotionApplyBean promotionApplyBean = new PromotionApplyBean();
            BeanUtils.copyProperties(promotionApply,promotionApplyBean);

//            AdminWebsit one = adminWebsitService.lambdaQuery().eq(AdminWebsit::getCorpId, adminUser.getCorpId())
//                    .eq(AdminWebsit::getWebsitId, promotionApply.getWebsitId()).one();
//            if(one != null) {
//                promotionApplyBean.setAdminWebsitName(one.getName());
//            }
            datas.add(promotionApplyBean);
        }
        page.setRecords(datas);
        return page;
    }


    public void save(String id,String userId, BigDecimal rate,Boolean status){
        AdminUserCom adminUser = commonLogic.getAdminUser();

        User user = userService.getById(userId);
        if(user == null){
            throw new RemoteServiceException("用户不存在");
        }
        if(rate.doubleValue() <= 0 || rate.doubleValue() >= 1){
            throw new RemoteServiceException("请填写大于0小于1的值");
        }
        Integer count = promotionApplyService.lambdaQuery().ne(StringUtils.isNotEmpty(id),PromotionApply::getId,id)
                .eq(PromotionApply::getUserId, userId).eq(PromotionApply::getStatus,true).count();
        if(count > 0){
            throw new RemoteServiceException("不可给同1个业务员添加多个配置");
        }
//        EnterpriseWechatWorker enterpriseWechatWorker = enterpriseWechatWorkerService.lambdaQuery()
//                .eq(EnterpriseWechatWorker::getWechatUserId, user.getWorkUserId())
//                .eq(EnterpriseWechatWorker::getCorpId,adminUser.getCorpId()).one();

        PromotionApply promotionApply = new PromotionApply();
        promotionApply.setId(id);
        promotionApply.setCompanyId(user.getCompanyId());
        promotionApply.setCompanyName(user.getCompanyName());
        promotionApply.setUserId(user.getUserId());
        promotionApply.setWorkerName(user.getWorkName());
        promotionApply.setMobile(user.getMobile());
        promotionApply.setType(user.getType());
//        if(enterpriseWechatWorker != null) {
//            promotionApply.setWebsitId(Long.parseLong(enterpriseWechatWorker.getMainDepartment()));
//        }
        promotionApply.setStatus(status);
        promotionApply.setRate(rate);
        promotionApply.setCreateTime(new Date());
        promotionApply.setCreateBy(adminUser.getNickName());
        promotionApply.setUpdateTime(new Date());
        promotionApply.setUpdateBy(adminUser.getNickName());
        promotionApply.insertOrUpdate();
    }

    public void delete(String id){
        promotionApplyService.removeById(id);
    }

    public PromotionApplyBean detail(String id){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        PromotionApply promotionApply = promotionApplyService.getById(id);
        PromotionApplyBean bean = new PromotionApplyBean();
        BeanUtils.copyProperties(promotionApply,bean);
//        AdminWebsit one = adminWebsitService.lambdaQuery().eq(AdminWebsit::getCorpId, adminUser.getCorpId())
//                .eq(AdminWebsit::getWebsitId, promotionApply.getWebsitId()).one();
//        if(one != null) {
//            bean.setAdminWebsitName(one.getName());
//        }
        return bean;
    }

    public ExcelData export(List<PromotionApplyBean> list){
        String[] titles = new String[]{"昵称","电话","角色","所属网点","可优惠价格折扣","状态","创建人","创建时间","更新人","更新时间"};

        List<List<Object>> rows = new ArrayList<>();
        for(PromotionApplyBean bean : list){
            List<Object> row = new ArrayList<>();
            row.add(bean.getWorkerName());
            row.add(bean.getMobile());
            row.add(UserTypeEnum.valueOf(bean.getType()).getName());
            row.add(bean.getAdminWebsitName());
            row.add(bean.getRate().multiply(BigDecimal.valueOf(10)));
            row.add(bean.getStatus()?"启用":"禁用");
            row.add(bean.getCreateBy());
            row.add(DateUtils.formatDate(bean.getCreateTime()));
            row.add(bean.getUpdateBy());
            row.add(DateUtils.formatDate(bean.getUpdateTime()));
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setTitles(Arrays.asList(titles));
        excelData.setRows(rows);
        return excelData;
    }

}
