package cn.pluss.platform.controller.deviceStock;


import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.base.BaseModelController;
import cn.pluss.platform.converter.Converter;
import cn.pluss.platform.device.DeviceSpecService;
import cn.pluss.platform.device.DeviceStockGroupService;
import cn.pluss.platform.device.DeviceTypeService;
import cn.pluss.platform.deviceDetail.DeviceDetailService;
import cn.pluss.platform.deviceStock.DeviceStockService;
import cn.pluss.platform.dict.DictService;
import cn.pluss.platform.dto.DeviceStockDTO;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.vo.DeviceStockVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

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

/**
 * <p>
 * 设备库存controller
 * </p>
 *
 * @author bzg
 * @since 2020-11-11
 */
@Controller
@RequestMapping("/deviceStock")
public class DeviceStockController extends BaseModelController<DeviceStockService, DeviceStock> {

    @Autowired
    private DictService dictService;

    @Autowired
    private DeviceDetailService deviceDetailService;

    @Autowired
    private DeviceStockService dsService;

    @Autowired
    private UserAppService uaService;

    @Autowired
    private DeviceTypeService deviceTypeService;

    @Autowired
    private DeviceStockGroupService deviceStockGroupService;

    @Autowired
    private DeviceSpecService deviceSpecService;

    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = "/index")
    public String index(HttpServletRequest request) {
        List<DeviceType> deviceType = deviceTypeService.list();
        request.setAttribute("deviceTypeDict", deviceType);
        return "deviceStock/list";
    }

    @PostMapping("saveOrUpdate")
    @ResponseBody
    public Result<String> saveOrUpdate(@RequestBody DeviceStockDTO deviceStock) {
        if (deviceStock.getId() != null) {
            baseService.updateById(Converter.INSTANCE.toEntity(deviceStock));
            return ResultGenerator.genSuccessResult("保存成功", null);
        }

        try {
            if (StringUtils.isEmpty(deviceStock.getSnNo())) {
                throw new MsgException("设备编号不能为空");
            }

            QueryWrapper<DeviceDetail> queryWrapper = new QueryWrapper<DeviceDetail>()
                    .eq("groupNo", deviceStock.getGroupNo());
            List<DeviceDetail> list = deviceDetailService.list(queryWrapper);
            if (list.isEmpty()) {
                return ResultGenerator.genFailResult("未查询到该类型的设备，请先添加", null);
            }
            deviceStock.setPrice(list.get(0).getUnitPrice());
            baseService.save(deviceStock);
        } catch (Exception e) {
            return ResultGenerator.genFailResult("设备编号重复!", null);
        }

        return ResultGenerator.genSuccessResult("保存成功", null);
    }

    /**
     * 绑定厂家id
     *
     * @param deviceStock
     * @return
     */
    @PostMapping("/bindDeviceNo")
    @ResponseBody
    public Result<String> bindDeviceNo(@RequestBody DeviceStock deviceStock) {
        if (deviceStock.getId() == null) {
            throw new MsgException("id不能为空");
        }

        DeviceStock exist = baseService.getById(deviceStock.getId());
        if (!exist.getCode().startsWith("MP") && deviceStock.getDeviceNo() == null) {
            throw new MsgException("非码牌设备，厂家编号不能为空");
        }

        this.baseService.updateById(deviceStock);
        return ResultGenerator.genSuccessResult("保存成功", null);
    }

    @RequestMapping("pageData")
    @ResponseBody
    public Result<Page<DeviceStockVO>> pageData(Page<DeviceStockVO> page, DeviceStockDTO dto) {
        if (Objects.equals(dto.getDeviceNo(), "")) {
            dto.setDeviceNo(null);
        }
        if(StringUtils.isEmpty(dto.getBindStatus())){
            dto.setBindStatus("-2");
        }
        if(StringUtils.isNotEmpty(dto.getNoType())){
            if("2".equals(dto.getNoType())){
                if(StringUtils.isNotEmpty(dto.getStartDeviceNo())){
                    dto.setStartSnNo(dto.getStartDeviceNo());
                    dto.setStartDeviceNo(null);
                }
                if(StringUtils.isNotEmpty(dto.getEndDeviceNo())){
                    dto.setEndSnNo(dto.getEndDeviceNo());
                    dto.setEndDeviceNo(null);
                }
            }
        }
        Page<DeviceStockVO> result = baseService.pageInfo(page, dto);

        List<DeviceStockVO> resultList = new ArrayList<>();

        List<DeviceStockGroup> deviceStockGroupList = deviceStockGroupService.list();
        List<DeviceType> deviceTypeList = deviceTypeService.list();
        List<DeviceSpec> deviceSpecList = deviceSpecService.list();

        for (DeviceStockVO item : result.getRecords()) {
            for (DeviceStockGroup deviceStockGroup : deviceStockGroupList) {
                if (deviceStockGroup.getGroupCode().equals(item.getGroupNo())) {
                    item.setGroupNoDesc(deviceStockGroup.getGroupName());
                }
            }

            for (DeviceType deviceType : deviceTypeList) {
                if (deviceType.getCode().equals(item.getCode())) {
                    item.setCodeDesc(deviceType.getName());
                }
            }

            for (DeviceSpec deviceSpec : deviceSpecList) {
                if (deviceSpec.getCode().equals(item.getCode()) && deviceSpec.getSpec().equals(item.getType())) {
                    item.setTypeDesc(deviceSpec.getSpecName());
                }
            }
            resultList.add(item);
        }
        result.setRecords(resultList);
        return ResultGenerator.genSuccessResult(result);
    }

    @PostMapping("batchSaveNo")
    @ResponseBody
    public Result<String> batchSaveNo(@RequestBody DeviceStock deviceStock) {
        if (StringUtils.isEmpty(deviceStock.getStartSnNo())) {
            return ResultGenerator.genFailResult("开始设备编号不能为空，请重新输入！");
        }

        if (StringUtils.isEmpty(deviceStock.getEndSnNo())) {
            return ResultGenerator.genFailResult("开始设备不能为空，请重新输入！");
        }
        try {
            Long startSnNo = Long.parseLong(deviceStock.getStartSnNo());
            Long endSnNo = Long.parseLong(deviceStock.getEndSnNo());
            if (endSnNo.compareTo(startSnNo) < 0) {
                return ResultGenerator.genFailResult("结束编号范围有误，请重新输入！");
            }
            QueryWrapper<DeviceDetail> queryWrapper = new QueryWrapper<DeviceDetail>()
                    .eq("groupNo", deviceStock.getGroupNo());
            List<DeviceDetail> detail = deviceDetailService.list(queryWrapper);
            if (detail.isEmpty()) {
                return ResultGenerator.genFailResult("未查询到该类型的设备，请先添加", null);
            }
            deviceStock.setPrice(detail.get(0).getUnitPrice());
            List<DeviceStock> list = new ArrayList<>();
            for (long i = startSnNo; i <= endSnNo; i++) {
                DeviceStock stock = new DeviceStock();
                stock.setCreateTime(new Date());
                stock.setSnNo(String.valueOf(i));
                stock.setPrice(deviceStock.getPrice());
                stock.setStatus("1");
                stock.setCode(deviceStock.getCode());
                stock.setType(deviceStock.getType());
                stock.setGroupNo(deviceStock.getGroupNo());
                list.add(stock);
            }
            try {
                this.baseService.saveBatch(list, Integer.parseInt(String.valueOf(endSnNo - startSnNo)));
            } catch (Exception e) {
                return ResultGenerator.genFailResult("设备编号重复!", null);
            }
            return ResultGenerator.genSuccessResult("操作成功！！", null);
        } catch (Exception e) {
            throw new MsgException("包含重复的设备编号！");
        }
    }

    @PostMapping("bindSave")
    @ResponseBody
    public Result<String> bindSave(@RequestBody DeviceStockDTO deviceStock) {
        MsgException.checkNull(deviceStock.getUserId(), "缺少用户id");
        UserApp ua = uaService.getOne(new QueryWrapper<UserApp>().eq("userId", deviceStock.getUserId()));
        MsgException.checkNull(ua, "不存在的用户id");

        if (!Objects.equals("promoter", ua.getUserType())) {
            throw new MsgException("该用户id不是商户");
        }

        DeviceStock existData = dsService.getById(deviceStock.getId());
        dsService.bindPayCode(existData.getSnNo(), ua);

        return ResultGenerator.genSuccessResult("操作成功！！", null);
    }

    @PostMapping("unBindSave")
    @ResponseBody
    public Result<String> unBindSave(@RequestBody DeviceStock deviceStock) {
        baseService.unbind(deviceStock.getId().longValue());
        return ResultGenerator.genSuccessResult("操作成功！！", null);
    }

    @GetMapping("/getDeviceVersion")
    @ResponseBody
    public Result getDeviceVersion() {
        QueryWrapper<DeviceStockGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("groupCode", "groupName");
        List<DeviceStockGroup> list = deviceStockGroupService.list(queryWrapper);
        return ResultGenerator.genSuccessResult("操作成功！！", list);
    }

    /**
     * 后台设备出库
     * @param ids
     * @param accpetUserId
     * @param orderNo
     * @return
     */
    @PostMapping("transfer")
    @ResponseBody
    public Result<String> transfer(@RequestParam("ids[]") List<Long> ids,Long accpetUserId,String orderNo) {
        return baseService.manageTransfer(ids,accpetUserId,orderNo);
    }
}
