package com.xxfc.platform.order.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.util.result.JsonResultUtil;
import com.xxfc.platform.order.biz.inner.OrderCalculateBiz;
import com.xxfc.platform.order.entity.InsureUser;
import com.xxfc.platform.order.entity.OrderPersonInsurance;
import com.xxfc.platform.order.entity.OrderRentVehicleDetail;
import com.xxfc.platform.order.mapper.OrderRentVehicleDetailMapper;
import com.xxfc.platform.order.pojo.order.OrderFullDTO;
import com.xxfc.platform.order.pojo.order.OrderFullVO;
import com.xxfc.platform.order.pojo.order.RentVehicleBO;
import com.xxfc.platform.order.pojo.order.add.AddRentVehicleDTO;
import com.xxfc.platform.universal.entity.IdInformation;
import com.xxfc.platform.universal.feign.ThirdFeign;
import com.xxfc.platform.vehicle.entity.BranchCompany;
import com.xxfc.platform.vehicle.feign.VehicleFeign;
import com.xxfc.platform.vehicle.pojo.BookVehicleVO;
import com.xxfc.platform.vehicle.pojo.CompanyDetail;
import lombok.extern.slf4j.Slf4j;
import org.mockito.internal.util.collections.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

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

import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_FALSE;
import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_TRUE;

/**
 * 租车订单详情
 *
 * @author zjw
 * @email nishijjo@qq.com
 * @date 2019-05-16 14:36:45
 */
@Slf4j
@Service
public class OrderRentVehicleBiz extends BaseBiz<OrderRentVehicleDetailMapper, OrderRentVehicleDetail> {

    @Autowired
    BaseOrderBiz baseOrderBiz;
    @Autowired
    VehicleFeign vehicleFeign;
    @Autowired
    ThirdFeign thirdFeign;

    @Autowired
    OrderCalculateBiz orderCalculateBiz;

    @Autowired
    InsureUserBiz insureUserBiz;


    public List<OrderRentVehicleDetail> listByOrderId(Integer orderId) {
        return mapper.listByOrderId(orderId);
    }
    //评分
    public JSONObject addScore(Integer userid,Integer score,Integer orderId) {
      try {
          List<OrderRentVehicleDetail> list=mapper.listByOrderId(orderId);
          int num=0;
          if(list.size()>0){
              Example example = new Example(OrderRentVehicleDetail.class);
              Example.Criteria criteria = example.createCriteria();
              criteria.andEqualTo("order_id",orderId);
              OrderRentVehicleDetail detail=list.get(0);
              Integer modelId=detail.getModelId();
              detail=new OrderRentVehicleDetail();
              detail.setScore(score);
              detail.setSUserid(userid);
              detail.setSTime(System.currentTimeMillis());
              num=mapper.updateByExampleSelective(detail,example);
              if(num>0){
                  score=mapper.getPScore(modelId);
                  vehicleFeign.addScore(modelId,score);
                  return JsonResultUtil.createSuccessResultWithObj(orderId);

              }
          }
          return JsonResultUtil.createDefaultFail();
      }catch (Exception e){
          log.error(e.getMessage(), e);
          return JsonResultUtil.createDefaultFail();
      }

    }
    //获取用户评分列表
    public JSONObject getScoreAll(Integer orderId) {
        try {
            Example example = new Example(OrderRentVehicleDetail.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("order_id",orderId);
           List<OrderRentVehicleDetail> list=mapper.selectByExample(example);
           if(list.size()>0){
               OrderRentVehicleDetail detail=list.get(0);
               Integer modelId=detail.getModelId();

           }


            return JsonResultUtil.createDefaultFail();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return JsonResultUtil.createDefaultFail();
        }
    }

    public RentVehicleBO initRentVehicleBO(AddRentVehicleDTO vo) {
        //计算天数
        vo.setDayNum(orderCalculateBiz.getIncludeDays(vo.getStartTime(), vo.getEndTime()));
        vo.setHourNum(orderCalculateBiz.getIncludeHours(vo.getStartTime(), vo.getEndTime()));

        if(null == vo.getEndCompanyId() || vo.getEndCompanyId().equals(0)) {
            if(StrUtil.isBlank(vo.getEndAddr())) {
                throw new BaseException(ResultCode.PARAM_ILLEGAL_CODE, Sets.newSet("公司参数不正确"));
            }else {
                Map<String, Object> map = BeanUtil.beanToMap(new BranchCompany(){{
                    setName(vo.getEndAddr());
                }}, false, true);
                List<BranchCompany> data = vehicleFeign.branchCompanyEntityList(map).getData();
                if(null == data) {
                    throw new BaseException(ResultCode.PARAM_ILLEGAL_CODE, Sets.newSet("公司参数不正确"));
                }else {
                    BranchCompany endCompany = vehicleFeign.branchCompanyEntityList(map).getData().get(0);
                    vo.setEndCompanyId(endCompany.getId());
                }
            }
        }
        if(vo.getStartCompanyId() != null) {
            CompanyDetail companyDetail = vehicleFeign.getCompanyDetail(vo.getStartCompanyId()).getData();
            if(companyDetail != null) {
                vo.setStartAddr(companyDetail.detailAddr());
            }
        }
        if(vo.getEndCompanyId() != null) {
            CompanyDetail companyDetail = vehicleFeign.getCompanyDetail(vo.getEndCompanyId()).getData();
            if(companyDetail != null) {
                vo.setEndAddr(companyDetail.detailAddr());
            }
        }
        RentVehicleBO bo = BeanUtil.toBean(vo, RentVehicleBO.class);
        bo.setBookVehicleVO(new BookVehicleVO(){{
            setBookStartDate(vo.getBookStartDate());
            setBookEndDate(vo.getBookEndDate());
            setBookStartDateTime(vo.getBookStartDateTime());
            setBookEndDateTime(vo.getBookEndDateTime());
        }});
        bo.setTickerNo(StrUtil.isNotBlank(vo.getTickerNos())?
                StrUtil.splitTrim(vo.getTickerNos(), ","):null);
        bo.setAccompanyItems(vo.getAccompanyItems());

        if(SYS_TRUE == vo.getNeedPersonInsurance() && StrUtil.isNotBlank(vo.getInsureUserIds())){
            String buyInsureIdCard = "";
            String buyInsureName = "";
            String buyInsurePhone = vo.getAppUserDTO().getUsername();
            IdInformation idInformation = thirdFeign.getOneByUserId(vo.getAppUserDTO().getUserid());
            if(null == idInformation) {
                String finalBuyInsurePhone = buyInsurePhone;
                List<InsureUser> insureUsers = insureUserBiz.selectList(new InsureUser(){{
                    setUserid(vo.getAppUserDTO().getUserid());
                    setPhone(finalBuyInsurePhone);
                    setIsdel(SYS_FALSE);
                }});
                if(CollUtil.isEmpty(insureUsers)) {
                    List<InsureUser> insureUsers2 = insureUserBiz.selectByWeekend(w -> {
                        w.andEqualTo(InsureUser::getUserid, vo.getAppUserDTO().getUserid());
                        w.andEqualTo(InsureUser::getIsdel, SYS_FALSE);
                        w.andIsNotNull(InsureUser::getPhone);
                        return w;
                    });
                    if(CollUtil.isEmpty(insureUsers2)) {
                        List<InsureUser> insureUsers3 = insureUserBiz.selectByWeekend(w -> {
                            w.andEqualTo(InsureUser::getUserid, vo.getAppUserDTO().getUserid());
                            w.andEqualTo(InsureUser::getIsdel, SYS_FALSE);
                            return w;
                        });
                        buyInsureIdCard = insureUsers3.get(0).getIdCard();
                        buyInsureName = insureUsers3.get(0).getName();
                    }else {
                        buyInsureIdCard = insureUsers2.get(0).getIdCard();
                        buyInsureName = insureUsers2.get(0).getName();
                        buyInsurePhone = insureUsers2.get(0).getPhone();
                    }
                }else{
                    buyInsureIdCard = insureUsers.get(0).getIdCard();
                    buyInsureName = insureUsers.get(0).getName();
                }

            }else {
                buyInsureIdCard = idInformation.getIdNumber();
                buyInsureName = idInformation.getName();
            }

            for(String insureUserId: vo.getInsureUserIds().split(",")) {
                InsureUser insureUser = insureUserBiz.selectById(Integer.valueOf(insureUserId));
                if(null == insureUser) {
                    throw new BaseException(ResultCode.PARAM_ILLEGAL_CODE, Sets.newSet("保险人不存在"));
                }else {
                    String finalBuyInsureIdCard = buyInsureIdCard;
                    String finalBuyInsureName = buyInsureName;
                    String finalBuyInsurePhone1 = buyInsurePhone;
                    bo.getInsurances().add(new OrderPersonInsurance(){{
                        setBuyInsureIdCard(finalBuyInsureIdCard);
                        setBuyInsureName(finalBuyInsureName);
                        setBuyInsurePhone(finalBuyInsurePhone1);
                        setIdCard(insureUser.getIdCard());
                        setName(insureUser.getName());
                    }});
                }
            }
        }
        return bo;
    }

    public List<OrderFullVO> selectListFull(OrderFullDTO dto) {
        return mapper.selectListFull(dto);
    }


}