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.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.process.ResultCode;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;

@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;

    //修改评分
    @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) {
        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);
        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));
                vcs.add(vc);
            }

            vehicleCataBiz.inserts(vcs);
            return ObjectRestResponse.succ();
        } catch (NumberFormatException e) {
            e.printStackTrace();
            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.updateSelectiveById(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());
                vcs.add(vc);
            }
            vehicleCataBiz.inserts(vcs);

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

        }
    }


    @Override
    @ApiOperation("删除")
    @DeleteMapping(value = "/app/{id}")
    @ResponseBody
    @Transactional
    public ObjectRestResponse<VehicleModel> remove(@PathVariable int id){
        try {
            vehicleModelBiz.deleteById(id);
            VehicleCata vehicleCata = new VehicleCata();
            vehicleCata.setVehicleModelId(id);
            vehicleCataBiz.delete(vehicleCata);
           return ObjectRestResponse.succ();
        } catch (Exception e) {
            e.printStackTrace();
            throw  new BaseException(ResultCode.FAILED_CODE);
        }
    }
}