package com.ruoyi.demo.service.impl;

import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.demo.entity.App;
import com.ruoyi.demo.entity.Commercial;
import com.ruoyi.demo.entity.Plan;
import com.ruoyi.demo.entity.bo.CommercialBo;
import com.ruoyi.demo.entity.vo.CommercialVo;
import com.ruoyi.demo.mapper.AppMapper;
import com.ruoyi.demo.mapper.CommercialMapper;
import com.ruoyi.demo.mapper.PlanMapper;
import com.ruoyi.demo.service.CommericalService;
import com.ruoyi.demo.utils.InitMapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotBlank;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class CommercialServiceImpl implements CommericalService {
    @Autowired
    CommercialMapper commercialMapper;

    @Autowired
    InitMapUtil initMapUtil;

    @Autowired
    AppMapper appMapper;

    @Autowired
    PlanMapper planMapper;
    @Override
    public void addCommercial(CommercialVo commercialVo) {
        Commercial commercial = new Commercial(commercialVo);
        commercial.setCreateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        commercial.setAddrCodeInfo(initMapUtil.getInitAddrCodeMap(commercial.getAddrCode()));
        commercialMapper.insert(commercial);
    }

    @Override
    public String deleteCommercial(String[] commercialIds) {
        //1.判断旗下是否有小程序
        QueryWrapper<App> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("commercial_id",commercialIds);
        Long aLong = appMapper.selectCount(queryWrapper);
        if (aLong != 0L)
            return "待删除的商户中存在App";
        commercialMapper.deleteBatchIds(Arrays.asList(commercialIds));
        return "删除成功";
    }

    @Override
    public Commercial getCommercial(String commercialId) {
        return commercialMapper.selectById(commercialId);
    }

    @Override
    public HashMap getCommercialList(CommercialVo commercialVo) {
        QueryWrapper<Commercial> queryWrapper = new QueryWrapper<>();
        if(commercialVo.getSearchText() != null && !commercialVo.getSearchText().equals("")){
            queryWrapper.likeRight("commercial_id",commercialVo.getSearchText());
            queryWrapper.or().like("commercial_name",commercialVo.getSearchText());
            queryWrapper.or().like("principal_name",commercialVo.getSearchText());
            queryWrapper.or().likeRight("principal_telephone",commercialVo.getSearchText());
        }

        Page<Commercial> page = new Page<>();
        page.setCurrent(commercialVo.getPageNum());
        page.setSize(commercialVo.getPageSize());
        Page<Commercial> commercialPage = commercialMapper.selectPage(page, queryWrapper);

        //1.找到需要关联的小程序
        ArrayList<String> commercialIds = new ArrayList<>();
        List<CommercialBo> result = new ArrayList<>();
        for (Commercial commercial : commercialPage.getRecords()) {
            commercialIds.add(commercial.getCommercialId());
            CommercialBo commercialBo = new CommercialBo(commercial);
            commercialBo.setApps(new ArrayList<>());
            result.add(commercialBo);
        }

        if (!commercialIds.isEmpty()){
            QueryWrapper<App> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.select("commercial_id","app_name");
            queryWrapper1.in("commercial_id",commercialIds);
            List<App> apps = appMapper.selectList(queryWrapper1);
            //2.组装Bo
            for (CommercialBo commercialBo : result) {
                ArrayList<String> list = new ArrayList<>();
                apps.stream().forEach(item -> {
                    if(item.getCommercialId().equals(commercialBo.getCommercialId()))
                        list.add(item.getAppName());
                });
                commercialBo.setApps(list);
            }
        }
        commercialPage.setRecords(null);
        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("page",commercialPage);
        objectObjectHashMap.put("data",result);
        return objectObjectHashMap;
    }

    @Override
    public List<Commercial>  getCommercialName() {
        QueryWrapper<Commercial> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("commercial_name","commercial_id");
        List<Commercial> commercials = commercialMapper.selectList(queryWrapper);
        return commercials;
    }

    @Override
    public R updateCommercial(CommercialVo commercialVo) {
        QueryWrapper<Commercial> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("state","commercial_name");
        queryWrapper.eq("commercial_id",commercialVo.getCommercialId());
        Commercial commercial = commercialMapper.selectOne(queryWrapper);
        if (commercial != null){
            //1.判断是否修改商户状态
            if (commercialVo.getState() != commercial.getState()){
                if (commercialVo.getState() == 0){
                    //1.修改app状态 ——> 关闭
                    UpdateWrapper<App> updateWrapper1 = new UpdateWrapper<>();
                    updateWrapper1.eq("commercial_id",commercialVo.getCommercialId());
                    updateWrapper1.set("state",0);
                    appMapper.update(null,updateWrapper1);

                    //2.下架所有广告
                    UpdateWrapper<Plan> updateWrapper2 = new UpdateWrapper<>();
                    updateWrapper2.eq("commercial_id",commercialVo.getCommercialId());
                    updateWrapper2.set("on_state",0);
                    planMapper.update(null,updateWrapper2);
                }else {
                    //1.修改app状态 ——> 启动
                    UpdateWrapper<App> updateWrapper1 = new UpdateWrapper<>();
                    updateWrapper1.eq("commercial_id",commercialVo.getCommercialId());
                    updateWrapper1.set("state",1);
                    appMapper.update(null,updateWrapper1);
                }
            }

            //2.修改商户
            UpdateWrapper<Commercial> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("commercial_id",commercialVo.getCommercialId())
                .set("commercial_name",commercialVo.getCommercialName())
                .set("code",commercialVo.getCode())
                .set("principal_name",commercialVo.getPrincipalName())
                .set("state",commercialVo.getState())
                .set("principal_telephone",commercialVo.getPrincipalTelephone())
                .set("prove_1",commercialVo.getProve1())
                .set("prove_2",commercialVo.getProve2())
                .set("prove_3",commercialVo.getProve3())
                .set("prove_4",commercialVo.getProve4())
                .set("prove_5",commercialVo.getProve5())
                .set("addr_code",commercialVo.getAddrCode())
                .set("addr_code_info",initMapUtil.getInitAddrCodeMap(commercialVo.getAddrCode()))
                .set("addr_info",commercialVo.getAddrInfo());
            commercialMapper.update(null,updateWrapper);

            //3.修改冗余字段中的商户名字
            if (!commercialVo.getCommercialName().equals(commercial.getCommercialName())){
                UpdateWrapper<App> updateWrapper1 = new UpdateWrapper<>();
                updateWrapper1.eq("commercial_id",commercialVo.getCommercialId())
                    .set("commercial_name",commercialVo.getCommercialName());
                appMapper.update(null,updateWrapper1);

                UpdateWrapper<Plan> updateWrapper2 = new UpdateWrapper<>();
                updateWrapper2.eq("commercial_id",commercialVo.getCommercialId())
                    .set("commercial_name",commercialVo.getCommercialName());
                planMapper.update(null,updateWrapper2);
            }
            return R.ok("修改成功");
        }else {
            return R.fail("不存在该小程序");
        }
    }
}
