package com.xxfc.platform.vehicle.rest;

import cn.hutool.core.bean.BeanUtil;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.UserDTO;
import com.github.wxiaoqi.security.auth.client.config.UserAuthConfig;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.vehicle.biz.VehicleBiz;
import com.xxfc.platform.vehicle.biz.VehicleCataBiz;
import com.xxfc.platform.vehicle.biz.VehicleModelBiz;
import com.xxfc.platform.vehicle.biz.VehiclePlatCataBiz;
import com.xxfc.platform.vehicle.common.RestResponse;
import com.xxfc.platform.vehicle.entity.Vehicle;
import com.xxfc.platform.vehicle.entity.VehicleCata;
import com.xxfc.platform.vehicle.entity.VehicleModel;
import com.xxfc.platform.vehicle.mapper.VehicleModelMapper;
import com.xxfc.platform.vehicle.pojo.VehicleModelQueryCondition;
import com.xxfc.platform.vehicle.pojo.VModelDetailVO;
import com.xxfc.platform.vehicle.pojo.VehicleModelVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.TransactionManagementConfigurationSelector;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.weekend.WeekendSqls;

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

@RestController
@RequestMapping("vehicleModel")
@Api(value = "车型controller", tags = {"车型操作接口"})
public class VehicleModelController extends BaseController<VehicleModelBiz, VehicleModel> {

    @Autowired
    private VehiclePlatCataBiz vehiclePlatCataBiz;

    @Autowired
    VehicleCataBiz vehicleCataBiz;

    @Autowired
    private VehicleModelBiz vehicleModelBiz;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private UserAuthConfig userAuthConfig;


    //修改评分
    @RequestMapping(value = "/app/addScore", method = RequestMethod.GET)
    public RestResponse addScore(
            @RequestParam(value = "id", defaultValue = "0") Integer id,
            @RequestParam(value = "score", defaultValue = "0") Integer score) {
        baseBiz.addScore(id, score);
        return RestResponse.suc();
    }

    //订单
    @ApiOperation("车型详情")
    @RequestMapping(value = "/app/unauth/detail/{id}", method = RequestMethod.GET)
    public ObjectRestResponse<VModelDetailVO> detail(@PathVariable("id") @ApiParam("车型id") Integer id) {
        //查询车型信息，车型类型关系
        //，公司信息，系统信息（购车须知，预定须知）
        VehicleModel vm = baseBiz.selectById(id);
        if (null == vm)
            throw new BaseException(ResultCode.NOTEXIST_CODE);
        VModelDetailVO vModelDetailVO = BeanUtil.toBean(vm, VModelDetailVO.class);
        vModelDetailVO.setVehiclePlatCatas(vehiclePlatCataBiz.getByModelId(vm.getId()));
        return new ObjectRestResponse().data(vModelDetailVO);
    }

    /**
     * 车型列表查
     *
     * @param vmqc 条件
     * @return
     */
    @ApiOperation("车型列表")
    @PostMapping(value = "/app/findVehicleModelPage")
    public ObjectRestResponse<VehicleModelVo> findVehicleModelPage(
            @RequestBody @ApiParam("查询条件") VehicleModelQueryCondition vmqc ,HttpServletRequest request) {

//        UserDTO user = userFeign.userinfoByToken(userAuthConfig.getToken(request)).getData();
//
//        if (user!=null) {
//            if (user.getDataAll()==2) {
//
//            }
//        }


        if (vmqc == null || vmqc.getPage() == null || vmqc.getLimit() == null || vmqc.getPage() < 0 || vmqc.getLimit() <= 0) {
            return ObjectRestResponse.createDefaultFail();
        }
        return vehicleModelBiz.findVehicleModelPage(vmqc);
    }

    /**
     * 添加车型
     *
     * @param vm      bean
     * @param request
     * @return
     */
    @ApiOperation("添加")
    @PostMapping(value = "/app/add")
    @ResponseBody
    @Transactional
    public ObjectRestResponse<VehicleModel> add(@RequestBody VehicleModel vm, HttpServletRequest request) {
        if (vm == null) {
            return ObjectRestResponse.createDefaultFail();
        }

        if (StringUtils.isBlank(vm.getName())) {
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "无车名");
        }

        String token = request.getHeader("Authorization");
        if (StringUtils.isBlank(token)) {
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "请登录");
        }
        ObjectRestResponse<UserDTO> uorr = null;
        try {
            uorr = userFeign.userinfoByToken(token);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (uorr == null || uorr.getData() == null || StringUtils.isBlank(uorr.getData().getName()) || uorr.getData().getId() == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "获取不到用户信息");
        }
        String host = request.getRemoteHost();
        if (StringUtils.isBlank(host)) {
            return ObjectRestResponse.createDefaultFail();
        }
        //设置信息
        vm.setCrtName(uorr.getData().getName());
        vm.setCrtUser(uorr.getData().getId());
        vm.setCrtTime(new Date());
        vm.setCrtHost(host);
        vm.setIsdel(0);
        vm.setVioDeposit(BigDecimal.valueOf(500));
        try {
            //插入数据到车型并返回id
            Integer vmId = vehicleModelBiz.insertAndGetId(vm);
            if (vmId == null) {
                return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "插入数据失败");
            }

            System.out.println("vmId:" + vmId);
            //获取该车型所有的标签id
            ArrayList<VehicleCata> vcs = new ArrayList<>();
//            获取cataid
            String[] config = vm.getConfig().split(",");
            for (String con : config) {
                VehicleCata vc = new VehicleCata();
                vc.setVehicleModelId(vmId);
                vc.setCataId(Integer.parseInt(con));
                vc.setCrtTime(System.currentTimeMillis());
                vcs.add(vc);
            }

            vehicleCataBiz.inserts(vcs);
            return ObjectRestResponse.succ();
        } catch (NumberFormatException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new BaseException(ResultCode.FAILED_CODE);
        }

    }


    @ApiOperation("修改")
    @PutMapping(value = "/app/update")
    @ResponseBody
    @Transactional
    public ObjectRestResponse<VehicleModel> update(@RequestBody VehicleModel vm, HttpServletRequest request) {

        String token = request.getHeader("Authorization");
        ObjectRestResponse<UserDTO> uorr = null;
        try {
            uorr = userFeign.userinfoByToken(token);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (uorr == null || uorr.getData() == null || StringUtils.isBlank(uorr.getData().getName()) || uorr.getData().getId() == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "获取不到用户信息");
        }
        String host = request.getRemoteHost();
        if (StringUtils.isBlank(host)) {
            return ObjectRestResponse.createDefaultFail();
        }
//     插入修改时间
        vm.setUpdName(uorr.getData().getName());
        vm.setUpdUser(uorr.getData().getId());
        vm.setUpdHost(host);
        vm.setUpdTime(new Date());


        try {
            //修改车型
            vehicleModelBiz.updateByPrimaryKeySelective(vm);
            VehicleCata vcDelete = new VehicleCata();
            vcDelete.setVehicleModelId(vm.getId());
            // 删除车型对应的标签
            vehicleCataBiz.delete(vcDelete);
            ArrayList<VehicleCata> vcs = new ArrayList<>();
            //从新插入车型对应的标签
//            获取cataid
            String[] config = vm.getConfig().split(",");
            for (String con : config) {
                VehicleCata vc = new VehicleCata();
                vc.setCataId(Integer.parseInt(con));
                vc.setVehicleModelId(vm.getId());
                vc.setCrtTime(System.currentTimeMillis());
                vcs.add(vc);
            }
            vehicleCataBiz.inserts(vcs);

            return ObjectRestResponse.succ();
        } catch (NumberFormatException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new BaseException(ResultCode.FAILED_CODE);

        }
    }


    @Override
    @ApiOperation("删除")
    @DeleteMapping(value = "/app/{id}")
    @ResponseBody
    @Transactional
    public ObjectRestResponse<VehicleModel> remove(@PathVariable int id) {

        //1.先判断是否有属于该车型可用的车辆,有不能删除,无可以进行删除
        //根据车型查询对应的车辆
//        Example exa = Example.builder(Vehicle.class).where(
//                WeekendSqls.<Vehicle>custom()
//                        .andEqualTo(Vehicle::getModelId, id)
//                        .andEqualTo(Vehicle::getStatus, 1)
//                        .orEqualTo(Vehicle::getStatus,"2")
//        ).build();
//
//        List<Vehicle> vehicles = vehicleBiz.selectByExample(exa);
//
//        //判断是查询到对应的车辆
//        if (vehicles != null) {
//            ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "该车型,无法删除");
//        }

        if (id==1||id==14) {
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,"The label cannot be deleted");
        }

        //2.进行逻辑删除
        VehicleModel vm = new VehicleModel();
        vm.setId(id);
        vm.setIsdel(1);
        vehicleModelBiz.updateById(vm);

        //3.删除车型对应的标签
        VehicleCata vehicleCata = new VehicleCata();
        vehicleCata.setVehicleModelId(id);
        vehicleCata.setIsdel(1);
        vehicleCataBiz.updateIsdalByVehicleModelId(vehicleCata);

        return ObjectRestResponse.succ();

    }


    @ApiOperation("查询所有")
    @RequestMapping(value = "/findAll",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse findAll(){
        VehicleModel vehicleModel = new VehicleModel();
        vehicleModel.setIsdel(0);
        return ObjectRestResponse.succ(baseBiz.selectList(vehicleModel));
    }

}