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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.biz.common.excel.ExcelUtil;
import com.yeejoin.amos.boot.module.common.api.dto.*;
import com.yeejoin.amos.boot.module.jxiop.api.dto.EXPersonUser;
import com.yeejoin.amos.boot.module.jxiop.api.dto.ExStationBasicDto;
import com.yeejoin.amos.boot.module.jxiop.api.entity.*;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.PersonBasicMapper;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.StationBasicMapper;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.utils.Bean;

import javax.servlet.http.HttpServletResponse;
import java.util.*;



@Service
public class ExcelServiceImpl {

    @Autowired
    ExDataSourcesImpl dataSourcesImpl;

    @Autowired
    StationBasicServiceImpl stationBasicServiceImpl;
    @Autowired
    PersonBasicServiceImpl personBasicServiceImpl;



    @Autowired
    PersonBasicMapper personBasicMapper;
    @Autowired
    StationBasicMapper stationBasicMapper;
    //人员资质信息service
    @Autowired
    PersonCertificateServiceImpl personCertificateService;
    //人员教育信息
    @Autowired
    PersonSkillEducationServiceImpl personSkillEducationService;
    @Autowired
    PersonAccountServiceImpl personAccountServiceImpl;



    public void templateExport(HttpServletResponse response, ExcelDto excelDto, Map par) throws ClassNotFoundException {
        String url = excelDto.getClassUrl();
        Class<?> clz = Class.forName(url);

        switch (excelDto.getType()) {

            case "RYXX":
                List<EXPersonUser> data=this.getEXPersonUser( par);

                ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), data,
                        clz, dataSourcesImpl, true);
                break;
            default:
                ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), null, clz, dataSourcesImpl,
                        true);
                break;
        }
    }

    public void commonExport(HttpServletResponse response, ExcelDto excelDto, Map par) {

        switch (excelDto.getType()) {

            case "CZXX":
                List<ExStationBasicDto> data=this.getExStationBasicDto(par);
                ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), data,
                        ExStationBasicDto.class, dataSourcesImpl, false);
                break;
            case "RYXX":
                List<EXPersonUser> datad=this.getEXPersonUserAll(par);
                ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), datad,
                        EXPersonUser.class, dataSourcesImpl, false);
                break;
            default:
                break;
        }
    }

    @Transactional
    public void commonUpload(MultipartFile multipartFile, ExcelDto excelDto) throws Exception {
        switch (excelDto.getType()) {
            case "CZXX":
                this.addExStationBasicDto(multipartFile);
                break;
            case "RYXX":
                this.updateEXPersonUser(multipartFile);
                break;
        }
        return;
    }



    //场站信息导出
    public List<ExStationBasicDto> getExStationBasicDto(Map<String,Object> map){
        List<ExStationBasicDto> data=null;
        if(!map.isEmpty()){
            data=stationBasicMapper.getExStationBasicDto(
                    map.containsKey("stationMasterName")? map.get("stationMasterName").toString():null,
                    map.containsKey("stationName")? map.get("stationName").toString():null,
                    map.containsKey("stationType")? map.get("stationType").toString():null,
                    map.containsKey("orgCode")? map.get("orgCode").toString():null);

        }
      return data;
    }
   //场站导入
   private void addExStationBasicDto(MultipartFile multipartFile) throws Exception {
       List<ExStationBasicDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile, ExStationBasicDto.class, 1);
       List<StationBasic> excelEntityList = new ArrayList<>();
       excelDtoList.forEach(item -> {
           StationBasic fireChemical = new StationBasic();
           fireChemical = Bean.toPo(item, fireChemical);
           if (fireChemical.getArea() != null) {
               String[] type = fireChemical.getArea().split("@");
               fireChemical.setAreaName(type[0]);
               fireChemical.setArea(type[1]);
               CompanyModel companyModel=personBasicServiceImpl.getCompanyModel(Long.parseLong(type[1]));
               fireChemical.setAreaCode(companyModel.getCompanyCode());
           }
           if (fireChemical.getStationType() != null) {
               String[] type = fireChemical.getStationType().split("@");
               fireChemical.setStationTypeName(type[0]);
               fireChemical.setStationType(type[1]);
           }



           //平台增加场站
           CompanyModel companyModeldata=new CompanyModel();
           companyModeldata.setCompanyName(fireChemical.getStationName());
           companyModeldata.setCompanyType("company");
           companyModeldata.setLevel("station");
           companyModeldata.setParentId(Long.valueOf(fireChemical.getArea()));
           companyModeldata.setCompanyCode(fireChemical.getStationCode());
           companyModeldata= this.addCompanyModel(companyModeldata);

           fireChemical.setProjectOrgCode(companyModeldata.getOrgCode());
           fireChemical.setPlatformStationId(companyModeldata.getSequenceNbr().toString());
           excelEntityList.add(fireChemical);
       });
       stationBasicServiceImpl.saveBatch(excelEntityList);
   }

   //获取人员数据

  public  List<EXPersonUser>  getEXPersonUser(Map map){
      List<EXPersonUser>  listdata= personBasicMapper.getEXPersonUser(
              map.containsKey("name")? map.get("name").toString():null,
              map.containsKey("accountName")? map.get("accountName").toString():null,
              map.containsKey("projectName")?map.get("projectName").toString():null,
              map.containsKey("orgCode")?map.get("orgCode").toString():null);
        return listdata;
  }

  //人员导出

    public  List<EXPersonUser>  getEXPersonUserAll(Map map){
        List<EXPersonUser>  listdata= personBasicMapper.getEXPersonUserAll(
                map.containsKey("name")? map.get("name").toString():null,
                map.containsKey("accountName")? map.get("accountName").toString():null,
                map.containsKey("projectName")?map.get("projectName").toString():null,
                map.containsKey("orgCode")?map.get("orgCode").toString():null);
        return listdata;
    }

    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 updateEXPersonUser(MultipartFile multipartFile) throws Exception {
    List<EXPersonUser> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile, EXPersonUser.class, 1);
    this.updateEXPersonUserda(excelDtoList);

}

    @Transactional
    public void updateEXPersonUserda(List<EXPersonUser> excelDtoList) {

        List<PersonBasic> listPersonBasic = new ArrayList<>();
        List<PersonSkillEducation> listPersonSkillEducation = new ArrayList<>();
        List<PersonCertificate> listPersonCertificate = new ArrayList<>();

        for (EXPersonUser exPersonUser : excelDtoList) {
            //根据平台账号获取用户id
            QueryWrapper<PersonAccount> wrapper = new QueryWrapper();
            wrapper.eq("account_name",exPersonUser.getAccountName());
            PersonAccount  personAccount=personAccountServiceImpl.getOne(wrapper);
            //获取基本信息
            PersonBasic personBasic  = personBasicMapper.selectById(personAccount.getPersonId());
            BeanUtils.copyProperties(exPersonUser, personBasic);
            listPersonBasic.add(personBasic);
            //人员技能
            QueryWrapper<PersonSkillEducation> wrapper1 = new QueryWrapper();
            wrapper1.eq("person_id",personAccount.getPersonId());
            PersonSkillEducation  personSkillEducation=personSkillEducationService.getOne(wrapper1);
            BeanUtils.copyProperties(exPersonUser, personSkillEducation);
            listPersonSkillEducation.add(personSkillEducation);
            //人员资质
            QueryWrapper<PersonCertificate> wrapper2 = new QueryWrapper();
            wrapper2.eq("person_id",personAccount.getPersonId());
            PersonCertificate  personCertificate=personCertificateService.getOne(wrapper2);
            BeanUtils.copyProperties(exPersonUser, personCertificate);
            listPersonCertificate.add(personCertificate);
        }
        personBasicServiceImpl.saveOrUpdateBatch(listPersonBasic);
        personSkillEducationService.saveOrUpdateBatch(listPersonSkillEducation);
        personCertificateService.saveOrUpdateBatch(listPersonCertificate);
    }


}
