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.admin.feign.rest.UserRestInterface;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreClientToken;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
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.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.GoodDataVO;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
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.VehicleCata;
import com.xxfc.platform.vehicle.entity.VehicleModel;
import com.xxfc.platform.vehicle.pojo.VModelDetailVO;
import com.xxfc.platform.vehicle.pojo.VehicleModelQueryCondition;
import com.xxfc.platform.vehicle.pojo.VehicleModelVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 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;

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

    @Autowired
    private VehiclePlatCataBiz vehiclePlatCataBiz;

    @Autowired
    VehicleCataBiz vehicleCataBiz;

    @Autowired
    private VehicleModelBiz vehicleModelBiz;

    @Autowired
    private UserFeign userFeign;

    @Override
    public UserFeign getUserFeign() {
        return 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();
    }

    /**
     * 车型详情
     *
     * @param id
     * @return
     */
    @ApiOperation("车型详情")
    @RequestMapping(value = "/app/unauth/detail/{id}", method = RequestMethod.GET)
    @IgnoreUserToken
    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 = initVModelDetailVO(vm);
        return new ObjectRestResponse().data(vModelDetailVO);
    }

    /**
     * 车型详情
     *
     * @param vehicleModel
     * @return
     */
    @ApiOperation("车型详情")
    @RequestMapping(value = "/app/unauth/detail-param", method = RequestMethod.GET)
    @IgnoreUserToken
    public ObjectRestResponse<VModelDetailVO> detailByParam(VehicleModel vehicleModel) {
        //查询车型信息，车型类型关系
        //公司信息，系统信息（购车须知，预定须知）
        ObjectRestResponse<List<VehicleModel>> vms = entityList(vehicleModel);
        if (null == vms.getData() || null == vms.getData().get(0))
            throw new BaseException(ResultCode.NOTEXIST_CODE);
        VehicleModel vm = vms.getData().get(0);
        VModelDetailVO vModelDetailVO = initVModelDetailVO(vm);
        return new ObjectRestResponse().data(vModelDetailVO);
    }

    private VModelDetailVO initVModelDetailVO(VehicleModel vm) {
        VModelDetailVO vModelDetailVO = BeanUtil.toBean(vm, VModelDetailVO.class);
        vModelDetailVO.setVehiclePlatCatas(vehiclePlatCataBiz.getByModelId(vm.getId()));
        vModelDetailVO.setAppUserDTO(getAppUser());
        vModelDetailVO.setUserMemberLevel(userFeign.levels());
        return vModelDetailVO;
    }

    /**
     * 车型列表查
     *
     * @param vmqc 条件
     * @return
     */
    @ApiOperation("车型列表")
    @PostMapping(value = "/app/unauth/findVehicleModelPage")
    @IgnoreUserToken
    public ObjectRestResponse<PageDataVO<VehicleModelVo>> findVehicleModelPageUnauthfind(
            @RequestBody @ApiParam("查询条件") VehicleModelQueryCondition vmqc, HttpServletRequest request) {
        if (vmqc.getIsDel() == null) {
            vmqc.setIsDel(0);
        }
//        if (vmqc.getStatus() == null) {
//            vmqc.setStatus(SYS_TRUE);
//        }
        if (vmqc == null || vmqc.getPage() == null || vmqc.getLimit() == null || vmqc.getPage() < 0 || vmqc.getLimit() <= 0) {
            return ObjectRestResponse.paramIsEmpty();
        }
        //结合车型
        if (org.apache.commons.lang3.StringUtils.isNotBlank(vmqc.getCatasStr())) {
            vmqc.setCatas(vehiclePlatCataBiz.groupCatasByParent(vmqc.getCatasStr()));
        }
        return vehicleModelBiz.findVehicleModelPage(vmqc);
    }


    @GetMapping(value = "/app/unauth/findRandomVehicle")
    @IgnoreUserToken
    @ApiOperation("获取随机车型")
    public ObjectRestResponse findRandomVehicle(Integer number) {
        return vehicleModelBiz.findRandomVehicle(number);
    }


    /**
     * 添加车型
     *
     * @param vm      bean
     * @param request
     * @return
     */
    @ApiOperation("添加")
    @PostMapping(value = "/app/add")
    @Transactional
    public ObjectRestResponse<VehicleModel> add(@RequestBody VehicleModel vm, HttpServletRequest request) {
        if (vm == null) {
            return ObjectRestResponse.paramIsEmpty();
        }
        if (StringUtils.isBlank(vm.getName())) {
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "车名不能为空");
        }

        ObjectRestResponse<UserDTO> uorr = null;
        try {
            uorr = userFeign.userinfoByToken(userAuthConfig.getToken(request));
        } 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.setHotSign(2);
        vm.setCrtTime(new Date());
        vm.setCrtHost(host);
        vm.setIsdel(0);
        vm.setStatus(0);
        vm.setSort(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.ADD_VEHICLE_FAIL);
        }

    }

    @ApiOperation("修改")
    @PutMapping(value = "/app/update")
    @Transactional
    public ObjectRestResponse<VehicleModel> update(@RequestBody VehicleModel vm, HttpServletRequest request) {
        ObjectRestResponse<UserDTO> uorr = null;
        try {
            uorr = userFeign.userinfoByToken(userAuthConfig.getToken(request));
        } 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();
            if (vm.getId() != null) {
                vcDelete.setVehicleModelId(vm.getId());
                // 删除车型对应的标签
                vehicleCataBiz.delete(vcDelete);


                //从新插入车型对应的标签
//            获取cataid
                if (vm.getConfig()!=null) {
                    ArrayList<VehicleCata> vcs = new ArrayList<>();
                    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.UPDATE_VEHICLE_FAIL);

        }
    }


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

        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.updateSelectiveById(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));
//    }

    @ApiOperation("查询所有")
    @RequestMapping(value = "/findAll", method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse getList() {
        Example exa = Example.builder(VehicleModel.class).where(
                WeekendSqls.<VehicleModel>custom()
                        .andEqualTo(VehicleModel::getIsdel, 0)
        ).orderByDesc("sort").build();

        return ObjectRestResponse.succ(baseBiz.selectByExample(exa));
    }

    /**
     * 优质车型
     *
     * @param page
     * @param limit
     * @return
     */
    @ApiOperation("优质车型")
    @GetMapping(value = "/goodList")
    @IgnoreUserToken
    public ObjectRestResponse<List<GoodDataVO>> goodList(@RequestParam(value = "page") Integer page, @RequestParam(value = "limit") Integer limit) {
        return ObjectRestResponse.succ(baseBiz.goodList(page, limit));
    }

    @ApiOperation("上下架")
    @PutMapping(value = "/setStatus/{id}/{status}")
    @Transactional
    public ObjectRestResponse<VehicleModel> setStatus(@PathVariable(value = "id") Integer id, @PathVariable(value = "status") Integer status) {
        ObjectRestResponse<UserDTO> uorr = null;
        try {
            uorr = userFeign.userinfoByToken(userAuthConfig.getToken(request));
        } 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();
        }
        VehicleModel vehicleModel = new VehicleModel();
        vehicleModel.setId(id);
        vehicleModel.setStatus(status);
        vehicleModel.setUpdName(uorr.getData().getName());
        vehicleModel.setUpdUser(uorr.getData().getId());
        vehicleModel.setUpdHost(host);
        vehicleModel.setUpdTime(new Date());
        try {
            //修改车型
            vehicleModelBiz.updateByPrimaryKeySelective(vehicleModel);
            return ObjectRestResponse.succ();
        } catch (NumberFormatException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new BaseException(ResultCode.UPDATE_VEHICLE_FAIL);
        }
    }
}