package com.pj.project.tb_costomer;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pj.constants.RoleEnum;
import com.pj.project.tb_district.TbDistrict;
import com.pj.project.tb_district.TbDistrictService;
import com.pj.project.tb_init_permission.TbInitPermission;
import com.pj.project.tb_init_permission.TbInitPermissionService;
import com.pj.project4sp.SP;
import com.pj.project4sp.admin.SpAdmin;
import com.pj.project4sp.admin.SpAdminMapper;
import com.pj.project4sp.admin.SpAdminService;
import com.pj.project4sp.role.SpRole;
import com.pj.project4sp.role.SpRoleMapper;
import com.pj.project4sp.role4permission.SpRolePermissionMapper;
import com.pj.utils.so.SoMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.pj.utils.sg.*;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Service: tb_costomer -- 客户管理
 *
 * @author qzy
 */
@Service
@Transactional
public class TbCostomerService extends ServiceImpl<TbCostomerMapper, TbCostomer> implements IService<TbCostomer> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbCostomerMapper tbCostomerMapper;
    @Resource
    private SpRoleMapper spRoleMapper;
    @Resource
    private SpRolePermissionMapper spRolePermissionMapper;
    @Resource
    private TbInitPermissionService tbInitPermissionService;
    @Resource
    private SpAdminMapper spAdminMapper;
    @Resource
    private SpAdminService spAdminService;

    /**
     * 增
     */
    int add(TbCostomer t) {
        if (!validateName(t)) {
            throw new RuntimeException("该企业名称已存在");
        }
        t.setCreareTime(new Date()).setJudgeContent("平台创建，直接通过").setJudgeTime(new Date());
        this.save(t);
        SpRole spRole = new SpRole();
        spRole.setCustomerId(t.getId()).setInfo("企业/客户管理员")
                .setName("管理员").setType("customerAdmin");
        spRoleMapper.add(spRole);
        long roleId = SP.publicMapper.getPrimarykey();
        List<String>codeList=new ArrayList<>();
        for (String type : StrUtil.splitTrim(t.getType(), ",")) {
           SoMap perSoMap = SoMap.getRequestSoMap();
            perSoMap.put("type", type);
           List<TbInitPermission>permissions= tbInitPermissionService.getList(perSoMap);
           codeList.addAll(permissions.stream().map(TbInitPermission::getCode).distinct().collect(Collectors.toList()));
        }
        spRolePermissionMapper.saveRolePer(roleId, codeList);
        return 1;
    }

    private boolean validateName(TbCostomer t) {
        String costomerName = t.getName();
        TbCostomer db = this.findByName(costomerName);
        if (db == null) {
            return true;
        }
        return StrUtil.equals(db.getId(), t.getId());
    }

   public TbCostomer findByName(String name){
        QueryWrapper<TbCostomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        return this.getOne(queryWrapper);
    }

    /**
     * 删
     */
    int delete(String id) {
        this.removeById(id);
        SoMap soMap = SoMap.getRequestSoMap();
        soMap.put("customerId", id);
        List<SpRole> roles = spRoleMapper.getList(soMap);
        if (roles.isEmpty()){
            return 1;
        }
        spRoleMapper.removeByCustomerId(id);
        spRolePermissionMapper.removeByRoleIds(roles.stream().map(SpRole::getId).collect(Collectors.toList()));
        spAdminMapper.removeByCustomerId(id);
        return 1;
    }

    /**
     * 改
     */
    int update(TbCostomer t) {
        if (!validateName(t)) {
            throw new RuntimeException("名称已存在");
        }
        this.updateById(t);
        return 1;
    }



    /**
     * 查集合 - 根据条件（参数为空时代表忽略指定条件）
     */
    public List<TbCostomer> getList(SoMap so) {

        return tbCostomerMapper.getList(so);
    }


    public int updateStatus(String id, int value) {
        int line = SP.publicMapper.updateColumnById(TbCostomer.TABLE_NAME, "status", value, id);
        int status=value==1?1:2;
        spAdminMapper.updateCustomerAdmin(id,status);
        return line;
    }

    public void judge(String id, int status,String judgeContent) {
        TbCostomer costomer=  this.getById(id);
        costomer.setJudgeContent(judgeContent)
            .setJudgeStatus(status).setJudgeTime(new Date());
        this.updateById(costomer);

        //审核不通过禁用用户
        int isBan = status == 3 ? 2 : 1;//账号状态(1=正常, 2=禁用)
        List<SpAdmin> spAdminList = spAdminMapper.getByCostomerId(costomer.getId());
        for (SpAdmin spAdmin : spAdminList) {
            if(spAdmin != null) {
                spAdmin.setStatus(isBan);
                spAdminMapper.updateCustomerAdmin(costomer.getId(), isBan);
            }
        }
    }

    public void register(TbCostomer costomer) {
        costomer.setJudgeStatus(1).setStatus(1);
        this.add(costomer);

        //新增一个默认用户账号 账号：联系人/密码：手机号后六位
        SpAdmin spAdmin = new SpAdmin();
        spAdmin.setId(0L);
        spAdmin.setCustomerId(costomer.getId());
        spAdmin.setName(costomer.getDutyPeople());
        spAdmin.setPassword(costomer.getPhone().substring(costomer.getPhone().length()-6));
        SoMap so = new SoMap();
        so.put("customerId", costomer.getId());
        List<SpRole> roleList = spRoleMapper.getList(so);
        List<Long> roleIdList = roleList.stream().map(role -> role.getId()).collect(Collectors.toList());
        String roleId = roleIdList.stream().map(String::valueOf).collect(Collectors.joining(","));
        spAdmin.setRoleId(roleId);
        spAdminService.addWhenRegister(spAdmin);
        spAdminMapper.updateCustomerAdmin(costomer.getId(), 2);
    }

    public List<String> findByBusinessTypeOpenid(String businessType, String bigBusinessType) {
        return  tbCostomerMapper.findByBusinessTypeOpenid(businessType, bigBusinessType);

    }
}
