package com.xxfc.platform.vehicle.biz;


import com.ace.cache.annotation.CacheClear;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.RandomUtil;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.vehicle.constant.RedisKey;
import com.xxfc.platform.vehicle.entity.*;
import com.xxfc.platform.vehicle.mapper.BranchCompanyStockInfoMapper;
import com.xxfc.platform.vehicle.mapper.CompanyBaseMapper;
import com.xxfc.platform.vehicle.mapper.SysRegionMapper;
import com.xxfc.platform.vehicle.pojo.AddOrUpdateVehicleVo;
import com.xxfc.platform.vehicle.pojo.dto.CompanyBaseDetailDTO;
import com.xxfc.platform.vehicle.pojo.vo.CompanyBaseVo;
import com.xxfc.platform.vehicle.pojo.vo.CompanyVo;
import com.xxfc.platform.vehicle.util.excel.ExcelImport;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class CompanyBaseBiz extends BaseBiz<CompanyBaseMapper, CompanyBase>  {


     @Autowired
    BranchCompanyStockRightBiz stockRightBiz;

    @Autowired
    BranchCompanyBiz branchCompanyBiz;

     @Autowired
     BranchCompanyStockInfoMapper stockInfoMapper;

     @Autowired
    SysRegionMapper sysRegionMapper;

     @Autowired
    AreaBiz areaBiz;

    @Autowired
    VehicleBiz  vehicleBiz;

    @Value("${branchCompanyPic.url}")
    private  String companyUrl;

    //临时数据同步
    public ObjectRestResponse synchro(){
        List<BranchCompanyStockInfo> list= stockInfoMapper.selectAll();
        if (list.size()>0){
            for (BranchCompanyStockInfo companyStockInfo:list){
                int num=0;
                String companyName=companyStockInfo.getCompanyName();
                Integer balance=companyStockInfo.getBalance();
                Integer total=companyStockInfo.getTotal();
                BigDecimal price=companyStockInfo.getPrice();
                CompanyBase companyBase=new CompanyBase();
                companyBase.setAddrCity(companyStockInfo.getAddrCity());
                companyBase.setAddrProvince(companyStockInfo.getAddrProvince());
                companyBase.setName(companyName);
                companyBase.setCover(companyUrl+"/image/admin/upload"+companyStockInfo.getCompanyPic());
                companyBase.setImages(companyUrl+"/image/admin/upload"+companyStockInfo.getCompanyPic());
                insertSelective(companyBase);
                Integer companyBaseId=companyBase.getId();
                if (companyBaseId!=null){
                    BranchCompanyStockRight branchCompanyStockRight=new BranchCompanyStockRight();
                    branchCompanyStockRight.setBalance(balance);
                    branchCompanyStockRight.setPrice(price);
                    branchCompanyStockRight.setTotal(total);
                    branchCompanyStockRight.setCompanyBaseId(companyBaseId);
                    branchCompanyStockRight.setStockState(2);
                    stockRightBiz.insertSelective(branchCompanyStockRight);
                }
                num++;
                log.info("----成功---num=="+num+"---companyBaseId==="+companyBaseId);
            }
        }

        return  ObjectRestResponse.succ();
    }

    //临时数据同步4(添加车辆)
    public ObjectRestResponse synchro4() throws  Exception{
        List<BranchCompany> list= branchCompanyBiz.selectListAll();
        if (list.size()>0){
            int num=1;
            for (BranchCompany branchCompany:list){
                List<AddOrUpdateVehicleVo> addOrUpdateVehicleVoList=new ArrayList<>();
                for (int i=1;i<6;i++){
                    String numberPlate="测试"+getNumberPlate(num);
                    AddOrUpdateVehicleVo vehicleVo=new AddOrUpdateVehicleVo();
                    vehicleVo.setCode(Integer.parseInt(RandomUtil.getRandomStr(4)));
                    vehicleVo.setNumberPlate(numberPlate);
                    vehicleVo.setStatus(1);
                    vehicleVo.setBrand(5);
                    vehicleVo.setUseType(1);
                    vehicleVo.setModelId(67);
                    vehicleVo.setSubordinateBranch(branchCompany.getId());
                    vehicleVo.setMaintenanceMileage(3000);
                    vehicleVo.setParkBranchCompanyId(branchCompany.getId());
                    vehicleVo.setTravelStatus(3);
                    addOrUpdateVehicleVoList.add(vehicleVo);
                    num++;
                    log.info("----成功---num=="+num+"---numberPlate==="+numberPlate);
                }
                vehicleBiz.add(addOrUpdateVehicleVoList);
            }

        }

        return  ObjectRestResponse.succ();
    }
    //临时数据同步5(添加车辆)
    public ObjectRestResponse synchro5(){
        List<JSONObject> list= branchCompanyBiz.getList();
        Integer number=10000;
        if (list.size()>0){

            for (JSONObject obj:list){
                Integer code= obj.getInteger("code");
                if (code==null||code==0){
                    continue;
                }
                Example example=new Example(Vehicle.class);
                example.createCriteria().andEqualTo("code",code);
                List<Vehicle> vehicles=vehicleBiz.selectByExample(example);
                int num=0;
                for (Vehicle vehicle:vehicles){
                    num++;
                    if (num==1){
                        continue;
                    }
                    number++;
                    vehicle.setCode(number);
                    vehicleBiz.updateSelectiveById(vehicle);
                }
            }

        }
        return  ObjectRestResponse.succ();
    }


    public  String  getNumberPlate(int number){
        String str=number+"";
        char[] ary1 = str.toCharArray();
        char[] ary2 = {'0','0','0','0'};
        System.arraycopy(ary1, 0, ary2, ary2.length-ary1.length, ary1.length);
        String result = new String(ary2);
        return result;
    }

    //临时数据同步2
    public ObjectRestResponse synchro2(){
        List<BranchCompany> list= branchCompanyBiz.selectListAll();
        if (list.size()>0){
            int num=0;
            for (BranchCompany branchCompany:list){
                Integer companyBaseId=branchCompany.getCompanyBaseId();
                Integer id=branchCompany.getId();
                if (companyBaseId!=null||companyBaseId!=0){
                     CompanyBase companyBase=selectById(companyBaseId);
                     if (companyBase!=null){
                         branchCompany=new BranchCompany();
                         branchCompany.setId(id);
                         branchCompany.setAddrProvince(companyBase.getAddrProvince());
                         branchCompany.setProvinceName(companyBase.getProvinceName());
                         branchCompany.setAddrCity(companyBase.getAddrCity());
                         branchCompany.setCityName(companyBase.getCityName());
                         branchCompany.setAddrTown(companyBase.getAddrTown());
                         branchCompany.setTownName(companyBase.getTownName());
                         branchCompanyBiz.updateSelectiveById(branchCompany);
                         num++;
                         log.info("----成功---num=="+num+"---companyBaseId==="+companyBaseId);
                     }
                }


            }
        }

        return  ObjectRestResponse.succ();
    }

    //临时数据同步6
    public ObjectRestResponse synchro6(){
        List<CompanyBase> list= mapper.getBaseList();
        if (list.size()>0){
            int num=0;
            for (CompanyBase companyBase:list){
                        String name=companyBase.getName();
                        BranchCompany branchCompany=new BranchCompany();
                        branchCompany.setCompanyBaseId(companyBase.getId());
                        name= name.substring(name.indexOf("（")+1,name.indexOf("）"));
                        name+="分公司";
                        log.info("----name=="+name);
                        branchCompany.setName(name);
                        branchCompany.setAddrProvince(companyBase.getAddrProvince());
                        branchCompany.setProvinceName(companyBase.getProvinceName());
                        branchCompany.setAddrCity(companyBase.getAddrCity());
                        branchCompany.setCityName(companyBase.getCityName());
                        branchCompany.setAddrTown(companyBase.getAddrTown());
                        branchCompany.setTownName(companyBase.getTownName());
                        branchCompany.setZoneId(companyBase.getZoneId());
                        branchCompany.setStatus(1);
                        branchCompanyBiz.insertSelective(branchCompany);
                        num++;
                        log.info("----成功---num=="+num+"---companyBaseId==="+companyBase.getId());
                    }
                }
        return  ObjectRestResponse.succ();
    }

    //临时数据同步3
    public ObjectRestResponse synchro3(){
        List<BranchCompanyStockInfo> list= stockInfoMapper.selectAll();
        if (list.size()>0){
            int num=0;
            for (BranchCompanyStockInfo companyStockInfo:list){
                Integer  id=companyStockInfo.getId();
                Integer balance=companyStockInfo.getBalance();
                Integer total=companyStockInfo.getTotal();
                BigDecimal price=companyStockInfo.getPrice();
                Integer state=companyStockInfo.getState();
                BranchCompanyStockRight branchCompanyStockRight=stockRightBiz.selectById(id);
                if (branchCompanyStockRight!=null){
                    branchCompanyStockRight=new BranchCompanyStockRight();
                    branchCompanyStockRight.setId(id);
                    branchCompanyStockRight.setBalance(balance);
                    branchCompanyStockRight.setStockState(state);
                    branchCompanyStockRight.setTotal(total);
                    branchCompanyStockRight.setPrice(price);
                    stockRightBiz.updateSelectiveById(branchCompanyStockRight);
                    num++;
                }
                log.info("----成功---num=="+num+"---id==="+id);
            }
        }
        return  ObjectRestResponse.succ();
    }
    //设置基础信息
    @CacheClear(pre = RedisKey.BRANCH_COMPANY_CACHE)
    public  ObjectRestResponse updCompany(CompanyVo companyVo){
        if (companyVo==null|| StringUtils.isBlank(companyVo.getCompanyName())|| StringUtils.isBlank(companyVo.getName())||
                companyVo.getZoneId()==null||companyVo.getZoneId()==0|| companyVo.getAddrProvince()==null||companyVo.getAddrProvince()==0
                || companyVo.getAddrCity()==null||companyVo.getAddrCity()==0){
            return  ObjectRestResponse.createFailedResult(ResultCode.NULL_CODE,"参数不能为空");
        }
        Area area=areaBiz.selectById(companyVo.getZoneId());
        Integer provinc=companyVo.getAddrProvince();
        if (area==null||StringUtils.isBlank(area.getProvinceIds())||!area.getProvinceIds().contains(provinc+"")){
            return  ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,"片区和省份不一致");
        }
        Integer state=companyVo.getState()==null?2:companyVo.getState();
        BigDecimal latitude=companyVo.getLatitude();
        BigDecimal longitude=companyVo.getLongitude();
        if (state==1&&(StringUtils.isBlank(companyVo.getAddrDetail())||StringUtils.isBlank(companyVo.getImages())||StringUtils.isBlank(companyVo.getDescribes())
                ||latitude==null||longitude==null)){
            return  ObjectRestResponse.createFailedResult(ResultCode.NULL_CODE,"上架时参数不能为空");
        }
        CompanyBase companyBase=new CompanyBase();
        BeanUtils.copyProperties(companyVo,companyBase);
        Integer companyBaseId=companyVo.getId();
        if (companyBaseId==null||companyBaseId==0){
            insertSelective(companyBase);
            companyBaseId=companyBase.getId();
        }else {
            updateSelectiveById(companyBase);
        }
        BranchCompany branchCompany=new BranchCompany();
        BeanUtils.copyProperties(companyVo,branchCompany);
        branchCompany.setCompanyBaseId(companyBaseId);
        branchCompany.setName(companyVo.getCompanyName());
        Integer companyId=companyVo.getCompanyId();
        if (companyId==null||companyId==0){
            branchCompany.setId(null);
            branchCompanyBiz.insertSelective(branchCompany);
        }else {
            branchCompany.setId(companyId);
            branchCompanyBiz.updateSelectiveById(branchCompany);
        }
        return  ObjectRestResponse.succ();
    }

    //获取详情
    public  ObjectRestResponse getCompanyDetail(CompanyVo companyVo){
        if (companyVo==null){
            return  ObjectRestResponse.createFailedResult(ResultCode.NULL_CODE,"参数不能为空");
        }
        Integer companyBaseId=companyVo.getId();
        Integer companyId=companyVo.getCompanyId();
        Integer stockId=companyVo.getStockId();
        String name="";
        String companyName="";
        String zoneName="";
        if (companyBaseId!=null&&companyBaseId>0){
            CompanyBase companyBase=selectById(companyBaseId);
            BeanUtils.copyProperties(companyBase,companyVo);
            name=companyBase.getName();
            Integer zoneId=companyBase.getZoneId();
            if (zoneId!=null){
                Area area=areaBiz.selectById(zoneId);
                if (area!=null){
                    zoneName=area.getName();
                }
            }

        }
        if (companyId!=null&&companyId>0){
            BranchCompany branchCompany=branchCompanyBiz.selectById(companyId);
            BeanUtils.copyProperties(branchCompany,companyVo);
            companyName=branchCompany.getName();
        }
        if (stockId!=null&&stockId>0){
            BranchCompanyStockRight stockRight=stockRightBiz.selectById(stockId);
            BeanUtils.copyProperties(stockRight,companyVo);
        }
        companyVo.setId(companyBaseId);
        companyVo.setName(name);
        companyVo.setCompanyName(companyName);
        companyVo.setZoneName(zoneName);
        return  ObjectRestResponse.succ(companyVo);
    }

    //设置股权信息
    public  ObjectRestResponse updStockInfo(CompanyVo companyVo){

        if (companyVo==null|| companyVo.getId()==null||companyVo.getId()==0 || companyVo.getBalance()==null||companyVo.getBalance()==0|| companyVo.getTotal()==null||companyVo.getTotal()==0
                ||companyVo.getPrice() ==null|| companyVo.getPrice().compareTo(BigDecimal.ZERO)<0){
            return  ObjectRestResponse.createFailedResult(ResultCode.NULL_CODE,"参数不能为空");
        }
        Integer companyBaseId=companyVo.getId();
        Integer stockState=companyVo.getStockState();
        if (stockState!=null&&stockState==2){
            CompanyBase companyBase=selectById(companyBaseId);
            if (companyBase==null||StringUtils.isBlank(companyBase.getDescribes())|| StringUtils.isBlank(companyBase.getContent())||StringUtils.isBlank(companyBase.getImages())){
                return  ObjectRestResponse.createFailedResult(ResultCode.NULL_CODE,"基础信息不完善");
            }
        }
        Integer stockId=companyVo.getStockId();
        BranchCompanyStockRight right=new BranchCompanyStockRight();
        BeanUtils.copyProperties(companyVo,right);
        if (stockId==null||stockId==0){
            right.setId(null);
            right.setCompanyBaseId(companyBaseId);
            stockRightBiz.insertSelective(right);
        }else {
            right.setId(stockId);
            stockRightBiz.updateSelectiveById(right);
        }
        return  ObjectRestResponse.succ();
    }

    //设置基础详情
    public  ObjectRestResponse updCompanyDetail(CompanyVo companyVo){
        if (companyVo==null){
            return  ObjectRestResponse.createFailedResult(ResultCode.NULL_CODE,"参数不能为空");
        }
        CompanyBase companyBase=new CompanyBase();
        BeanUtils.copyProperties(companyVo,companyBase);
        Integer companyBaseId=companyVo.getId();
        if (companyBaseId==null||companyBaseId==0){
            insertSelective(companyBase);
        }else {
            updateSelectiveById(companyBase);
        }
        return  ObjectRestResponse.succ();
    }

    public  ObjectRestResponse delCompany(Integer id){
        CompanyBase companyBase=new CompanyBase();
        companyBase.setId(id);
        companyBase.setIsDel(1);
        updateSelectiveById(companyBase);
        branchCompanyBiz.delCompanyByBaseId(id);
        return  ObjectRestResponse.succ();
    }

    public  ObjectRestResponse getList(CompanyVo companyVo){
        Integer page=1;
        Integer limit=10;
        if (companyVo.getPage()!=null&&companyVo.getPage()>0){
            page=companyVo.getPage();
        }
        if (companyVo.getLimit()!=null&&companyVo.getLimit()>0){
            limit=companyVo.getLimit();
        }
        return  ObjectRestResponse.succ(PageDataVO.pageInfo(page, limit, ()->mapper.getList(companyVo)));
    }

    //分公司和总表同步
    public ObjectRestResponse importExcel(MultipartFile multipartfile, HttpServletRequest request){
        try {
            List<String[]> readExcel = ExcelImport.getExcelData(multipartfile);
            if(readExcel.size()<4){
                return ObjectRestResponse.createFailedResult(1001,"导入不能没数据！！！");
            }
            for (int i = 3; i < readExcel.size(); i++) {
                String[] str = readExcel.get(i);
                String companyId = str[1];
                String companyName = str[2];
                String name = str[3];
                BranchCompany branchCompany=branchCompanyBiz.selectById(companyId);
                String provinceName=sysRegionMapper.getName(branchCompany.getAddrProvince());
                String cityName=sysRegionMapper.getName(branchCompany.getAddrCity());
                String townName=sysRegionMapper.getName(branchCompany.getAddrTown());
                branchCompany.setProvinceName(provinceName);
                branchCompany.setCityName(cityName);
                branchCompany.setTownName(townName);
                CompanyBase companyBase=new CompanyBase();
                companyBase.setName(name);
                companyBase=selectOne(companyBase);
                Integer companyBaseId=0;
                if (companyBase==null){
                    companyBase=new CompanyBase();
                    BeanUtils.copyProperties(branchCompany,companyBase);
                    companyBase.setId(null);
                    companyBase.setName(name);
                    insertSelective(companyBase);
                    companyBaseId=companyBase.getId();
                }else {
                    companyBaseId=companyBase.getId();
                    companyBase.setZoneId(branchCompany.getZoneId());
                    companyBase.setAddrProvince(branchCompany.getAddrProvince());
                    companyBase.setProvinceName(provinceName);
                    companyBase.setAddrCity(branchCompany.getAddrCity());
                    companyBase.setCityName(cityName);
                    companyBase.setAddrTown(branchCompany.getAddrTown());
                    companyBase.setTownName(townName);
                    updateSelectiveById(companyBase);
                }
                branchCompany.setCompanyBaseId(companyBaseId);
                branchCompanyBiz.updateSelectiveById(branchCompany);
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
            return ObjectRestResponse.createFailedResult(10001,"网络异常！");
        }
        return ObjectRestResponse.succ();
    }

    

    public CompanyBaseVo findCompanyDetailById(Integer id) {
        CompanyBaseVo companyBaseVo = new CompanyBaseVo();
        CompanyBaseDetailDTO companyBaseDetailDTO = mapper.findCompanyBaseById(id);
        BeanUtils.copyProperties(companyBaseDetailDTO,companyBaseVo);
        return companyBaseVo;
    }

    public  BranchCompany getCompanyId(String name){
        return  mapper.getCompanyId(name);
    }

}
