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.impl.ServiceImpl;
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.util.SecurityUtil;
import com.njzscloud.supervisory.biz.constant.AuditStatus;
import com.njzscloud.supervisory.biz.constant.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.biz.pojo.result.StationResult;
import com.njzscloud.supervisory.config.AppProperties;
import com.njzscloud.supervisory.sys.auth.pojo.result.MyResult;
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> {

    private final AppProperties appProperties;

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

    /**
     * 新增
     *
     * @param bizCompanyEntity 数据
     */
    public void addStation(BizCompanyEntity bizCompanyEntity) {
        bizCompanyEntity.setStation(true);
        this.save(bizCompanyEntity);
    }

    @Transactional(rollbackFor = Exception.class)
    public Long 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);
        return bizCompanyEntity.getId();
    }

    /**
     * 修改
     *
     * @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, "当前状态不能修改");
        } */
        AppProperties.DefaultPlace defaultPlace = appProperties.getDefaultPlace();

        BizCompanyEntity bizCompanyEntity = BeanUtil.copyProperties(modifyBizCompanyParam, BizCompanyEntity.class)
                .setAuditStatus(AuditStatus.DaiShenHe)
                .setProvince(defaultPlace.getProvince())
                .setCity(defaultPlace.getCity())
                .setProvinceName(defaultPlace.getProvinceName())
                .setAuditStatus(oldData.getAuditStatus() == AuditStatus.TongGuo ? AuditStatus.TongGuo : AuditStatus.DaiShenHe)
                .setAuditMemo("")
                .setCityName(defaultPlace.getCityName());
        this.updateById(bizCompanyEntity);
    }

    @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("当前状态不能撤销");
        } */
        update(Wrappers.<BizCompanyEntity>lambdaUpdate()
                        .set(BizCompanyEntity::getAuditStatus, AuditStatus.YiCheXiao)
                        .eq(BizCompanyEntity::getId, id)
                // .eq(BizCompanyEntity::getAuditStatus, AuditStatus.DaiShenHe)
        );
    }

    /**
     * 详情
     *
     * @param id Id
     * @return SearchCompanyResult 结果
     */
    public SearchCompanyResult detail(Long id) {
        MyResult userDetail = SecurityUtil.loginUser();
        Long userId = userDetail.getUserId();
        BizObj bizObj = userDetail.getBizObj();
        BizCompanyEntity bizCompanyEntity;
        if (bizObj == null) {
            // 使用联表查询获取企业信息和用户的bizObj
            bizCompanyEntity = baseMapper.selectDetailWithBizObj(id);
            if (bizCompanyEntity == null) {
                throw Exceptions.exception("企业信息不存在");
            }
            return BeanUtil.copyProperties(bizCompanyEntity, SearchCompanyResult.class);
        }
        switch (bizObj) {
            case ShiGongDanWei:
            case QingYunGongSi:
                bizCompanyEntity = this.getOne(Wrappers.<BizCompanyEntity>lambdaQuery().eq(BizCompanyEntity::getUserId, userId));
                if (bizCompanyEntity == null) {
                    throw Exceptions.exception("企业信息不存在");
                }
                id = bizCompanyEntity.getId();
                // 使用联表查询获取企业信息和用户的bizObj
                bizCompanyEntity = baseMapper.selectDetailWithBizObj(id);
                break;
            // case ZhengFuBuMen:
            //     bizCompanyEntity = baseMapper.selectDetailWithBizObj(id);
            //     break;
            default:
                throw Exceptions.exception("不允许查询");
        }
        if (bizCompanyEntity == null) {
            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(),
                    BizObj.QiTa.getVal());
        } else if (bizObj == BizObj.QingYunGongSi) {
            bizObjList = Arrays.asList(
                    BizObj.QiYe.getVal(),
                    BizObj.GeTi.getVal());
        }

        String uscc = searchCompanyParam.getUscc();
        AuditStatus auditStatus = searchCompanyParam.getAuditStatus();
        String aStatus = "";
        if (null != auditStatus) {
            aStatus = auditStatus.getVal();
        }
        String companyName = searchCompanyParam.getCompanyName();
        String stationName = searchCompanyParam.getStationName();
        String legalRepresentative = searchCompanyParam.getLegalRepresentative();
        Integer station = searchCompanyParam.getStation();
        Boolean enabled = searchCompanyParam.getEnabled();
        String area = searchCompanyParam.getArea();
        return PageResult.of(baseMapper.paging(pageParam.toPage(), Wrappers.query()
//                .eq("a.station", Boolean.FALSE)
                        .eq("a.deleted", 0)
                        .eq(StrUtil.isNotBlank(aStatus), "a.audit_status", aStatus)
                        .eq(station != null, "a.station", station)
                        .eq(enabled != null, "a.enabled", enabled)
                        .eq(StrUtil.isNotBlank(area), "a.area", area)
//                .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(stationName), "a.station_name", stationName)
                        .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<StationResult> station(Double lng, Double lat) {
        return baseMapper.station(lng, lat);
    }

    public void open(Long id, Boolean open) {
        update(Wrappers.<BizCompanyEntity>lambdaUpdate()
                .set(BizCompanyEntity::getOpen, open)
                .eq(BizCompanyEntity::getId, id));
    }

    public Boolean isOpen(Long id) {
        BizCompanyEntity company = getById(id);
        Assert.notNull(company, () -> Exceptions.clierr("数据不存在"));
        return company.getOpen();
    }
}
