package com.artfess.cqlt.controller;


import cn.hutool.core.bean.BeanUtil;
import com.artfess.base.annotation.ApiGroup;
import com.artfess.base.constants.ApiGroupConsts;
import com.artfess.base.controller.BaseController;
import com.artfess.base.enums.DelStatusEnum;
import com.artfess.base.enums.ProductSalesDataTypeEnum;
import com.artfess.base.enums.SubjectTypeEnum;
import com.artfess.base.exception.RequiredException;
import com.artfess.base.model.CommonResult;
import com.artfess.base.query.Direction;
import com.artfess.base.query.FieldSort;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.util.DateUtils;
import com.artfess.base.valid.AddGroup;
import com.artfess.base.valid.UpdateGroup;
import com.artfess.cqlt.manager.QfOperatingStatisticalManager;
import com.artfess.cqlt.manager.QfOperationSalesProductDManager;
import com.artfess.cqlt.manager.QfOperationSalesProductMManager;
import com.artfess.cqlt.model.QfEnterpriseInfo;
import com.artfess.cqlt.model.QfOperationSalesProductD;
import com.artfess.cqlt.model.QfOperationSalesProductM;
import com.artfess.cqlt.model.QfSubjectInternationalInfo;
import com.artfess.cqlt.vo.EnterpriseInfoVo;
import com.artfess.cqlt.vo.OpReportReqVo;
import com.artfess.cqlt.vo.OpTargetRespVo;
import com.artfess.cqlt.vo.ReportReqVo;
import com.artfess.cqlt.vo.SalesProductDetailVo;
import com.artfess.i18n.util.I18nUtil;
import com.artfess.poi.util.ExcelUtils;
import com.artfess.poi.util.FileDownloadUtil;
import com.artfess.uc.api.impl.util.ContextUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.io.ClassPathResource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

/**
 * 运营--产品销售数据填报主表 前端控制器
 *
 * @author min.wu
 * @company 阿特菲斯信息技术有限公司
 * @since 2023-02-17
 */
@Slf4j
@RestController
@Api(tags = "运营--产品销售数据填报主表")
@RequestMapping("/qf/operation/product/")
@ApiGroup(group = {ApiGroupConsts.GROUP_BIZ})
public class QfOperationSalesProductMController extends BaseController<QfOperationSalesProductMManager, QfOperationSalesProductM> {

    @Autowired
    private QfOperationSalesProductDManager operationSalesProductDManager;

    @Autowired
    private QfOperatingStatisticalManager qfOperatingStatisticalManager;

    @Override
    @PostMapping(value="/query", produces={"application/json; charset=utf-8" })
    @ApiOperation("分页查询结果")
    public PageList<QfOperationSalesProductM> query(@ApiParam(name="queryFilter", value="分页查询信息") @RequestBody QueryFilter<QfOperationSalesProductM> queryFilter) {
        List<FieldSort> sorter = queryFilter.getSorter();
        sorter.add(new FieldSort("fill_month_", Direction.ASC));
        queryFilter.setSorter(sorter);
        return baseService.query(queryFilter);
    }

    @Override
    @PostMapping("/")
    @ApiOperation("添加实体的接口")
    public CommonResult<String> create(@ApiParam(name = "model", value = "实体信息") @RequestBody @Validated({AddGroup.class}) QfOperationSalesProductM t) {
        t.setFillUser(ContextUtil.getCurrentUserId());
        t.setFillDate(LocalDate.now());
        t.setFillQuarter(DateUtils.getQuarter(t.getFillMonth()));
        boolean result = baseService.insertInfo(t);
        if (!result) {
            return new CommonResult<String>(false, I18nUtil.getMessage("option.fail", LocaleContextHolder.getLocale()), null);
        }

        return new CommonResult<String>(true, I18nUtil.getMessage("option.success", LocaleContextHolder.getLocale()), t.getId());
    }

    @Override
    @PutMapping("/")
    @ApiOperation("更新实体")
    public CommonResult<String> updateById(@ApiParam(name = "model", value = "实体信息") @RequestBody @Validated({UpdateGroup.class}) QfOperationSalesProductM t) {
        boolean result = baseService.updateInfo(t);
        if (!result) {
            return new CommonResult<String>(false, I18nUtil.getMessage("option.fail", LocaleContextHolder.getLocale()), null);
        }
        return new CommonResult<String>(true, I18nUtil.getMessage("option.success", LocaleContextHolder.getLocale()), null);
    }

    @PutMapping("/updateStatus")
    @ApiOperation("生效")
    public CommonResult<String> updateStatus(@ApiParam(name = "model", value = "实体信息") @RequestBody QfOperationSalesProductM t) {
        boolean result = baseService.updateStatus(t);
        if (!result) {
            return new CommonResult<String>(false, I18nUtil.getMessage("option.fail", LocaleContextHolder.getLocale()), null);
        }
        return new CommonResult<String>(true, I18nUtil.getMessage("option.success", LocaleContextHolder.getLocale()), null);
    }


    @Override
    @DeleteMapping("/{id}")
    @ApiOperation("根据id删除")
    public CommonResult<String> deleteById(@ApiParam(name = "id", value = "实体id") @PathVariable String id) {
        boolean result = baseService.removeById(id);
        if (!result) {
            return new CommonResult<String>(false, I18nUtil.getMessage("delete.fail", LocaleContextHolder.getLocale()), null);
        }
        return new CommonResult<String>(true, I18nUtil.getMessage("option.success", LocaleContextHolder.getLocale()), null);
    }

    @Override
    @DeleteMapping("/")
    @ApiOperation("根据id集合批量删除")
    public CommonResult<String> deleteByIds(@ApiParam(name = "ids", value = "实体集合") @RequestParam String... ids) {
        boolean result = baseService.removeByIds(Arrays.asList(ids));
        if (!result) {
            return new CommonResult<String>(false, I18nUtil.getMessage("delete.fail", LocaleContextHolder.getLocale()), null);
        }
        return new CommonResult<String>(true, I18nUtil.getMessage("option.success", LocaleContextHolder.getLocale()), null);
    }

    /**
     * @param file
     * @param mainId
     * @return
     */
    @ApiOperation(value = "产品销售数据导入")
    @PostMapping("/importExcel")
    public CommonResult<String> importExcel(@RequestParam("file") MultipartFile file, @RequestParam(value = "mainId", required = false) String mainId) {
        try {
            ExcelUtils<QfOperationSalesProductD> excelUtil = new ExcelUtils<>(QfOperationSalesProductD.class);
            List<QfOperationSalesProductD> list = excelUtil.importExcel(null, file.getInputStream());
            boolean result = baseService.importExcel(list, mainId);
            if (!result) {
                throw new IllegalArgumentException(I18nUtil.getMessage("import.fail", LocaleContextHolder.getLocale()));
            }
            return new CommonResult<>();
        } catch (Exception e) {
            throw new IllegalArgumentException(I18nUtil.getMessage("import.fail", LocaleContextHolder.getLocale()) + "," + e.getMessage());
        }
    }

    /**
     * 下载导入模板
     *
     * @param response
     * @return
     */
    @ApiOperation(value = "下载导入模板")
    @GetMapping("/downModel")
    public void downTemplate(HttpServletResponse response) {
        try {
            ClassPathResource classPathResource = new ClassPathResource("model/productDetail.xlsx");
            FileDownloadUtil.fileDownload(response, classPathResource.getInputStream(), "产品销售数据导入模板.xlsx");
        } catch (Exception e) {
            response.setCharacterEncoding("utf-8");
            throw new RequiredException(I18nUtil.getMessage("resources.noexist", LocaleContextHolder.getLocale()));
        }
    }

    @ApiOperation(value = "产品销售数据导出")
    @PostMapping("/export")
    public void export(HttpServletRequest request, HttpServletResponse response, @ApiParam(name = "queryFilter", value = "分页查询信息") @RequestBody QueryFilter<QfOperationSalesProductD> queryFilter) throws Exception {
        PageList<QfOperationSalesProductD> page = operationSalesProductDManager.query(queryFilter);
        List<SalesProductDetailVo> list = Lists.newArrayList();
        page.getRows().forEach(detail -> {
            SalesProductDetailVo detailVo = new SalesProductDetailVo();
            BeanUtil.copyProperties(detail, detailVo);
            // 百分比格式，不改VO，导出工具类已经根据%处理，这一行保留，不做数据放大
            if (null != detail.getDeviationRate()) {
                detailVo.setDeviationRateStr(detail.getDeviationRate() + "%");
            }
            if (null != detail.getDeviationRateYtd()) {
                detailVo.setDeviationRateYtdStr(detail.getDeviationRateYtd() + "%");
            }
            String dataType = ProductSalesDataTypeEnum.getDesc(detail.getDataType());
            detail.setDataType(dataType);

            list.add(detailVo);
        });
        ExcelUtils<SalesProductDetailVo> util = new ExcelUtils<SalesProductDetailVo>(SalesProductDetailVo.class);
        util.exportExcel(response, request, list, "产品销售数据信息");
    }

    @PostMapping("/oneLevelData")
    @ApiOperation(value = "销售板块指标一级界面统计接口", response = OpTargetRespVo.class, notes = "包括持续改进类数据")
    public CommonResult<String> oneLevelData(@ApiParam(name= "model", value = "请求参数") @RequestBody OpReportReqVo t) {
        List<OpTargetRespVo> data = qfOperatingStatisticalManager.data(t);
        return CommonResult.success(data, null);
    }

    @PostMapping("/fromUnderData")
    @ApiOperation(value = "销售板块指标包含当前指标的年度、季度、月度报表)", notes = "包括持续改进类数据")
    public CommonResult<String> fromUnderData(@ApiParam(name = "model", value = "请求参数") @RequestBody OpReportReqVo t) {
        List<OpTargetRespVo> data = qfOperatingStatisticalManager.fromUnderData(t);
        return CommonResult.success(data, null);
    }

}
