package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.PolicyMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ObjectUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.system.domain.SettledMerchantsInterests;
import com.ruoyi.system.mapper.PolicyMenuMapper;
import com.ruoyi.system.mapper.SettledMerchantsInterestsMapper;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SettledMerchantsMapper;
import com.ruoyi.system.domain.SettledMerchants;
import com.ruoyi.system.service.ISettledMerchantsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入驻商家Service业务层处理
 * 
 * @author boman
 * @date 2022-06-10
 */
@Service
public class SettledMerchantsServiceImpl implements ISettledMerchantsService 
{
    @Autowired
    private SettledMerchantsMapper settledMerchantsMapper;
    @Autowired
    private SettledMerchantsInterestsMapper settledMerchantsInterestsMapper;
    @Autowired
    private PolicyMenuMapper policyMenuMapper;
    @Autowired
    private ISysUserService userService;

    /**
     * 查询入驻商家
     * 
     * @param businessId 入驻商家主键
     * @return 入驻商家
     */
    @Override
    public SettledMerchants selectSettledMerchantsByBusinessId(Long businessId)
    {
        SettledMerchants settledMerchants = settledMerchantsMapper.selectSettledMerchantsByBusinessId(businessId);
        List<Long> menuIdList = ObjectUtils.map(settledMerchants.getSettledMerchantsInterestsList(), SettledMerchantsInterests::getMenuId);
        settledMerchants.setMenuIdList(menuIdList);
        return settledMerchants;
    }

    /**
     * 根据政策类别获取入驻商家详细信息
     * @param menuId
     * @return
     */
    @Override
    public List<SettledMerchants> selectSettledMerchantsByMenuId(Long menuId) {

        List<SettledMerchants> settledMerchantsList = settledMerchantsMapper.selectSettledMerchantsByMenuId(menuId);
        //拼接政策类别
        for (SettledMerchants settledMerchants : settledMerchantsList) {
            StringBuilder sb = new StringBuilder();
            for (int i=0;i<settledMerchants.getSettledMerchantsInterestsList().size();i++) {
                if(i==0){
                    sb.append(settledMerchants.getSettledMerchantsInterestsList().get(i).getMenuName());
                }else{
                    sb.append(",").append(settledMerchants.getSettledMerchantsInterestsList().get(i).getMenuName());
                }
            }
            settledMerchants.setMenuNames(sb.toString());
        }
        return settledMerchantsList;
    }

    /**
     * 查询入驻商家列表
     * 
     * @param settledMerchants 入驻商家
     * @return 入驻商家
     */
    @Override
    public List<SettledMerchants> selectSettledMerchantsList(SettledMerchants settledMerchants)
    {

        startPage();
        List<SettledMerchants> settledMerchantsList = settledMerchantsMapper.selectSettledMerchantsList(settledMerchants);
        //拼接政策类别
        for (SettledMerchants settledMerchant : settledMerchantsList) {
            StringBuilder sb = new StringBuilder();
            for (int i=0;i<settledMerchant.getSettledMerchantsInterestsList().size();i++) {
                if(i==0){
                    sb.append(settledMerchant.getSettledMerchantsInterestsList().get(i).getMenuName());
                }else{
                    sb.append(",").append(settledMerchant.getSettledMerchantsInterestsList().get(i).getMenuName());
                }
            }
            settledMerchants.setMenuNames(sb.toString());
        }
        return settledMerchantsList;
    }

    /**
     * 新增入驻商家
     * 
     * @param settledMerchants 入驻商家
     * @return 结果
     */
    @Override
    public AjaxResult insertSettledMerchants(SettledMerchants settledMerchants)
    {

        //List<SettledMerchantsInterests> settledMerchantsInterestsList = settledMerchants.getSettledMerchantsInterestsList();
        //查询政策类别上一级
        PolicyMenu policyMenub = policyMenuMapper.selectPolicyMenuByMenuId(settledMerchants.getMenuIdList().get(0));
        PolicyMenu policyMenup = policyMenuMapper.selectPolicyMenuByMenuId(policyMenub.getParentId());
        if(policyMenup == null){
            settledMerchants.setPolicyId(Math.toIntExact(policyMenub.getMenuId()));
        }else{
            settledMerchants.setPolicyId(Math.toIntExact(policyMenup.getMenuId()));
        }
        settledMerchants.setCreateTime(DateUtils.getNowDate());
        int count = settledMerchantsMapper.insertSettledMerchants(settledMerchants);
        if (count < 1) return AjaxResult.error("新增失败");
        int childCount = 0;
        for (Long aLong : settledMerchants.getMenuIdList()) {
            //通过id查询类别名称
            PolicyMenu policyMenu = policyMenuMapper.selectPolicyMenuByMenuId(aLong);
            SettledMerchantsInterests settledMerchantsInterests = new SettledMerchantsInterests();
            settledMerchantsInterests.setBusinessId(settledMerchants.getBusinessId());
            settledMerchantsInterests.setMenuId(policyMenu.getMenuId());
            settledMerchantsInterests.setMenuName(policyMenu.getMenuName());
            childCount +=  settledMerchantsInterestsMapper.insertSettledMerchantsInterests(settledMerchantsInterests);
        }

        if(childCount > 0){
            //将入驻商家生成账号
            SysUser user = new SysUser();
            user.setUserName(settledMerchants.getBusinessPhone());
            user.setNickName(settledMerchants.getBusinessName());
            user.setPhonenumber(settledMerchants.getBusinessPhone());
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            userService.insertUser(user);

        }

        return childCount > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 修改入驻商家
     * 
     * @param settledMerchants 入驻商家
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSettledMerchants(SettledMerchants settledMerchants)
    {
        //先删除商户-政策类型表

        settledMerchantsInterestsMapper.delectByBusinessId(settledMerchants.getBusinessId());

        for (Long aLong : settledMerchants.getMenuIdList()) {
            //通过id查询类别名称
            PolicyMenu policyMenu = policyMenuMapper.selectPolicyMenuByMenuId(aLong);
            SettledMerchantsInterests settledMerchantsInterests = new SettledMerchantsInterests();
            settledMerchantsInterests.setBusinessId(settledMerchants.getBusinessId());
            settledMerchantsInterests.setMenuId(policyMenu.getMenuId());
            settledMerchantsInterests.setMenuName(policyMenu.getMenuName());
            settledMerchantsInterestsMapper.insertSettledMerchantsInterests(settledMerchantsInterests);
        }

        settledMerchants.setUpdateTime(DateUtils.getNowDate());
        return settledMerchantsMapper.updateSettledMerchants(settledMerchants);
    }

    /**
     * 批量删除入驻商家
     * 
     * @param businessIds 需要删除的入驻商家主键
     * @return 结果
     */
    @Override
    public int deleteSettledMerchantsByBusinessIds(Long[] businessIds)
    {
        return settledMerchantsMapper.deleteSettledMerchantsByBusinessIds(businessIds);
    }

    /**
     * 删除入驻商家信息
     * 
     * @param businessId 入驻商家主键
     * @return 结果
     */
    @Override
    public int deleteSettledMerchantsByBusinessId(Long businessId)
    {
        return settledMerchantsMapper.deleteSettledMerchantsByBusinessId(businessId);
    }

    @Override
    public SettledMerchants selectByPhone(String businessPhone) {
        return settledMerchantsMapper.selectByPhone(businessPhone);
    }

    private void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }
}
