package com.jwipc.supplier.controller.pc;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jwipc.log.annotation.AuditLogInter;
import com.jwipc.page.PageView;
import com.jwipc.supplier.convert.SupplierBankConvert;
import com.jwipc.supplier.dto.SupplierBankDTO;
import com.jwipc.supplier.dto.SupplierImportDTO;
import com.jwipc.supplier.entity.Supplier;
import com.jwipc.supplier.entity.SupplierBank;
import com.jwipc.supplier.entity.SupplierBankInfo;
import com.jwipc.supplier.entity.SupplierPurchaseCategory;
import com.jwipc.supplier.logic.SupplierImportLogic;
import com.jwipc.supplier.logic.SupplierLogic;
import com.jwipc.supplier.model.query.SupplierSelectQuery;
import com.jwipc.supplier.service.ISupplierBankInfoService;
import com.jwipc.supplier.service.ISupplierBankService;
import com.jwipc.supplier.service.ISupplierPurchaseCategoryService;
import com.jwipc.supplier.service.ISupplierService;
import com.jwipc.sys.client.DictClient;
import lombok.RequiredArgsConstructor;
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.io.PrintWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.jwipc.constant.DictCode.CURRENCY;
import static com.jwipc.supplier.constant.ModuleConst.MODULE_ROOT;

/**
 * <p> </p>
 *
 * @author ZhangJie
 * @version 1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping(MODULE_ROOT + "/rest")
@RequiredArgsConstructor
public class SupplierRestController {
    private final SupplierLogic supplierLogic;
    private final SupplierImportLogic supplierImportLogic;

    private final ISupplierBankInfoService supplierBankInfoService;

    private final SupplierBankConvert supplierBankConvert;

    private final ISupplierBankService supplierBankService;

    private final DictClient dictClient;

    private final ISupplierService supplierService;

    @GetMapping("listForSelect")
    public PageView listForSelect(SupplierSelectQuery query) {
        return supplierLogic.getListForSelect(query);
    }

    @PostMapping("updateSamplePass")
    public ResponseEntity updateSamplePass(Long id) {
        supplierLogic.updateSamplePass(id);
        return ResponseEntity.ok().build();
    }

    @PostMapping("updateSignatureFlag")
    public ResponseEntity updateSignatureFlag(Long id) {
        supplierLogic.updateSignatureFlag(id);
        return ResponseEntity.ok().build();
    }

    @PostMapping("updateMonthFlagFlag")
    public ResponseEntity updateMonthFlagFlag(Long id) {
        supplierLogic.updateMonthFlagFlag(id);
        return ResponseEntity.ok().build();
    }

    @PostMapping("updateErpCode")
    public ResponseEntity updateErpCode(Long id, String erpCode) {
        supplierLogic.updateFormalCode(id, erpCode);
        return ResponseEntity.ok().build();
    }

    @PostMapping("updateApprovalOpinion")
    public ResponseEntity updateApprovalOpinion(Long id,String approvalOpinion) {
        supplierLogic.updateApprovalOpinion(id,approvalOpinion);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/find/bank")
    public ResponseEntity<?> findSupplierBankData(String supplierId) {
        final List<SupplierBankDTO> supplierBankDTOS = supplierLogic.findSupplierBankData(supplierId);
        return ResponseEntity.ok(supplierBankDTOS);
    }

    @AuditLogInter(value = "导入数据", module = "供应商主数据")
    @PostMapping("import")
    public void importSupplier(HttpServletResponse response,
                               @RequestParam(value = "file") MultipartFile file,@RequestParam(name = "supplierAttribution",required = true)String supplierAttribution) throws
            IOException
    {
        final Map<String,List<SupplierImportDTO>> stringListMap = supplierImportLogic.processor(file,supplierAttribution);
        List<SupplierImportDTO> s=stringListMap.get("false");
        if (CollUtil.isNotEmpty(s)) {
            // 设置响应头信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("供应商导入出错数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 使用EasyExcel导出Excel文件
            EasyExcel.write(response.getOutputStream(), SupplierImportDTO.class).sheet("Sheet1").doWrite(s);
        } else {

            //推送供应商银行信息到中间库
            List<SupplierImportDTO> processor=stringListMap.get("true");
            for(SupplierImportDTO supplierImportDTOsu:processor){
                String productCategory = supplierImportDTOsu.getProductCategory();
                if("客供品类".equals(productCategory)){
                    List<Supplier> suppliers = supplierService.list(new LambdaQueryWrapper<Supplier>()
                            .eq(Supplier::getSupplierName, supplierImportDTOsu.getSupplierName())
                            .eq(Supplier::getIsDeleted, false));
                    Long id = suppliers.get(0).getId();

                    String   currencyCode= supplierImportDTOsu.getCurrency();
                    final Map<String, String> dictCache = dictClient.getDicMapByType(CURRENCY.getCode());
                    String currencyName = dictCache.get(currencyCode);
                    final List<SupplierBank> supplierBanks = supplierBankService.list(
                            new LambdaQueryWrapper<SupplierBank>().eq(SupplierBank::getSupplierId,id ));
                    List<SupplierBankInfo> supplierBankInfos = supplierBankConvert.bank2SupplierBank(supplierBanks);
                    supplierBankInfos.stream().forEach(supplierBankInfo ->{
                        supplierBankInfo.setCurrencyCode(currencyCode);
                        supplierBankInfo.setCurrencyName(currencyName);
                        supplierBankInfo.setSupplierRegister(supplierImportDTOsu.getSupplierRegister());
                    });
                    //若中间表有此供应商银行信息，先清除数据再保存
                    if(CollectionUtil.isNotEmpty(supplierBanks)){
                        List<Long> ids=  new ArrayList<>();
                        ids.add(supplierBanks.get(0).getId());
                        supplierBankInfoService.deleteBySupplieId(ids);
                        supplierBankInfoService.saveSupplierBankInfos(supplierBankInfos);
                    }
                }
            }
            // 将JSON数据写入响应输出流
            PrintWriter out = response.getWriter();
            out.print(JSON.toJSONString(ResponseEntity.ok().build()));
            out.flush();
        }
    }

    @PostMapping("updatePurchaseGroup")
    public ResponseEntity updatePurchaseGroup(Long id, String purchaseGroup) {
        supplierLogic.updatePurchaseGroup(id, purchaseGroup);
        return ResponseEntity.ok().build();
    }

    @PostMapping("updateRecommender")
    public ResponseEntity updateRecommender(Long id, String recommenderCode) {
        supplierLogic.updateRecommender(id, recommenderCode);
        return ResponseEntity.ok().build();
    }

    @PostMapping("sendSupplierBank")
    public ResponseEntity sendSupplierBank(@RequestParam("id") List<Long> ids) {
        supplierLogic.findSupplierBankDatas(ids);
        return ResponseEntity.ok().build();
    }
}
