package com.sy.coinage.workshop.controller;

import com.sy.coinage.config.CustomConfig;
import com.sy.coinage.core.exception.RetException;
import com.sy.coinage.core.redis.RedisService;
import com.sy.coinage.core.util.DateUtils;
import com.sy.coinage.core.util.ExcelExportUtil;
import com.sy.coinage.sys.model.Dict;
import com.sy.coinage.sys.model.Role;
import com.sy.coinage.sys.service.IDictService;
import com.sy.coinage.workshop.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;

import org.apache.commons.lang3.ArraySorter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sy.coinage.core.annotation.ActiveFastJsonProfile;
import com.sy.coinage.core.annotation.CurrentUser;
import com.sy.coinage.core.aop.annotation.Permission;
import com.sy.coinage.core.aop.annotation.Operation;
import com.sy.coinage.core.controller.BaseController;
import com.sy.coinage.core.interceptor.Create;
import com.sy.coinage.core.interceptor.Update;
import com.sy.coinage.core.req.*;
import com.sy.coinage.core.vo.*;

import com.sy.coinage.workshop.model.*;
import com.sy.coinage.workshop.vo.*;
import com.sy.coinage.workshop.req.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

@Api(value = "接口", tags = {"接口"})
@RestController
@RequestMapping(value = "/deliveryPlan")
public class DeliveryPlanController extends BaseController {

    @Autowired
    private IDeliveryPlanService deliveryPlanService;

    @ApiOperation(value = "分页列表")
    @PostMapping("/page")
    @ActiveFastJsonProfile(groups = "list", clazz = DeliveryPlan.class)
    public IPage<DeliveryPlan> page(@RequestBody @ApiParam(value = "列表查询请求bean") DeliveryPlanListReq req, @CurrentUser CacheUserVO user) {
        LambdaQueryWrapper<DeliveryPlan> queryWrapper = new LambdaQueryWrapper<>();
        if (req.getSecuritiesId() != null && req.getSecuritiesId() > 0) {
            queryWrapper.eq(DeliveryPlan::getSecuritiesId, req.getSecuritiesId());
        }
        queryWrapper.like(StringUtils.isNotBlank(req.getAddressCn()), DeliveryPlan::getAddressCn, req.getAddressCn());
        if (req.getPlanDeliveryDate() != null) {
            queryWrapper.eq(DeliveryPlan::getPlanDeliveryDate, req.getPlanDeliveryDate());
        }
        queryWrapper.like(StringUtils.isNotBlank(req.getOrderNo()), DeliveryPlan::getOrderNo, req.getOrderNo());
        queryWrapper.orderByAsc(DeliveryPlan::getSecurities).orderByAsc(DeliveryPlan::getOrderNo);
        Page<DeliveryPlan> page = new Page<>(req.getPage(), req.getRows());
        IPage<DeliveryPlan> data = this.deliveryPlanService.page(page, queryWrapper);
        return data;
    }

    @ApiOperation(value = "列表")
    @PostMapping("/list")
    @ActiveFastJsonProfile(groups = "list", clazz = DeliveryPlan.class)
    public List<DeliveryPlan> list(@RequestBody @ApiParam(value = "列表查询请求bean") DeliveryPlanListReq req, @CurrentUser CacheUserVO user) {
        LambdaQueryWrapper<DeliveryPlan> queryWrapper = new LambdaQueryWrapper<>();
        List<DeliveryPlan> data = this.deliveryPlanService.list(queryWrapper);
        return data;
    }

    @ApiOperation(value = "获取详情")
    @PostMapping("/get")
    @ActiveFastJsonProfile(groups = "get", clazz = DeliveryPlan.class)
    public DeliveryPlanVO get(@RequestBody @ApiParam(value = "主键请求bean") @Valid IdReq req) {
        DeliveryPlanVO data = null;
        DeliveryPlan model = this.deliveryPlanService.getById(req.getId());
        data = new DeliveryPlanVO();
        BeanUtils.copyProperties(model, data);
        return data;
    }

    @ApiOperation(value = "新增")
    @Operation(value = "新增")
    @PostMapping("/add")
//    @Permission("deliveryPlan:add")
    public Object add(@RequestBody @ApiParam(value = "新增请求bean") @Validated({Create.class}) DeliveryPlanReq req, @CurrentUser CacheUserVO user) {
        this.deliveryPlanService.addModel(req);
        return "";
    }

    @ApiOperation(value = "修改")
    @Operation(value = "修改")
    @PostMapping("/update")
//    @Permission("deliveryPlan:update")
    public Object update(@RequestBody @ApiParam(value = "修改请求bean") @Validated({Update.class}) DeliveryPlanReq req, @CurrentUser CacheUserVO user) {
//        this.deliveryPlanService.updateModel(req);
        this.deliveryPlanService.updateModelNew(req);
        return "";
    }

    @ApiOperation(value = "根据品名id验证有无发货计划")
    @Operation(value = "根据品名id验证有无发货计划")
    @PostMapping("/validSecuritiesId")
    public Object validSecuritiesId(@RequestBody @ApiParam(value = "品名id请求bean") @Valid DeliveryPlanValidReq req, @CurrentUser CacheUserVO user) {
        return this.deliveryPlanService.validSecurities(req.getSecuritiesId(), req.getId());
    }

    private static String[] codes = {"securities", "addressCn", "planDeliveryDate", "qty", "totalBoxNum", "crownBetween", "parBetween", "orderNo", "status",};
    private static String[] names = {"品名", "入库地点", "解缴时间", "数量(万枚)", "总箱数", "冠字号范围", "拍号", "发货单号", "状态"};

    @Autowired
    private CustomConfig customConfig;

    @ApiOperation(value = "导出")
    @PostMapping("/exp")
    public Object exp(@RequestBody @ApiParam(value = "列表查询请求bean") DeliveryPlanListReq req) {
        FileVO data = new FileVO();
        LambdaQueryWrapper<DeliveryPlan> queryWrapper = new LambdaQueryWrapper<>();
        if (req.getSecuritiesId() != null && req.getSecuritiesId() > 0) {
            queryWrapper.eq(DeliveryPlan::getSecuritiesId, req.getSecuritiesId());
        }
        queryWrapper.like(StringUtils.isNotBlank(req.getAddressCn()), DeliveryPlan::getAddressCn, req.getAddressCn());
        if (req.getPlanDeliveryDate() != null) {
            queryWrapper.eq(DeliveryPlan::getPlanDeliveryDate, req.getPlanDeliveryDate());
        }
        queryWrapper.orderByAsc(DeliveryPlan::getSecurities).orderByAsc(DeliveryPlan::getOrderNo);
        List<DeliveryPlan> list = this.deliveryPlanService.list(queryWrapper);
        if (list != null && list.size() > 0) {
            list.stream().forEach(item -> {
                // 导出时替换css样式
                if (item.getParBetween().contains("<span")) {
                    item.setParBetween(item.getParBetween().replaceAll("<span class='red'>", "").replaceAll("</span>", ""));
                }
            });
        }
        ExcelExportUtil<DeliveryPlan> excelExport = new ExcelExportUtil<>();
        String fileName = "产品异地入库产品冠字号分配计划.xlsx";
        data.setName(fileName);
        String url = excelExport.exportData(names, codes, list, fileName, customConfig.getAttaPath(), customConfig.getAttaUrl());
        data.setUrl(url);
        return data;
    }

    //  @ApiOperation(value = "导入")
    //  @PostMapping("/imp")
    //  public Object imp(@RequestParam(required=true) MultipartFile file, @CurrentUser CacheUserVO user){
    //      Workbook workbook = ExcelUtil.readExcel(file);
    //      List<DeliveryPlanAddReq> list = ExcelImport.convertToList(DeliveryPlanAddReq.class, workbook, codes, names, 1, 1);
    //      this.validData(list);
    //      this.deliveryPlan.batchAdd(list, user);
    //      return "";
    //  }

    /**
     * 验证数据长度,非空
     */
    //	private void validData(List<DeliveryPlanAddReq> list) {
    //		if(null != list && list.size() > 0) {
    //			for (int i = 0; i < list.size(); i++) {
    //				ValidatorUtils.validateEntity(i, list.get(i));
    //			}
    //		}
    //	}
    @ApiOperation(value = "根据品名id获取箱数")
    @PostMapping("/getBoxNum")
    public Object getBoxNum(@RequestBody @ApiParam(value = "品名id获取箱数请求bean") @Valid BoxNumReq req, @CurrentUser CacheUserVO user) {
        DeliveryPlan model = new DeliveryPlan();
        BeanUtils.copyProperties(req, model);
        if (StringUtils.isNotBlank(req.getStartIds())) {
            model.setStartJumpIds(req.getStartIds());
        }
        if (StringUtils.isNotBlank(req.getEndIds())) {
            model.setEndJumpIds(req.getEndIds());
        }
        List<DeliveryPlanDetail> detail = new ArrayList<>();
        model = this.deliveryPlanService.getModel(model, detail, false, null);
        return model;
    }

    @ApiOperation(value = "更新当前冠字号范围和拍号")
    @PostMapping("/updateCrown")
    public Object updateCrown(@RequestBody @ApiParam(value = "品名id获取箱数请求bean") @Valid IdReq req, @CurrentUser CacheUserVO user) {
        this.deliveryPlanService.updateCrown(req.getId());
        return "";
    }

}
