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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.module.jxiop.api.dto.StationCoordinateDto;
import com.yeejoin.amos.boot.module.jxiop.api.dto.StationInfoDto;
import com.yeejoin.amos.boot.module.jxiop.api.entity.PersonAccount;
import com.yeejoin.amos.boot.module.jxiop.api.entity.StationBasic;
import com.yeejoin.amos.boot.module.jxiop.api.entity.StationCoordinate;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.StationBasicMapper;
import com.yeejoin.amos.boot.module.jxiop.api.service.IStationBasicService;
import com.yeejoin.amos.boot.module.jxiop.api.dto.StationBasicDto;
import com.yeejoin.amos.component.feign.config.InnerInvokException;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.systemctl.model.DictionarieModel;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * 场站基础信息表服务实现类
 *
 * @author system_generator
 * @date 2023-04-20
 */
@Service
public class StationBasicServiceImpl extends BaseService<StationBasicDto,StationBasic,StationBasicMapper> implements IStationBasicService {


    @Autowired
    StationCoordinateServiceImpl stationCoordinateServiceImpl;

    @Autowired
    PersonBasicServiceImpl personBasicServiceImpl;
    @Autowired
    StationBasicMapper stationBasicMapper;

    private  final  String CZLX="CZLX";
    /**
     * 分页查询
     */
    public Page<StationBasicDto> queryForStationBasicPage(Page<StationBasicDto> page)   {
        return this.queryForPage(page, null, false);
    }


    /**
     * 分页查询
     */
    public Page<StationBasicDto> queryPage(Page<StationBasicDto> page,
                                           String stationMasterName,
                                           String stationName,
                                           String stationType,
                                           String orgCode
                                           )   {
        List<StationBasicDto> list=stationBasicMapper.queryPage((page.getCurrent()-1) * page.getSize(),page.getSize(),  stationMasterName,
                stationName,
                stationType,orgCode);
        List<StationBasicDto> listcount=stationBasicMapper.queryPagecount( stationMasterName,
                stationName,
                stationType,
                orgCode);
        page.setTotal(listcount.size());
        page.setRecords(list);
        return page;
    }





    /**
     * 列表查询 示例
     */
    public List<StationBasicDto> queryForStationBasicList()   {
        return this.queryForList("" , false);
    }

    @Transactional
    public void add(StationBasic  stationBasic)   {

        //场站坐标信息
        List<StationCoordinate>  list=  stationBasic.getStationCoordinate();
        List<StationCoordinate>  listdate=new ArrayList<>();
        if(stationBasic.getBelongArealist()!=null){
            stationBasic.setBelongArea(JSON.toJSONString(stationBasic.getBelongArealist()));
        }
        CompanyModel companyModel=new CompanyModel();
        //单位
        companyModel=personBasicServiceImpl.getCompanyModel(Long.parseLong(stationBasic.getArea()));
        stationBasic.setAreaName(companyModel.getCompanyName());
        stationBasic.setAreaCode(companyModel.getCompanyCode());
        //获取类型名称
        String typeName=this.queryByCode(CZLX,stationBasic.getStationType());
        stationBasic.setStationTypeName(typeName);

        //场站基本信息
        this.save(stationBasic);
        if(CollectionUtils.isEmpty(list)){
            StationCoordinate stationCoordinate =  new StationCoordinate();
            stationCoordinate.setStationId(stationBasic.getSequenceNbr());
        }else{
            for (StationCoordinate stationCoordinate : list) {
                stationCoordinate.setStationId(stationBasic.getSequenceNbr());
                listdate.add(stationCoordinate);
            }
        }
        stationCoordinateServiceImpl.saveBatch(listdate);
        //平台增加场站
        CompanyModel companyModeldata=new CompanyModel();
        companyModeldata.setCompanyName(stationBasic.getStationName());
        companyModeldata.setCompanyType("company");
        companyModeldata.setLevel("station");
        companyModeldata.setParentId(Long.valueOf(stationBasic.getArea()));
        companyModeldata.setCompanyCode(stationBasic.getStationCode());
        companyModeldata= this.addCompanyModel(companyModeldata);
        stationBasic.setProjectOrgCode(companyModeldata.getOrgCode());
        stationBasic.setPlatformStationId(companyModeldata.getSequenceNbr().toString());
        this.update(stationBasic);
    }



    private CompanyModel addCompanyModel( CompanyModel companyModel) {
        FeignClientResult<CompanyModel> Model =Privilege.companyClient.create(companyModel);
        CompanyModel user=new CompanyModel();

        if (!ObjectUtils.isEmpty(Model)) {
            if(Model.getStatus()==200){
                user = Model.getResult();
            }else{
                throw new RuntimeException(Model.getMessage());
            }
        }
        return user;
    }

    private void deleteCompany( String ids) {
        FeignClientResult Model =Privilege.companyClient.deleteCompany(ids);

        CompanyModel user=new CompanyModel();

        if (!ObjectUtils.isEmpty(Model)) {
            if(Model.getStatus()!=200){
                throw new RuntimeException(Model.getMessage());
            }
        }

    }


    private String queryByCode(String dictCode,String dictDataKey) {
        FeignClientResult<DictionarieValueModel> Model =Systemctl.dictionarieClient.value(dictCode,dictDataKey);
        DictionarieValueModel user=new DictionarieValueModel();

        if (!ObjectUtils.isEmpty(Model)) {
            if(Model.getStatus()==200){
                user = Model.getResult();
            }else{
                throw new RuntimeException(Model.getMessage());
            }
        }
        return user.getDictDataValue();
    }



    private CompanyModel updateCompanyModel( CompanyModel companyModel,Long sequenceNbr) {
        FeignClientResult<CompanyModel> Model =Privilege.companyClient.update(companyModel,sequenceNbr);
        CompanyModel user=new CompanyModel();

        if (!ObjectUtils.isEmpty(Model)) {
            if(Model.getStatus()==200){
                user = Model.getResult();
            }else{
                throw new RuntimeException(Model.getMessage());
            }
        }
        return user;
    }



    @Transactional
    public void update(StationBasic  stationBasic)   {

        //场站坐标信息
        List<StationCoordinate>  list=  stationBasic.getStationCoordinate();
        List<StationCoordinate>  listdate=new ArrayList<>();
        if(stationBasic.getBelongArealist()!=null){
            stationBasic.setBelongArea(JSON.toJSONString(stationBasic.getBelongArealist()));
        }
        CompanyModel companyModel=new CompanyModel();
        //单位
        companyModel=personBasicServiceImpl.getCompanyModel(Long.parseLong(stationBasic.getArea()));
        stationBasic.setAreaName(companyModel.getCompanyName());
        stationBasic.setAreaCode(companyModel.getCompanyCode());

        //获取类型名称
        String typeName=this.queryByCode(CZLX,stationBasic.getStationType());
        stationBasic.setStationTypeName(typeName);

        //场站基本信息
        stationBasicMapper.updateById(stationBasic);
        stationBasicMapper.deleteStationCoordinateByStationid(stationBasic.getSequenceNbr());
        for (StationCoordinate stationCoordinate : list) {
            stationCoordinate.setStationId(stationBasic.getSequenceNbr());
            listdate.add(stationCoordinate);
        }
        stationCoordinateServiceImpl.saveOrUpdateBatch(listdate);

        //平台增加场站
        CompanyModel companyModeldata=new CompanyModel();
        companyModeldata.setCompanyName(stationBasic.getStationName());
        companyModeldata.setCompanyType("company");
        companyModeldata.setLevel("station");
        companyModeldata.setParentId(Long.valueOf(stationBasic.getArea()));
        companyModeldata.setCompanyCode(stationBasic.getStationCode());
        companyModeldata= this.updateCompanyModel(companyModeldata,Long.valueOf(stationBasic.getPlatformStationId()));
        stationBasic.setProjectOrgCode(companyModeldata.getOrgCode());
        stationBasic.setPlatformStationId(companyModeldata.getSequenceNbr().toString());
        stationBasicMapper.updateById(stationBasic);
    }


    public  int deleteList(String ids){
        QueryWrapper<StationBasic> wrapper = new QueryWrapper();
        wrapper.in("sequence_nbr",ids);
        List<StationBasic>  list=this.list(wrapper);
        List<String> idscom=new ArrayList<>();
        for (StationBasic personAccount : list) {
            idscom.add(personAccount.getPlatformStationId());
        }
        //删除平台
        int deleteResult = stationBasicMapper.deleteList(ids);
        this.deleteCompany(String.join(",",idscom));
        return deleteResult;
    }


    public  StationBasic getById(Long sequenceNbr){

        QueryWrapper<StationBasic> wrapper1 = new QueryWrapper();
        wrapper1.eq("sequence_nbr",sequenceNbr);
        StationBasic  stationBasic=this.getOne(wrapper1);

        if(stationBasic.getBelongArea()!=null){
            stationBasic.setBelongArealist(JSON.parseArray(stationBasic.getBelongArea(),Integer.class));
        }

        QueryWrapper<StationCoordinate> wrapper = new QueryWrapper();
        wrapper.eq("station_id",sequenceNbr);
        List<StationCoordinate>  list=stationCoordinateServiceImpl.list(wrapper);
        stationBasic.setStationCoordinate(list);
        return stationBasic;

    }

    public List<StationInfoDto> getStationList(String areaCode){
        return stationBasicMapper.getStationList(areaCode);
    }
    public int getStationPersonByStationID(String id) {return stationBasicMapper.getStationPersonByStationID(id);};

}