package cn.pluss.platform.controller.deviceMerchantBuy;

import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.controller.BaseNoModelController;
import cn.pluss.platform.deviceMerchantBuy.DeviceMerchantBuyService;
import cn.pluss.platform.deviceStock.DeviceStockService;
import cn.pluss.platform.dict.DictService;
import cn.pluss.platform.entitiy.ShiroUser;
import cn.pluss.platform.entity.DeviceMerchantBuy;
import cn.pluss.platform.entity.DeviceStock;
import cn.pluss.platform.entity.Dict;
import cn.pluss.platform.entity.MerchantBaseInfo;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.yt.YtLogistHandler;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Setter;
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 org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("deviceMerchantBuy")
public class DeviceMerchantBuyController extends BaseNoModelController {

    private Integer PAGE_SIZE = 12;

    @Setter(onMethod_ = {@Autowired})
    private DeviceMerchantBuyService deviceMerchantBuyService;

    @Setter(onMethod_ = {@Autowired})
    private DeviceStockService deviceStockService;

    @Setter(onMethod_ = {@Autowired})
    private DictService dictService;

    @Setter(onMethod_ = {@Autowired})
    private MerchantBaseInfoService merchantBaseInfoService;

    @Setter(onMethod_ = {@Autowired})
    private HttpServletRequest request;

    @Setter(onMethod_ = {@Autowired})
    private YtLogistHandler ytLogistHandler;

    /**
     * 引导页
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView index(ModelAndView view) {
        List<Dict> deviceGroupDict = dictService.getByCode(Collections.singletonList("DEVICE_STOCK_GROUP"));
        view.addObject("deviceGroupDict", deviceGroupDict);
        view.setViewName("deviceMerchantBuy/deviceMerchantBuyList");
        return view;
    }

    /**
     * 分页查询
     */
    @RequestMapping(value = "/queryDeviceMerchantBuyByPage", method = RequestMethod.GET)
    @ResponseBody
    public Result<Page<DeviceMerchantBuy>> queryDeviceMerchantBuyByPage(Page<DeviceMerchantBuy> page, DeviceMerchantBuy deviceMerchantBuy, String startTime, String endTime) {
        QueryWrapper<DeviceMerchantBuy> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(deviceMerchantBuy.getOrderNo()),"dmb.orderNo", deviceMerchantBuy.getOrderNo());

        queryWrapper.eq(StringUtils.isNotBlank(deviceMerchantBuy.getMerchantName()), "merchantCode", deviceMerchantBuy.getMerchantName());

        queryWrapper.like(StringUtils.isNotBlank(deviceMerchantBuy.getAlias()),"mbi.alias", deviceMerchantBuy.getAlias());

        queryWrapper.like(StringUtils.isNotBlank(deviceMerchantBuy.getTransNo()),"dmb.transNo", deviceMerchantBuy.getTransNo());

        queryWrapper.eq(StringUtils.isNotBlank(deviceMerchantBuy.getStatus()),"dmb.status", deviceMerchantBuy.getStatus());

        queryWrapper.gt(deviceMerchantBuy.getStartTime() != null, "dmb.createDt", deviceMerchantBuy.getStartTime());

        queryWrapper.lt(deviceMerchantBuy.getEndTime() != null, "dmb.createDt", deviceMerchantBuy.getEndTime());

        queryWrapper.eq(StringUtils.isNotBlank(deviceMerchantBuy.getUserId()), "doi.userId", deviceMerchantBuy.getUserId());

        queryWrapper.like(StringUtils.isNotBlank(deviceMerchantBuy.getName()),"dg.name",deviceMerchantBuy.getName());

        queryWrapper.like(StringUtils.isNotBlank(deviceMerchantBuy.getLinkName()),"dmb.linkName",deviceMerchantBuy.getLinkName());

        queryWrapper.eq(StringUtils.isNotBlank(deviceMerchantBuy.getLinkPhone()),"dmb.linkPhone",deviceMerchantBuy.getLinkPhone());

        queryWrapper.eq(deviceMerchantBuy.getOrderAmount() != null,"dmb.orderAmount",deviceMerchantBuy.getOrderAmount());

        queryWrapper.orderByDesc("id");

        Boolean admin = verifyUserRole();
        if (!admin) {
            ShiroUser queryCurrentShiroUser = queryCurrentShiroUser();
            queryWrapper.eq("status", "1");
            queryWrapper.eq("merchantCode", queryCurrentShiroUser.getMerchantCode());
        }

        Page<DeviceMerchantBuy> result = deviceMerchantBuyService.pageDeviceMerchantBuy(page, queryWrapper);
        return ResultGenerator.genSuccessResult(result);
    }

    /**
     * 查询详情
     */
    @RequestMapping(value = "/queryDeviceMerchantBuyDetails", method = RequestMethod.GET)
    public String queryDeviceMerchantBuyDetails(HttpServletRequest request, Integer id, Integer pageIndex) {

        if (id != null && id != 0) {
            DeviceMerchantBuy deviceMerchantBuy = new DeviceMerchantBuy();
            deviceMerchantBuy.setId(id);
            deviceMerchantBuy = deviceMerchantBuyService.queryDeviceMerchantBuy(deviceMerchantBuy);
            request.setAttribute("deviceMerchantBuy", deviceMerchantBuy);
            request.setAttribute("pageIndex", pageIndex);
        }
        return "deviceMerchantBuy/deviceMerchantBuyDetails";
    }

    /**
     * 查询详情
     */
    @RequestMapping(value = "/queryDeviceMerchantBuyBaseInfo", method = RequestMethod.GET)
    public String queryDeviceMerchantBuyBaseInfo(HttpServletRequest request, Integer id, Integer pageIndex) {

        if (id != null && id != 0) {
            DeviceMerchantBuy deviceMerchantBuy = new DeviceMerchantBuy();
            deviceMerchantBuy.setId(id);
            deviceMerchantBuy = deviceMerchantBuyService.queryDeviceMerchantBuy(deviceMerchantBuy);
            request.setAttribute("deviceMerchantBuy", deviceMerchantBuy);
            request.setAttribute("pageIndex", pageIndex);
        }
        return "deviceMerchantBuy/deviceMerchantBuyBaseInfo";
    }

    @PostMapping("/update")
    @ResponseBody
    public Result<Object> update(@RequestBody DeviceMerchantBuy entity) {
        deviceMerchantBuyService.updateById(entity);
        return ResultGenerator.genSuccessResult("操作成功", null);
    }

    /**
     * 查询详情
     */
    @RequestMapping(value = "/queryDeviceMerchantBuyExtendsInfo", method = RequestMethod.GET)
    public String queryDeviceMerchantBuyExtendsInfo() {

        return "deviceMerchantBuy/deviceMerchantBuyExtendsInfo";
    }

    /**
     * 查询详情
     */
    @RequestMapping(value = "/queryDeviceMerchantBuyFunctionsInfo", method = RequestMethod.GET)
    public String queryDeviceMerchantBuyFunctionsInfo() {

        return "deviceMerchantBuy/deviceMerchantBuyFunctionsInfo";
    }

    /**
     * 保存对象
     *
     * @throws IOException
     */
    @RequestMapping(value = "/saveDeviceMerchantBuy", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveDeviceMerchantBuy(DeviceMerchantBuy deviceMerchantBuy) {

        if (deviceMerchantBuy.getId() != null && deviceMerchantBuy.getId() != 0) {
            deviceMerchantBuyService.updateDeviceMerchantBuy(deviceMerchantBuy);
        } else {
            deviceMerchantBuyService.saveDeviceMerchantBuy(deviceMerchantBuy);
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("resultCode", "1");
        result.put("resultMessage", "保存成功!");
        return result;
    }

    /**
     * 修改对象
     *
     * @throws IOException
     */
    @RequestMapping(value = "/updateDeviceMerchantBuy", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateDeviceMerchantBuy(Integer id) {

        DeviceMerchantBuy deviceMerchantBuy = new DeviceMerchantBuy();
        deviceMerchantBuy.setId(id);
        deviceMerchantBuyService.updateDeviceMerchantBuy(deviceMerchantBuy);
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("resultCode", "1");
        result.put("resultMessage", "保存成功!");
        return result;
    }

    /**
     * 删除对象
     *
     * @throws IOException
     */
    @RequestMapping(value = "/deleteDeviceMerchantBuy", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> deleteDeviceMerchantBuy(Integer id) {
        DeviceMerchantBuy deviceMerchantBuy = new DeviceMerchantBuy();
        deviceMerchantBuy.setId(id);
        deviceMerchantBuyService.deleteDeviceMerchantBuy(deviceMerchantBuy);
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("resultCode", "1");
        result.put("resultMessage", "保存成功!");
        return result;
    }

    /**
     * expressNo:(填写快递单号). <br/>
     *
     * @param deviceMerchantBuy
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    @RequestMapping(value = "/expressNo", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> expressNo(DeviceMerchantBuy deviceMerchantBuy) {
        Map<String, Object> result = new HashMap<String, Object>(16);
        try {
            deviceMerchantBuyService.updateDeviceMerchantBuy(deviceMerchantBuy);
            result.put("msg", "操作成功");
        } catch (Exception e) {
            result.put("msg", "操作失败");
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping(value = "/printYtOrder", method = RequestMethod.POST)
    @ResponseBody
    public Result<?> printYtOrder(String ids) {
        if(StringUtils.isEmpty(ids)){
            return ResultGenerator.genFailResult("缺失参数");
        }
        if(ids.indexOf(",") < 0){
            DeviceMerchantBuy merchantBy = deviceMerchantBuyService.getById(ids);
            ytLogistHandler.createYtOrder(merchantBy);
            deviceMerchantBuyService.updateDeviceMerchantBuy(merchantBy);
            return ResultGenerator.genSuccessResult("操作成功！",null);
        }else{
            String[] idArr = ids.split(",");
            QueryWrapper<DeviceMerchantBuy> queryWrapper = new QueryWrapper<DeviceMerchantBuy>().
                    last(" WHERE linkPhone IN ( SELECT linkPhone FROM tb_pluss_device_merchant_buy WHERE id IN ("+ids+") GROUP BY linkPhone HAVING COUNT( linkPhone ) < 2) AND id IN ("+ids+") and status = 1 and expressNo IS NULL");
            List<DeviceMerchantBuy> list = deviceMerchantBuyService.list(queryWrapper);
            if(list.isEmpty()){
                return ResultGenerator.genFailResult("当前选中的订单未满足条件！",null);
            }
            int sIndex = idArr.length;
            int mIndex = list.size();
            for (DeviceMerchantBuy buy:list) {
                ytLogistHandler.createYtOrder(buy);
                deviceMerchantBuyService.updateDeviceMerchantBuy(buy);
            }
            return ResultGenerator.genSuccessResult("执行成功个数:"+mIndex+",选中个数:"+sIndex+",重复个数:"+(sIndex-mIndex),null);
        }
    }

    @PostMapping(value = "/updateSnNo")
    @ResponseBody
    public Result updateQrNo(Integer id, String snNo, String groupNo) {
        try {
            QueryWrapper<DeviceStock> queryWrapper = new QueryWrapper<DeviceStock>().eq("groupNo",groupNo)
                    .eq("snNo",snNo);
            List<DeviceStock> list = deviceStockService.list(queryWrapper);
            if(list.isEmpty()){
                return ResultGenerator.genFailResult("设备编号和设备类型不一致！",null);
            }
            DeviceMerchantBuy deviceMerchantBuy = new DeviceMerchantBuy();
            deviceMerchantBuy.setId(id);
            DeviceMerchantBuy buy = deviceMerchantBuyService.queryDeviceMerchantBuy(deviceMerchantBuy);
            if(buy == null){
                return ResultGenerator.genFailResult("订单数据不存在！",null);
            }
            DeviceStock stock = list.get(0);
            if(!"1".equals(stock.getStatus())){
                return ResultGenerator.genFailResult("设备已出售或激活，请更换！",null);
            }
            QueryWrapper<MerchantBaseInfo> baseInfoQueryWrapper = new QueryWrapper<MerchantBaseInfo>()
                    .eq("merchantCode",buy.getMerchantCode());
            List<MerchantBaseInfo> baseInfo = merchantBaseInfoService.list(baseInfoQueryWrapper);
            if (baseInfo != null && !baseInfo.isEmpty()) {
                MerchantBaseInfo merchant = baseInfo.get(0);
                stock.setBuyMercId(String.valueOf(merchant.getId()));
                stock.setBuyMercName(merchant.getAlias());
            }
            buy.setSnNo(snNo);
            deviceMerchantBuyService.updateDeviceMerchantBuy(buy);
            stock.setOrderNo(buy.getOrderNo());
            stock.setStatus("2");

            deviceStockService.updateById(stock);
            return ResultGenerator.genSuccessResult("操作成功！",null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("操作异常！",null);
        }
    }

    @RequestMapping(value = "/querydeviceMerchantBuyInfo", method = RequestMethod.GET)
    public String querydeviceMerchantBuyInfo(Integer id, HttpServletRequest request) {
        DeviceMerchantBuy deviceMerchantBuy = new DeviceMerchantBuy();
        deviceMerchantBuy.setId(id);
        deviceMerchantBuy = deviceMerchantBuyService.queryDeviceMerchantBuy(deviceMerchantBuy);
        request.setAttribute("deviceMerchantBuy", deviceMerchantBuy);
        return "deviceMerchantBuy/deviceMerchantBuyBaseInfo";
    }
}


