package com.njzscloud.supervisory.biz.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import com.njzscloud.common.security.support.UserDetail;
import com.njzscloud.common.security.util.SecurityUtil;
import com.njzscloud.supervisory.biz.contant.AuditStatus;
import com.njzscloud.supervisory.biz.contant.BizObj;
import com.njzscloud.supervisory.biz.mapper.BizCompanyMapper;
import com.njzscloud.supervisory.biz.pojo.entity.BizCompanyEntity;
import com.njzscloud.supervisory.biz.pojo.param.AddBizCompanyParam;
import com.njzscloud.supervisory.biz.pojo.param.ModifyBizCompanyParam;
import com.njzscloud.supervisory.biz.pojo.param.SearchCompanyParam;
import com.njzscloud.supervisory.biz.pojo.result.SearchCompanyResult;
import com.njzscloud.supervisory.config.AppProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * 企业信息
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BizCompanyService extends ServiceImpl<BizCompanyMapper, BizCompanyEntity> implements IService<BizCompanyEntity> {

    private final AppProperties appProperties;

    /**
     * 新增
     *
     * @param bizCompanyEntity 数据
     */
    public void add(BizCompanyEntity bizCompanyEntity) {
        bizCompanyEntity.setAuditStatus(AuditStatus.DaiShenHe);
        this.save(bizCompanyEntity);
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(AddBizCompanyParam addBizCompanyParam) {
        AppProperties.DefaultPlace defaultPlace = appProperties.getDefaultPlace();
        BizCompanyEntity bizCompanyEntity = BeanUtil.copyProperties(addBizCompanyParam, BizCompanyEntity.class)
                .setAuditStatus(AuditStatus.DaiShenHe)
                .setProvince(defaultPlace.getProvince())
                .setCity(defaultPlace.getCity())
                .setProvinceName(defaultPlace.getProvinceName())
                .setCityName(defaultPlace.getCityName());
        this.save(bizCompanyEntity);
    }

    /**
     * 修改
     *
     * @param modifyBizCompanyParam 数据
     */
    public void modify(ModifyBizCompanyParam modifyBizCompanyParam) {
        Long id = modifyBizCompanyParam.getId();
        BizCompanyEntity oldData = getById(id);
        if (oldData == null) {
            throw Exceptions.exception("未找到要修改的数据");
        }
        /* if (oldData.getAuditStatus() != AuditStatus.YiCheXiao) {
            throw Exceptions.create(CompanyExceptionMsg.COMPANY_MODIFY_ERROR, "当前状态不能修改");
        } */
        BizCompanyEntity bizCompanyEntity = BeanUtil.copyProperties(modifyBizCompanyParam, BizCompanyEntity.class)
                .setAuditStatus(AuditStatus.DaiShenHe);
        this.updateById(bizCompanyEntity);
        BizObj bizObj = modifyBizCompanyParam.getBizObj();

        Long userId = oldData.getUserId();
        Long companyId = oldData.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    public void cancel(Long id) {
        BizCompanyEntity oldData = getById(id);
        if (oldData == null) {
            throw Exceptions.exception("未找到要撤销的数据");
        }
        /* if (oldData.getAuditStatus() != AuditStatus.DaiShenHe) {
            throw Exceptions.exception("当前状态不能撤销");
        } */
        boolean updated = update(Wrappers.<BizCompanyEntity>lambdaUpdate()
                        .set(BizCompanyEntity::getAuditStatus, AuditStatus.YiCheXiao)
                        .eq(BizCompanyEntity::getId, id)
                // .eq(BizCompanyEntity::getAuditStatus, AuditStatus.DaiShenHe)
        );
      /*   if (!updated) {
            throw Exceptions.exception("数据状态已改变，无法撤销");
        } */
    }

    /**
     * 详情
     *
     * @param id Id
     * @return BizCompanyEntity 结果
     */
    public SearchCompanyResult detail(Long id) {
        UserDetail userDetail = SecurityUtil.loginUser();
        Long userId = userDetail.getUserId();
        String bizObjValue = userDetail.getBizObj();
        BizCompanyEntity bizCompanyEntity;
        if (Strings.isNullOrEmpty(bizObjValue)) {
            bizCompanyEntity = this.getById(id);
            return BeanUtil.copyProperties(bizCompanyEntity, SearchCompanyResult.class);
        }
        BizObj bizObj = BizObj.valueOf(bizObjValue);
        switch (bizObj) {
            case ShiGongDanWei:
            case QingYunGongSi:
            case XiaoNaCang:
                bizCompanyEntity = this.getOne(Wrappers.<BizCompanyEntity>lambdaQuery().eq(BizCompanyEntity::getUserId, userId));
                id = bizCompanyEntity.getId();
                break;
            case ZhengFuBuMen:
                bizCompanyEntity = this.getById(id);
                break;
            default:
                throw Exceptions.exception("不允许查询");
        }
        return BeanUtil.copyProperties(bizCompanyEntity, SearchCompanyResult.class);
    }

    /**
     * 分页查询
     *
     * @param pageParam          分页参数
     * @param searchCompanyParam 筛选条件
     * @return PageResult&lt;BizCompanyEntity&gt; 分页结果
     */
    public PageResult<BizCompanyEntity> paging(PageParam pageParam, SearchCompanyParam searchCompanyParam) {
        BizObj bizObj = searchCompanyParam.getBizObj();
        List<String> bizObjList = null;

        if (bizObj == BizObj.ChanFeiDanWei) {
            bizObjList = Arrays.asList(BizObj.GeRen.getVal(),
                    BizObj.WuYe.getVal(),
                    BizObj.ShiGongDanWei.getVal(),
                    BizObj.ChaiQian.getVal(),
                    BizObj.SheQu.getVal());
        } else if (bizObj == BizObj.QingYunGongSi) {
            bizObjList = Arrays.asList(
                    BizObj.QiYe.getVal(),
                    BizObj.GeTi.getVal());
        }

        String uscc = searchCompanyParam.getUscc();
        AuditStatus auditStatus = searchCompanyParam.getAuditStatus();
        String companyName = searchCompanyParam.getCompanyName();
        String legalRepresentative = searchCompanyParam.getLegalRepresentative();
        return PageResult.of(baseMapper.paging(pageParam.toPage(), Wrappers.query()
                .eq(auditStatus != null, "a.audit_status", auditStatus)
                .eq(StrUtil.isNotBlank(searchCompanyParam.getStation()), "a.station", searchCompanyParam.getStation())
                .in(CollUtil.isNotEmpty(bizObjList), "b.biz_obj", bizObjList)
                .like(StrUtil.isNotBlank(companyName), "a.company_name", companyName)
                .like(StrUtil.isNotBlank(legalRepresentative), "a.legal_representative", legalRepresentative)
                .like(StrUtil.isNotBlank(uscc), "a.uscc", uscc)
        ));
    }

    @Transactional(rollbackFor = Exception.class)
    public void audit(Long id, AuditStatus auditStatus, String auditMemo) {
        Assert.isTrue(auditStatus == AuditStatus.TongGuo || auditStatus == AuditStatus.BoHui, "错误的审核状态");
        BizCompanyEntity oldData = getById(id);
        if (oldData == null) {
            throw Exceptions.exception("未找到要审核的数据");
        }
        if (oldData.getAuditStatus() != AuditStatus.DaiShenHe) {
            throw Exceptions.exception("当前状态不能审核");
        }
        boolean updated = update(Wrappers.<BizCompanyEntity>lambdaUpdate()
                .set(BizCompanyEntity::getAuditStatus, auditStatus)
                .set(BizCompanyEntity::getAuditMemo, auditStatus == AuditStatus.TongGuo ? "" : auditMemo)
                .eq(BizCompanyEntity::getId, id)
                .eq(BizCompanyEntity::getAuditStatus, AuditStatus.DaiShenHe));
        if (!updated) {
            throw Exceptions.exception("数据状态已改变，无法审核");
        }
    }

    public List<BizCompanyEntity> station() {
        return this.list(Wrappers.<BizCompanyEntity>lambdaQuery().eq(BizCompanyEntity::getStation, Boolean.TRUE));
    }
}
