package com.sy.coinage.workshop.controller;

import com.sy.coinage.config.CustomConfig;
import com.sy.coinage.core.annotation.LoginNotRequired;
import com.sy.coinage.core.exception.RetException;
import com.sy.coinage.core.interceptor.TokenVerify;
import com.sy.coinage.core.util.DateUtils;
import com.sy.coinage.core.util.ExcelExportUtil;
import com.sy.coinage.log.model.LoginLog;
import com.sy.coinage.sys.model.Dept;
import com.sy.coinage.sys.model.Dict;
import com.sy.coinage.sys.service.IDeptService;
import com.sy.coinage.sys.service.IDictService;
import com.sy.coinage.workshop.service.IProductService;
import com.sy.coinage.workshop.service.IStockService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import javax.validation.Valid;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

import com.sy.coinage.workshop.model.*;
import com.sy.coinage.workshop.service.IWorkshopAccountService;
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.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.Date;
import java.util.List;

/**
 * -Controller
 */
@Api(value = "接口", tags = {"接口"})
@RestController
@RequestMapping(value = "/workshopAccount")
public class WorkshopAccountController extends BaseController {
    @Autowired
    private TokenVerify tokenVerify;

    @Autowired
    private IWorkshopAccountService workshopAccountService;

    @Autowired
    private CustomConfig customConfig;

    @Autowired
    private IProductService productService;

    @Autowired
    private IDictService dictService;

    @Autowired
    private IDeptService deptService;

    @Autowired
    private IStockService stockService;

    private static String[] names = {"序号", "日期", "摘要", "收入", "付出", "内部收入", "内部付出", "库存", "管库员"};
    private static String[] names2 = {"序号", "日期", "凭证编号", "摘要", "收入", "付出", "结存", "管库员"};


    @ApiOperation(value = "实物收发卡列表")
    @LoginNotRequired
    @PostMapping("/ware/list")
    @ActiveFastJsonProfile(groups = "list", clazz = WorkshopAccount.class)
    public IPage<WorkshopAccount> wareList(@RequestBody @Valid WareAccountExpReq req) {
        LambdaQueryWrapper<WorkshopAccount> queryWrapper = new LambdaQueryWrapper<>();
        // 统计台账类型：1.实物收发卡 2.封箱成品实物收发卡(车间) 3.剔除品实物收发卡(车间) 4.印花成品出入库台账 5.封箱成品出入库台账
        queryWrapper.eq(WorkshopAccount::getStatType, 1).eq(WorkshopAccount::getSecuritiesId, req.getSecuritiesId());
        queryWrapper.eq(WorkshopAccount::getWareId, req.getWareId());
        queryWrapper.orderByAsc(WorkshopAccount::getCreateTime);
        Page<WorkshopAccount> page = new Page<>(req.getPage(), req.getRows());
        IPage<WorkshopAccount> data = this.workshopAccountService.page(page, queryWrapper);
        return data;
    }

    @ApiOperation(value = "封箱成品/剔除品实物收发卡列表")
    @LoginNotRequired
    @PostMapping("/shopWare/list")
    @ActiveFastJsonProfile(groups = "list", clazz = WorkshopAccount.class)
    public IPage<WorkshopAccount> shopWareList(@RequestBody @Valid ShopWareAccountExpReq req) {
        Dept dept = this.deptService.getByCode(req.getWareId());
        LambdaQueryWrapper<WorkshopAccount> queryWrapper = new LambdaQueryWrapper<>();
        // 统计台账类型：1.实物收发卡 2.封箱成品实物收发卡(车间) 3.剔除品实物收发卡(车间) 4.印花成品出入库台账 5.封箱成品出入库台账
        queryWrapper.eq(WorkshopAccount::getStatType, req.getType()).eq(WorkshopAccount::getSecuritiesId, req.getSecuritiesId());
        queryWrapper.eq(WorkshopAccount::getDeptId, dept.getId());
        queryWrapper.orderByAsc(WorkshopAccount::getId);
        Page<WorkshopAccount> page = new Page<>(req.getPage(), req.getRows());
        IPage<WorkshopAccount> data = this.workshopAccountService.page(page, queryWrapper);
        return data;
    }

    @ApiOperation(value = "实物收发卡导出")
    @PostMapping("/ware/exp")
    @ActiveFastJsonProfile(groups = "list", clazz = WorkshopAccount.class)
    public FileVO wareExp(@RequestBody @Valid WareAccountExpReq req, @CurrentUser CacheUserVO user) {
        Dict dict = this.dictService.getByVal("locationOpt", req.getWareId(), null);
        Product p = this.productService.getById(req.getSecuritiesId());
        LambdaQueryWrapper<WorkshopAccount> queryWrapper = new LambdaQueryWrapper<>();
        // 统计台账类型：1.实物收发卡 2.封箱成品实物收发卡(车间) 3.剔除品实物收发卡(车间) 4.印花成品出入库台账 5.封箱成品出入库台账
        queryWrapper.eq(WorkshopAccount::getStatType, 1).eq(WorkshopAccount::getSecuritiesId, req.getSecuritiesId());
        queryWrapper.eq(WorkshopAccount::getWareId, req.getWareId());
        queryWrapper.orderByAsc(WorkshopAccount::getCreateTime);
        List<WorkshopAccount> list = this.workshopAccountService.list(queryWrapper);
        ExcelExportUtil<WorkshopAccount> excelExport = new ExcelExportUtil<>();
        String resp = excelExport.exportWare("实物收发卡", p.getSecurities(), dict.getName(), names, list, DateUtils.toString(new Date()) + "_实物收发卡.xlsx",
                customConfig.getAttaPath(),
                customConfig.getAttaUrl());
        FileVO data = new FileVO("实物收发卡.xlsx", resp);
        return data;
    }

    @ApiOperation(value = "车间收发卡导出")
    @PostMapping("/shop/exp")
    @LoginNotRequired
    @ActiveFastJsonProfile(groups = "list", clazz = WorkshopAccount.class)
    public FileVO shopExp(@RequestHeader String token, @RequestBody @Valid ShopAccountExpReq req) {
        if (req.getWareId() == null || req.getWareId().intValue() == 0) {
            CacheUserVO user = this.tokenVerify.getCacheUser(token);
            req.setWareId(user.getSelfWareId());
        }
        Stock stock = null;
        Integer wareId = req.getWareId();
        Stock lastStock = this.stockService.getLastStock(wareId);
        Dept dept = this.deptService.getByCode(req.getWareId());
        List<Stock> stockList = this.stockService
                .getStockList(wareId, lastStock.getSecuritiesId());
        if (stockList == null || stockList.size() == 0) {
            throw new RetException("仓库信息不存在");
        }
        for (Stock vo : stockList) {
            if (req.getType().intValue() == 3 && vo.getAreaId() == 2) {
                stock = vo;
                break;
            } else if (req.getType().intValue() == 2 && vo.getAreaId() == 1) {
                stock = vo;
                break;
            }
        }
        if (stock == null && req.getType() < 4) {
            throw new RetException("仓库信息不存在");
        } else {
            stock = stockList.get(0);
        }
        Dict dict = this.dictService.getByVal("locationOpt", wareId, null);
        Product p = this.productService.getById(stock.getSecuritiesId());
        LambdaQueryWrapper<WorkshopAccount> queryWrapper = new LambdaQueryWrapper<>();
        // 统计台账类型：1.实物收发卡 2.封箱成品实物收发卡(车间) 3.剔除品实物收发卡(车间) 4.印花成品出入库台账 5.封箱成品出入库台账
        queryWrapper.eq(WorkshopAccount::getStatType, req.getType())
                .eq(WorkshopAccount::getSecuritiesId, stock.getSecuritiesId());
        queryWrapper.eq(WorkshopAccount::getDeptId, dept.getId());
        queryWrapper.orderByAsc(WorkshopAccount::getCreateTime);
        List<WorkshopAccount> list = this.workshopAccountService.list(queryWrapper);
        ExcelExportUtil<WorkshopAccount> excelExport = new ExcelExportUtil<>();
        String name = null;
        switch (req.getType()) {
            case 2:
                name = "封箱成品实物收发卡";
                break;
            case 3:
                name = "剔除品实物收发卡";
                break;
            case 4:
                name = "印花成品出入库台账";
                break;
            case 5:
                name = "封箱成品出入库台账";
                break;
        }
        String resp = null;
        if (req.getType() == 2 || req.getType() == 3) {
            resp = excelExport.exportShop(req.getType(), name, p.getSecurities(), dict.getName(), names, list, DateUtils.toString(new Date()) + "_" + name + ".xlsx",
                    customConfig.getAttaPath(),
                    customConfig.getAttaUrl());
        } else {
            resp = excelExport.exportAccount(req.getType(), name, p.getSecurities(), dict.getName(), names2, list, DateUtils.toString(new Date()) + "_" + name + ".xlsx",
                    customConfig.getAttaPath(),
                    customConfig.getAttaUrl());
        }
        FileVO data = new FileVO(name + ".xlsx", resp);
        return data;
    }


    /**
     * 分页列表
     */
    @ApiOperation(value = "分页列表")
    @PostMapping("/list")
    @ActiveFastJsonProfile(groups = "list", clazz = WorkshopAccount.class)
    public IPage<WorkshopAccount> list(@RequestBody WorkshopAccountListReq req, @CurrentUser CacheUserVO user) {
        LambdaQueryWrapper<WorkshopAccount> queryWrapper = new LambdaQueryWrapper<>();
        // queryWrapper.eq(WorkshopAccount::getDeptId, user.getDeptId());
        // if (StringUtils.isNotBlank(req.getId())) {
        // queryWrapper.like(WorkshopAccount::getName, req.getName());
        // }
        // queryWrapper.and(wq -> {
        // // 拼接sql
        // wq.like(WorkshopAccount::getName, req.getName())
        // .or()
        // .like(WorkshopAccount::getRealName, req.getName());
        // })
        Page<WorkshopAccount> page = new Page<>(req.getPage(), req.getRows());
        IPage<WorkshopAccount> data = this.workshopAccountService.page(page, queryWrapper);
        return data;
    }


    /**
     * 详情
     */
    @ApiOperation(value = "-通过ID查询单条数据")
    @PostMapping("/get")
    @ActiveFastJsonProfile(groups = "get", clazz = WorkshopAccount.class)
    public WorkshopAccountVO get(@RequestBody @ApiParam(value = "主键请求bean") @Valid IdReq req) {
        WorkshopAccountVO data = null;
        WorkshopAccount model = this.workshopAccountService.getById(req.getId());
        data = new WorkshopAccountVO();
        BeanUtils.copyProperties(model, data);
        return data;
    }

    @ApiOperation(value = "生成当日台账")
    @Operation(value = "生成当日台账")
    @PostMapping("/createAccount")
//    @Permission("workshopAccount:add")
    public Object createAccount(@RequestBody @Valid CreateAccountReq req, @CurrentUser CacheUserVO user) {
        this.workshopAccountService.createAccount(req.getCreateDate(), user);
        return "";
    }

}
