package com.jwipc.supplier.controller.pc;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.jwipc.constant.DictCode;
import com.jwipc.dto.ExportDataDTO;
import com.jwipc.page.PageView;
import com.jwipc.security.LoginUtil;
import com.jwipc.supplier.constant.ModuleConst;
import com.jwipc.supplier.dto.SupplierAvlBaseDTO;
import com.jwipc.supplier.dto.SupplierAvlSaveDTO;
import com.jwipc.supplier.logic.SupplierAvlLogic;
import com.jwipc.supplier.model.query.SupplierAvlQuery;
import com.jwipc.sys.client.DictClient;
import com.jwipc.sys.client.dto.DictDTO;
import com.jwipc.util.EasyExcelUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p> 供应商avl清单相关接口</p>
 *
 * @author dengjsh
 * @version 1.0
 * @since JDK 1.8
 */

@Slf4j
@RestController
@RequestMapping(ModuleConst.MODULE_ROOT + "/avl/rest")
@RequiredArgsConstructor
public class SupplierAvlRestController {
    private final SupplierAvlLogic supplierAvlLogic;
    private final DictClient dictClient;

    /**
     * 供应商avl清单列表数据
     *
     * @param query 查询参数
     * @return
     */
    @GetMapping("list")
    public PageView list(SupplierAvlQuery query) {
        return supplierAvlLogic.getList(query);
    }

    /**
     * 保存&更新
     *
     * @param saveDTO avl清单主数据
     * @throws Exception
     */
    @PostMapping("save")
    public ResponseEntity save(@RequestBody SupplierAvlSaveDTO saveDTO) {
        supplierAvlLogic.saveOrUpdate(saveDTO);
        return ResponseEntity.ok().build();
    }

    /**
     * 删除
     *
     * @param ids 要删除的ids
     * @return
     */
    @PostMapping("remove")
    public ResponseEntity remove(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        supplierAvlLogic.remove(idList);
        return ResponseEntity.ok().build();
    }

    /**
     * 同步至Mes
     *
     * @param ids 同步至Mes
     * @return
     */
    @PostMapping("pushToMes")
    public ResponseEntity pushToMes(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        supplierAvlLogic.pushAvlToMes(idList);
        return ResponseEntity.ok().build();
    }


    /**
     * 供应商avl清单列表导入
     *
     * @param file 导入的列信息
     */
    @PostMapping("import")
    public ResponseEntity importData(@RequestParam(value = "file") MultipartFile file) {
        supplierAvlLogic.avlImportData(file);
        return ResponseEntity.ok().build();
    }

    /**
     * 导出Excel
     *
     * @param response
     * @param exportFiled 导出列
     * @param queryStr    导出查询参数
     */
    @PostMapping("/exportExcel")
    public void reportExportExcel(HttpServletResponse response, String exportFiled, String queryStr) throws
            IOException  {
        //查询国系下拉列表。
        final List<DictDTO> countriesDict = dictClient.getDicByType(DictCode.COUNTRY_SERIES.getCode());
        List<String> fieldValues = new ArrayList<>();
        fieldValues.add("");
        fieldValues.addAll(countriesDict.stream()
                .map(DictDTO::getName)
                .collect(Collectors.toList()));

        List<DictDTO> dictList = dictClient.getDicByType(DictCode.MSL_LEVEL.getCode());
        List<String> mslList = dictList.stream()
                .map(DictDTO::getName)
                .collect(Collectors.toList());

        List<ExportDataDTO> exportDataDTOS = JSON.parseArray(exportFiled, ExportDataDTO.class);
        exportDataDTOS.forEach(exportDataDTO -> {
            //如果字段为国系，则生成下拉框
            if ("countryName".equals(exportDataDTO.getField())){
                //插入下拉框数据，也可以从字典里取数据，只插入字典名称
                exportDataDTO.setSelectList(fieldValues);
            }
            if ("createTime".equals(exportDataDTO.getField())){
                //设置列宽，为啥不生效
                exportDataDTO.setWidth(2400);
//                ExportDataDTO.builder().title("创建时间").field("createTime").exportDateFormatter("createTime").build();
            }
            //如果字段为msl等级，则生成下拉框选项
            if ("mslName".equals(exportDataDTO.getField())){
                exportDataDTO.setSelectList(mslList);
            }
        });
        // 查询数据列表，直接调用列表的查询，无需特殊改动
        SupplierAvlQuery query = JSON.parseObject(queryStr, SupplierAvlQuery.class);
        //如果是供应商登录导出
        if (LoginUtil.isSupplier()) {
            query.setSupplierId(LoginUtil.getSupplierId());
        }
        List<SupplierAvlBaseDTO> exportData = supplierAvlLogic.listAll(query);
        exportData.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getSynToMes())) {
                item.setSynToMes(item.getSynToMes().equals("1")?"是":"否");
            }
        });
        EasyExcelUtils.trendsModelWrite(response,"供应商AVL清单-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN),"sheet", exportData, exportDataDTOS);
    }

    @GetMapping("getMPN")
    public ResponseEntity getMPN(String supplierCode, String materialCode, String manufacturer) {
        return ResponseEntity.ok(supplierAvlLogic.getMPN(supplierCode, materialCode, manufacturer));
    }

    @GetMapping("getAvlItem")
    public ResponseEntity getAvlItem(String materialCode) {
        return ResponseEntity.ok(supplierAvlLogic.getAvlItems(materialCode));
    }

}
