package com.yeejoin.amos.boot.module.common.biz.service.impl;

import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.constants.BizConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.annotation.Condition;
import org.typroject.tyboot.core.rdbms.annotation.Operator;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.yeejoin.amos.boot.biz.common.utils.MenuFrom;
import com.yeejoin.amos.boot.biz.common.utils.TreeParser;
import com.yeejoin.amos.boot.module.common.api.dto.FireStationDto;
import com.yeejoin.amos.boot.module.common.api.dto.FireStationzhDto;
import com.yeejoin.amos.boot.module.common.api.dto.RequestData;
import com.yeejoin.amos.boot.module.common.api.entity.FireStation;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.api.mapper.FireStationMapper;
import com.yeejoin.amos.boot.module.common.api.mapper.OrgUsrMapper;
import com.yeejoin.amos.boot.module.common.api.service.IFireStationService;

/**
 * 微型消防站服务实现类
 *
 * @author system_generator
 * @date 2021-06-28
 */
@Service
public class FireStationServiceImpl extends BaseService<FireStationDto, FireStation, FireStationMapper>
        implements IFireStationService {


    @Autowired
    FireStationMapper fireStationMapper;
    @Autowired
    OrgUsrMapper orgUsrMapper;
    @Autowired
    OrgUsrServiceImpl orgUsrService;
    /**
     * 分页查询
     */
    public Page<FireStationDto> queryForFireStationPage(Page<FireStationDto> page) {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询 示例
     */
    public List<FireStationDto> queryForFireStationList(@Condition(Operator.eq) Boolean isDelete,@Condition(Operator.eq) Long bizCompanyId,@Condition(Operator.like) String name) {
        return this.queryForList("", false, isDelete,bizCompanyId,name);
    }

    /**
     * 删除
     */
    public Boolean updateisDelete(Long sequenceNbr) {

        return this.update(new UpdateWrapper<FireStation>().eq("sequence_nbr", sequenceNbr).set("is_delete", 1));
    }

    @Override
    public Page<FireStationDto> getFirefighters(int pageNum, int pageSize, FireStationDto par) {
        List<FireStationDto> list = fireStationMapper.getFireStation((pageNum - 1) * pageSize, pageSize, par);
        Map<String, Long> num = fireStationMapper.getFireStationCount(par);
        Page<FireStationDto> pageBean = new Page<>(pageNum, pageSize, num.get("num"));
        return pageBean.setRecords(list);
    }

    @Override
    public List<FireStationzhDto> getStationList(Integer pageNum, Integer pageSize, RequestData requestData) {
        if (null == pageNum || null == pageSize) {
            pageNum = 1;
            pageSize = Integer.MAX_VALUE;
        }else{
            pageNum=(pageNum - 1) * pageSize;
        }
        return fireStationMapper.getStationList(pageNum,pageSize,requestData);
    }

    @Override
    public Integer getStationListCount(RequestData requestData) {
        return fireStationMapper.getStationListCount(requestData);
    }

    @Override
    public FireStationDto selectBySequenceNbr(Long id) {
        return fireStationMapper.getFireStationDetails(id);
    }


    /**
     * 新增
     ***/
    public FireStationDto add(FireStationDto model) {
        /*bug 3072 微型消防站，新增页面多次点击保存报主键重复错误 2021-10-13 chenzhao */
        if (model.getSequenceNbr() != null){
            Update(model);
        }
        /*bug 3072 微型消防站，新增页面多次点击保存报主键重复错误 2021-10-13 chenzhao */

        if (model.getBizCompanyId() != null) {
            OrgUsr orgUsr = orgUsrMapper.selectById(model.getBizCompanyId());
            model.setBizCompany(orgUsr.getBizOrgName());
            model.setBizCompanyCode(orgUsr.getBizOrgCode());

            // 地址处理
            if (model.getAddress() != null) {
                JSONObject address = WaterResourceServiceImpl.getLongLatFromAddress(model.getAddress());
                model.setAddress(address.getString(BizConstant.ADDRESS));
                if(!"0".equals(address.getString(BizConstant.LONGITUDE))) {
                    model.setLongitude(Double.valueOf(address.getString(BizConstant.LONGITUDE)));
                }
                if(!"0".equals(address.getString(BizConstant.LATITUDE))) {
                    model.setLongitude(Double.valueOf(address.getString(BizConstant.LATITUDE)));
                }
            }
        }
        FireStation entity = this.prepareEntity(model);
        this.save(entity);
        return Bean.toModel(entity, model);
    }

    /**
     * 修改
     ***/
    public FireStationDto Update(FireStationDto model) {
        if (model.getBizCompanyId() != null) {
            OrgUsr orgUsr = orgUsrMapper.selectById(model.getBizCompanyId());
            model.setBizCompany(orgUsr.getBizOrgName());
            model.setBizCompanyCode(orgUsr.getBizOrgCode());
        }

        // 地址处理
        if (model.getAddress() != null) {
            JSONObject address = WaterResourceServiceImpl.getLongLatFromAddress(model.getAddress());
            model.setAddress(address.getString(BizConstant.ADDRESS));
            if(!"0".equals(address.getString(BizConstant.LONGITUDE))) {
                model.setLongitude(Double.valueOf(address.getString(BizConstant.LONGITUDE)));
            }
            if(!"0".equals(address.getString(BizConstant.LATITUDE))) {
                model.setLongitude(Double.valueOf(address.getString(BizConstant.LATITUDE)));
            }
        }

        FireStation entity = this.prepareEntity(model);
        this.updateById(entity);
        return Bean.toModel(entity, model);
    }
    /**
     * 列表查询 示例
     */
    public List<FireStation> queryForFireStationList(List<String> companyIdList) {
    	LambdaQueryWrapper<FireStation> wrapper =new LambdaQueryWrapper<FireStation>();
    	wrapper.eq(FireStation::getIsDelete, false);
    	wrapper.in(FireStation::getBizCompanyId, companyIdList);
        return this.baseMapper.selectList(wrapper);
    }
    /**
     * 查询当前公司下的所有微型消防站信息
     * @param companyId
     * @return
     */
    public List<Map<String , Object>> queryForFireStationListByCompanyId(Long companyId) {
    	LambdaQueryWrapper<FireStation> wrapper =new LambdaQueryWrapper<FireStation>();
    	wrapper.eq(FireStation::getIsDelete, false);
    	wrapper.eq(FireStation::getBizCompanyId, companyId);
    	wrapper.select(FireStation::getSequenceNbr,FireStation::getName);
    	return  this.baseMapper.selectMaps(wrapper);
    }

    /**
     * 获取机场单位树
     * chenzhao 2021-10-14
     * @return
     */
    public List<MenuFrom> getCompanyTeamTree() throws Exception {
        MenuFrom root = new MenuFrom("-1", "微型消防站", null, null);

        List<OrgUsr> companyDeptList = orgUsrService.selectCompanyList();
        List<MenuFrom> companyDeptMenuList = Lists.newArrayList();
        companyDeptList.forEach(o -> {
            if (ValidationUtil.isEmpty(o.getParentId())) {
                o.setParentId("-1");
            }
            companyDeptMenuList.add(new MenuFrom(o.getSequenceNbr().toString(), o.getBizOrgName(), o.getParentId(),
                    "1"));
        });

        List<MenuFrom> menuList = TreeParser.getTreexin("-1", companyDeptMenuList, MenuFrom.class.getName(), "getKey",
                1, "getName", "getParentId", "getNodeType");
        root.setChildren(menuList);
        return Lists.newArrayList(root);
    }
}
