package com.xxfc.platform.vehicle.biz;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.BeanUtils;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.universal.dto.SmsTemplateDTO;
import com.xxfc.platform.universal.feign.ThirdFeign;
import com.xxfc.platform.vehicle.entity.BranchCompany;
import com.xxfc.platform.vehicle.entity.Vehicle;
import com.xxfc.platform.vehicle.entity.VehicleApply;
import com.xxfc.platform.vehicle.mapper.VehicleApplyMapper;
import com.xxfc.platform.vehicle.pojo.CompanySearchDTO;
import com.xxfc.platform.vehicle.pojo.CompanySearchVO;
import com.xxfc.platform.vehicle.pojo.dto.VehicleApplyFindDTO;
import com.xxfc.platform.vehicle.pojo.vo.VehicleApplyVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class VehicleApplyBiz extends BaseBiz<VehicleApplyMapper, VehicleApply>{

    @Autowired
    VehicleBiz vehicleBiz;

    @Autowired
    VehicleExtensionBiz extensionBiz;

    @Autowired
    ThirdFeign thirdFeign;

    @Autowired
    UserFeign userFeign;

    @Autowired
    BranchCompanyBiz branchCompanyBiz;




    @Transactional(rollbackFor = Exception.class)
    public  VehicleApply  saveApply(Vehicle vehicle){
        if (vehicle == null || StringUtils.isBlank(vehicle.getName()) || vehicle.getSubordinateBranch() == null || vehicle.getSubordinateBranch() == 0){
             throw  new BaseException("参数不能为空",ResultCode.FAILED_CODE);
        }
        String vehicleId=StringUtils.isBlank(vehicle.getId()) ? "" : vehicle.getId();
        List<Vehicle> list=vehicleBiz.getListByExample(vehicleId,vehicle.getNumberPlate());
        if (list.size() > 0){
            throw  new BaseException("车牌号不能重复",ResultCode.FAILED_CODE);
        }
        setPriceType(vehicle);
        VehicleApply vehicleApply=new VehicleApply();
        BeanUtils.copyProperties(vehicle,vehicleApply);
        Integer formType=2;
        String detailJson;
        if (StringUtils.isNotBlank(vehicleId)){
            if (checkStatus(vehicleId) > 0L){
                throw  new BaseException("已存在待审核记录",ResultCode.FAILED_CODE);
            }
            Vehicle vehicle1=vehicleBiz.selectById(vehicleId);
            BeanUtils.copyPropertiesTargetIsEquals(vehicle1,vehicle);
            detailJson= JSONObject.toJSONString(vehicle);
        }else {
            formType=1;
            detailJson= JSONObject.toJSONString(vehicle);
        }
        vehicleApply.setChangeJson(detailJson);
        vehicleApply.setFormType(formType);
        vehicleApply.setVehicleId(vehicleId);
        vehicleApply.setId(null);
        insertSelective(vehicleApply);
        Integer vehicleApplyId = vehicle.getVehicleApplyId() == null ? 0 : vehicle.getVehicleApplyId();
        if (vehicleApplyId > 0){
            VehicleApply vehicleApply1=new VehicleApply();
            vehicleApply1.setId(vehicleApplyId);
            vehicleApply1.setIsDel(1);
            updateSelectiveById(vehicleApply1);
        }
        return  vehicleApply;
    }

    public  void  setPriceType(Vehicle vehicle){
        Integer goodsType = vehicle.getGoodsType() == null ? 0 : vehicle.getGoodsType();
        if (goodsType > 0){
            if (goodsType == 1 || goodsType == 2){
                vehicle.setPriceType(1);
            }else if (goodsType == 3){
                vehicle.setPriceType(2);
            }
        }
    }

    public Long checkStatus(String vehicleId){
        VehicleApply vehicleApply=new VehicleApply();
        vehicleApply.setVehicleId(vehicleId);
        vehicleApply.setApplyStatus(0);
        vehicleApply.setIsDel(0);
        return  selectCount(vehicleApply);
    }




    public List<VehicleApplyVo> getList(VehicleApplyFindDTO vehicleApplyFindDTO){
        return  mapper.selectList(vehicleApplyFindDTO);
    }

    public ObjectRestResponse selectList(VehicleApplyFindDTO vehicleApplyFindDTO){
        PageHelper.startPage(vehicleApplyFindDTO.getPage(), vehicleApplyFindDTO.getLimit());
        PageInfo<VehicleApplyVo> pageInfo = new PageInfo<>(getList(vehicleApplyFindDTO));
        return ObjectRestResponse.succ(PageDataVO.pageInfo(pageInfo));
    }


    public VehicleApply  getApplyInfo(Long id){
        VehicleApply vehicleApply = selectById(id);
        if (vehicleApply == null ){
            throw  new BaseException("申请记录不存在",ResultCode.FAILED_CODE);
        }
        return  vehicleApply;
    }

    @Transactional(rollbackFor = Exception.class)
    public  void  audit(VehicleApply vehicleApply) {
        Integer status=vehicleApply.getApplyStatus();
        if (status == 2 && StringUtils.isBlank(vehicleApply.getReason())){
            throw  new BaseException("驳回原因不能为空",ResultCode.FAILED_CODE);
        }
        updateSelectiveById(vehicleApply);
        if (status == 1){
            vehicleApply=selectById(vehicleApply.getId());
            if (vehicleApply == null ){
                throw  new BaseException("申请记录不存在",ResultCode.FAILED_CODE);
            }
           String vehicleId =vehicleBiz.addOrUpd(vehicleApply);
            if (StringUtils.isNotBlank(vehicleId)){
                VehicleApply vehicleApply1=new VehicleApply();
                vehicleApply1.setId(vehicleApply.getId());
                vehicleApply1.setVehicleId(vehicleId);
                updateSelectiveById(vehicleApply1);
                String extensionList=vehicleApply.getExtensionList();
                if (StringUtils.isNotBlank(extensionList)){
                    extensionBiz.saveOrUpd(vehicleId,extensionList);
                }

            }

        }
        sendSms(vehicleApply);
    }

    public void  sendSms(VehicleApply vehicleApply){
        try {
            //发送短信通知用户
            vehicleApply=selectById(vehicleApply.getId());
            List<String> smsParams = new ArrayList<>();
            String name = StringUtils.isBlank(vehicleApply.getName()) ? "" : vehicleApply.getName();
            smsParams.add(name);
            Integer companyId = vehicleApply.getSubordinateBranch() == null ? 0 : vehicleApply.getSubordinateBranch();
            if (companyId == 0){
                return;
            }
            CompanySearchDTO companySearchDTO = new CompanySearchDTO();
            companySearchDTO.setId(companyId);
            List<CompanySearchVO> list = branchCompanyBiz.getList(companySearchDTO);
            if (list.size() == 0){
                return;
            }
            CompanySearchVO companySearchVO = list.get(0);
            ObjectRestResponse<AppUserDTO> restResponse = userFeign.userDetailById(companySearchVO.getAppUserId());
            if (restResponse.getData() == null){
                return;
            }
            AppUserDTO appUserDTO = restResponse.getData();
            Integer type=vehicleApply.getApplyStatus() == 1 ? SmsTemplateDTO.GOODS_S : SmsTemplateDTO.GOODS_F;
            thirdFeign.sendTemplate(new SmsTemplateDTO(){{
                setPhoneNumbers(appUserDTO.getUsername());
                setType(type);
                setParams(smsParams.toArray(new String[smsParams.size()]));
            }});
        }catch (Exception e){
            log.error(e.getMessage(), e);
            return;
        }

    }

    public VehicleApply  getVehicleInfo(String vehicleId){
        return  mapper.getOneByOrderUpdTime(vehicleId);
    }




    public List<VehicleApplyVo> getListByApp(VehicleApplyFindDTO vehicleApplyFindDTO){
        return  mapper.selectListByApp(vehicleApplyFindDTO);
    }

    public ObjectRestResponse selectListByApp(VehicleApplyFindDTO vehicleApplyFindDTO){
        PageHelper.startPage(vehicleApplyFindDTO.getPage(), vehicleApplyFindDTO.getLimit());
        PageInfo<VehicleApplyVo> pageInfo = new PageInfo<>(getListByApp(vehicleApplyFindDTO));
        return ObjectRestResponse.succ(PageDataVO.pageInfo(pageInfo));
    }



    //自动审核
    public  void authAudit(){
        List<VehicleApply> list = mapper.getListByDay();
        if (list != null && list.size() > 0 ){
            for (VehicleApply vehicleApply : list){
                VehicleApply vehicleApply1 = new VehicleApply();
                vehicleApply1.setApplyStatus(1);
                vehicleApply1.setId(vehicleApply.getId());
                try {
                    log.info("-----自动审核---id=="+vehicleApply1.getId());
                    audit(vehicleApply1);
                }catch (Exception e){
                    log.error(e.getMessage(),e);
                    vehicleApply1.setApplyStatus(2);
                    JSONObject reson = new JSONObject();
                    reson.put("content",e.getMessage());
                    vehicleApply1.setReason(reson.toJSONString());
                    audit(vehicleApply1);
                    continue;
                }
            }
        }
    }










}
