package com.pj.project.tb_costomer;

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.TbDistrictService;
import com.pj.project4sp.SP;
import com.pj.project4sp.admin.SpAdmin;
import com.pj.project4sp.admin.SpAdminMapper;
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 javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

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

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbCostomerMapper tbCostomerMapper;
    @Resource
    private SpRoleMapper spRoleMapper;
    @Resource
    private SpRolePermissionMapper spRolePermissionMapper;
    @Resource
    private TbDistrictService tbDistrictService;
    @Resource
    private SpAdminMapper spAdminMapper;

    /**
     * 增
     */
    int add(TbCostomer t) {
        if (!validateName(t)) {
            throw new RuntimeException("该企业名称已存在");
        }
        t.setCreareTime(new Date()).setJudgeContent("平台创建，直接通过").setJudgeTime(new Date());
        this.save(t);
        List<RoleEnum> roleEnums = RoleEnum.getCustomerInitRoleList();
        List<String>commonPer=RoleEnum.COMMON_ROLE_PER.getPerCode();
        roleEnums.forEach(roleEnum -> {
            SpRole spRole = new SpRole();
            spRole.setCustomerId(t.getId()).setInfo(roleEnum.getName())
                    .setName(roleEnum.getName()).setType(roleEnum.getType());
            spRoleMapper.add(spRole);
            long roleId = SP.publicMapper.getPrimarykey();
            spRolePermissionMapper.saveRolePer(roleId, roleEnum.getPerCode());
            spRolePermissionMapper.saveRolePer(roleId,commonPer);
        });
        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());
    }

    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=禁用)
        SpAdmin spAdmin = spAdminMapper.getByCostomerId(costomer.getId());
        if(spAdmin != null) {
            spAdmin.setStatus(isBan);
            spAdminMapper.updateCustomerAdmin(costomer.getId(), isBan);
        }

    }

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