package com.jwipc.supplier.controller.pc;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson2.JSON;
import com.jwipc.log.annotation.AuditLogInter;
import com.jwipc.page.PageView;
import com.jwipc.supplier.dto.*;
import com.jwipc.supplier.logic.SupplierPurchaseCategoryLogic;
import com.jwipc.supplier.model.query.SupplierPurchaseCategoryBaseQuery;
import com.jwipc.supplier.model.query.SupplierPurchaseCategorySelectQuery;
import com.jwipc.sys.client.*;
import com.jwipc.sys.client.dto.CompanyDTO;
import com.jwipc.sys.client.dto.PurchaseGroupDTO;
import com.jwipc.sys.client.dto.PurchaseOrgDTO;
import com.jwipc.sys.client.dto.TaxDTO;
import com.jwipc.util.EasyExcelUtils;
import com.jwipc.util.ExcelDictConverter;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

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

/**
 * <p> </p>
 *
 * @author ZhangJie
 * @version 1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping(MODULE_ROOT + "/purchaseCategory/rest")
@RequiredArgsConstructor
public class SupplierPurchaseCategoryRestController {
    private final SupplierPurchaseCategoryLogic supplierPurchaseCategoryLogic;
    private final DictClient dictClient;
    private final TaxClient taxClient;
    private final CompanyClient companyClient;
    private final PurchaseOrgClient purchaseOrgClient;
    private final PurchaseGroupClient purchaseGroupClient;

    @GetMapping("listByInvitation")
    public ResponseEntity listByInvitation(Long invitationId) {
        return ResponseEntity.ok(supplierPurchaseCategoryLogic.listByInvitation(invitationId));
    }

    @GetMapping("listSupplier")
    public PageView listSupplier(SupplierPurchaseCategorySelectQuery query)
    {
        return supplierPurchaseCategoryLogic.listSupplier(query);
    }

    @PostMapping("saveAuthFile")
    public ResponseEntity saveAuthFile(Long id, String fileIds) {
        supplierPurchaseCategoryLogic.saveAuthFile(id, fileIds);
        return ResponseEntity.ok().build();
    }

    /**
     * 保存现场认证附件
     *
     * @param id      品类id
     * @param fileIds 附件id 逗号分割
     * @return
     */
    @PostMapping("saveOnSiteAuthenticationFile")
    public ResponseEntity saveOnSiteAuthenticationFile(Long id, String fileIds) {
        supplierPurchaseCategoryLogic.saveOnSiteAuthenticationFile(id, fileIds);
        return ResponseEntity.ok().build();
    }

    /**
     * 潜在供应商列表接口
     *
     * @param query 查询参数
     * @return
     */
    @GetMapping("potentialList")
    public PageView potentialList(SupplierPurchaseCategoryBaseQuery query) {
        return supplierPurchaseCategoryLogic.getPotentialList(query);
    }

    @PostMapping("potentialExport")
    public void potentialExport(HttpServletResponse response, String exportFiled, String queryStr) throws IOException {
        final SupplierPurchaseCategoryBaseQuery query = JSON.parseObject(queryStr,
                SupplierPurchaseCategoryBaseQuery.class);
        // 创建数据列表
        List<SupplierPotentialListDTO> forExport = supplierPurchaseCategoryLogic.getPotentialAllList(query);
        //动态导出工具类，只需要修改导出excel名称
        EasyExcelUtils.trendsModelWrite(response,
                "潜在供应商数据-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN), "sheet", forExport,
                exportFiled);
    }

    /**
     * 小批量供应商列表接口
     *
     * @param query 查询参数
     * @return
     */
    @GetMapping("smallbatchList")
    public PageView smallbatchList(SupplierPurchaseCategoryBaseQuery query) {
        return supplierPurchaseCategoryLogic.getSmallbatchList(query);
    }

    @AuditLogInter(value = "导出信息数据", module = "小批量供应商")
    @PostMapping("smallbatchExport")
    public void smallbatchExport(HttpServletResponse response, String exportFiled, String queryStr) throws IOException {
        final SupplierPurchaseCategoryBaseQuery query = JSON.parseObject(queryStr,
                SupplierPurchaseCategoryBaseQuery.class);
        // 创建数据列表
        List<SupplierSmallbatchListDTO> forExport = supplierPurchaseCategoryLogic.getSmallbatchAllList(query);
        //动态导出工具类，只需要修改导出excel名称
        EasyExcelUtils.trendsModelWrite(response,
                "小批量供应商数据-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN), "sheet", forExport,
                exportFiled);
    }

    /**
     * 合格供应商列表接口
     *
     * @param query 查询参数
     * @return
     */
    @AuditLogInter(value = "首页查询列表", module = "合格供应商")
    @GetMapping("qualifiedList")
    public PageView qualifiedList(SupplierPurchaseCategoryBaseQuery query) {
        return supplierPurchaseCategoryLogic.getQualifiedList(query);
    }
    @AuditLogInter(value = "导出数据", module = "合格供应商")
    @PostMapping("qualifiedExport")
    public void qualifiedExport(HttpServletResponse response, String exportFiled, String queryStr) throws IOException {
        final SupplierPurchaseCategoryBaseQuery query = JSON.parseObject(queryStr,
                SupplierPurchaseCategoryBaseQuery.class);
        // 创建数据列表
        List<SupplierQualifiedListDTO> forExport = supplierPurchaseCategoryLogic.getQualifiedAllList(query);
        //动态导出工具类，只需要修改导出excel名称
        EasyExcelUtils.trendsModelWrite(response,
                "合格供应商数据-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN), "sheet", forExport,
                exportFiled);
    }


    /**
     * 供应商主数据列表接口
     *
     * @param query 查询参数
     * @return
     */
    @AuditLogInter(value = "首页查询列表", module = "供应商主数据")
    @GetMapping("mainDataList")
    public PageView mainDataList(SupplierPurchaseCategoryBaseQuery query) {
        return supplierPurchaseCategoryLogic.getMainDataList(query);
    }

    /**
     * 采购品类对应的物料认证列表数据
     *
     * @param id 查询参数
     * @return
     */
    @GetMapping("demo")
    public PageView demo(Long id) {
        return supplierPurchaseCategoryLogic.getDemo(id);
    }

    /**
     * 转小批量
     *
     * @param ids
     * @return
     */
    @PostMapping("convertSmallbatch")
    public ResponseEntity convertSmallbatch(String ids) {
        supplierPurchaseCategoryLogic.convertSmallbatch(ids);
        return ResponseEntity.ok().build();
    }

    /**
     * 导入供应商抛OA审批
     *
     * @param ids
     * @return
     */
    @PostMapping("importSupplierApproval")
    public ResponseEntity importSupplierApproval(String ids) {
        supplierPurchaseCategoryLogic.importSupplierApproval(ids);
        return ResponseEntity.ok().build();
    }

    /**
     * 转合格
     *
     * @param id
     * @param demoIds 物料认证主键，多个逗号分割
     * @return
     */
    @PostMapping("convertQualified")
    public ResponseEntity convertQualified(Long id, String demoIds) {
        supplierPurchaseCategoryLogic.convertQualified(id, demoIds);
        return ResponseEntity.ok().build();
    }

    /**
     * 保存平类和物料认证的关联数据
     *
     * @param id      品类id
     * @param demoIds 物料认证主键，多个逗号分割
     * @return
     */
    @PostMapping("sumbmitDemoRel")
    public ResponseEntity sumbmitDemoRel(Long id, String demoIds) {
        supplierPurchaseCategoryLogic.sumbmitDemoRel(id, demoIds);
        return ResponseEntity.ok().build();
    }

    /**
     * 保存优先选项
     *
     * @param id 品类id
     * @return
     */
    @PostMapping("updateFirst")
    public ResponseEntity updateFirst(Long id) {
        supplierPurchaseCategoryLogic.updateFirst(id);
        return ResponseEntity.ok().build();
    }

    /**
     * 新增加供应商品类信息
     *
     * @param supplierPurchaseCategoryBaseDTO
     * @return
     */
    @PostMapping("saveOrUpdate")
    public ResponseEntity saveOrUpdate(@RequestBody SupplierPurchaseCategoryBaseDTO supplierPurchaseCategoryBaseDTO) {
        supplierPurchaseCategoryLogic.saveOrUpdate(supplierPurchaseCategoryBaseDTO);
        return ResponseEntity.ok().build();
    }

    @PostMapping("updateFreeze")
    public ResponseEntity updateFreeze(@RequestBody Set<String> purchaseOrgCodes, Long supplierId, Integer state) {
        supplierPurchaseCategoryLogic.updateFreeze(purchaseOrgCodes, supplierId, state);
        return ResponseEntity.ok().build();
    }

    @AuditLogInter(value = "导出信息数据", module = "供应商主数据")
    @PostMapping("export")
    public void export(HttpServletResponse response, String exportFiled, String queryStr) throws IOException {
        final SupplierPurchaseCategoryBaseQuery query = JSON.parseObject(queryStr,
                SupplierPurchaseCategoryBaseQuery.class);
        // 创建数据列表
        List<SupplierMainDataListDTO> forExport = supplierPurchaseCategoryLogic.findForMainDataExport(query);
        //动态导出工具类，只需要修改导出excel名称
        EasyExcelUtils.trendsModelWrite(response,
                "供应商主数据-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN), "sheet", forExport,
                exportFiled);
    }
    @AuditLogInter(value = "导出银行信息数据", module = "供应商主数据")
    @GetMapping("exportBankdm")
    public void exportBankdm(String q, HttpServletResponse response) throws
            IOException
    {
        final SupplierPurchaseCategoryBaseQuery query = JSON.parseObject(q,
                SupplierPurchaseCategoryBaseQuery.class);
        List<SupplierBankDMDTO> list = supplierPurchaseCategoryLogic.findForBankdmReportExport(query);
        // 设置响应头信息
        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文件
        Function<String, Map<String, String>> dictFunction = (type) -> {
            if (type.equals("purchaseGroupCode")) {
                final List<PurchaseGroupDTO> all = purchaseGroupClient.getAll();
                return all.stream().collect(Collectors.toMap(PurchaseGroupDTO::getPurchaseGroupCode, PurchaseGroupDTO::getPurchaseGroupName));
            } else {
                Map<String, String> dict = dictClient.getDicMapByType(type);
                return dict;
            }
        };
        EasyExcel.write(response.getOutputStream(), SupplierBankDMDTO.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .registerConverter(new ExcelDictConverter(dictFunction)).sheet("Sheet1").doWrite(list);
    }
    @AuditLogInter(value = "导出品类信息数据", module = "供应商主数据")
    @GetMapping("exportProducttypedm")
    public void exportProducttypedm(String q, HttpServletResponse response) throws
            IOException
    {
        final SupplierPurchaseCategoryBaseQuery query = JSON.parseObject(q,
                SupplierPurchaseCategoryBaseQuery.class);
        List<SupplierProductTypeDMDTO> list = supplierPurchaseCategoryLogic.findForProducttypedmReportExport(query);
        // 设置响应头信息
        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文件
        Function<String, Map<String, String>> dictFunction = (type) -> {
            if (type.equals("tax_code")) {
                final List<TaxDTO> all = taxClient.getAll();
                return all.stream().collect(Collectors.toMap(TaxDTO::getTaxCode, TaxDTO::getTaxName));
            } else if (type.equals("company_code")) {
                final List<CompanyDTO> all = companyClient.getAll();
                return all.stream().collect(Collectors.toMap(CompanyDTO::getCompanyCode, CompanyDTO::getCompanyName));
            } else if (type.equals("purchase_org")) {
                final List<PurchaseOrgDTO> all = purchaseOrgClient.getAll();
                return all.stream().collect(
                        Collectors.toMap(PurchaseOrgDTO::getPurchaseOrgCode, PurchaseOrgDTO::getPurchaseOrgDesc));
            } else {
                Map<String, String> dict = dictClient.getDicMapByType(type);
                return dict;
            }
        };
        EasyExcel.write(response.getOutputStream(), SupplierProductTypeDMDTO.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .registerConverter(new ExcelDictConverter(dictFunction)).sheet("Sheet1").doWrite(list);
    }

    @AuditLogInter(value = "导出联系人信息数据", module = "供应商主数据")
    @GetMapping("exportContacts")
    public void exportContacts(String q, HttpServletResponse response) throws IOException {
        final SupplierPurchaseCategoryBaseQuery query = JSON.parseObject(q,
                SupplierPurchaseCategoryBaseQuery.class);
        List<SupplierContactsDMDTO> list = supplierPurchaseCategoryLogic.findForContactdmReportExport(query);
        // 设置响应头信息
        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文件
        Function<String, Map<String, String>> dictFunction = (type) -> {
            if (type.equals("company_code")) {
                final List<CompanyDTO> all = companyClient.getAll();
                return all.stream().collect(Collectors.toMap(CompanyDTO::getCompanyCode, CompanyDTO::getCompanyName));
            } else {
                Map<String, String> dict = dictClient.getDicMapByType(type);
                return dict;
            }
        };
        EasyExcel.write(response.getOutputStream(), SupplierContactsDMDTO.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .registerConverter(new ExcelDictConverter(dictFunction)).sheet("Sheet1").doWrite(list);
    }

    @AuditLogInter(value = "导出总表信息数据", module = "供应商主数据")
    @GetMapping("exportSupplierReport")
    public void exportSupplierReport(String q,HttpServletResponse response) throws IOException{
        final SupplierPurchaseCategoryBaseQuery query = JSON.parseObject(q,
                SupplierPurchaseCategoryBaseQuery.class);
        List<SupplierReportDTO> list = supplierPurchaseCategoryLogic.findForSupplierReportExport(query);
        // 设置响应头信息
        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.write(response.getOutputStream(), SupplierReportDTO.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet("Sheet1").doWrite(list);
    }

    @RequestMapping("/findCurryCode")
    public String findCurryCode(String supplierCode) {
        return supplierPurchaseCategoryLogic.findCurryCode(supplierCode);
    }

    @PostMapping("updateReportFlag")
    public ResponseEntity updateReportFlag(String ids) {
        supplierPurchaseCategoryLogic.updateReportFlag(ids);
        return ResponseEntity.ok().build();
    }

    @PostMapping("updateSqeReject")
    public ResponseEntity updateSqeReject(String ids,String remark) {
        supplierPurchaseCategoryLogic.updateSqeReject(ids,remark);
        return ResponseEntity.ok().build();
    }

    @GetMapping("getCompanyCategoryAndSupplierIds")
    public ResponseEntity getCompanyCategoryAndSupplierIds(String companyCode, String category,
                                                           String supplierIds)
    {
        List<SupplierPurchaseCategoryBaseDTO> supplierPurchaseCategoryBaseDTOS =
                supplierPurchaseCategoryLogic.getCompanyCategoryAndSupplierIds(
                        companyCode, category, supplierIds);
        return ResponseEntity.ok(supplierPurchaseCategoryBaseDTOS);
    }

    @GetMapping("getCompanyAndSupplierCode")
    public ResponseEntity getCompanyAndSupplierCode(String companyCode, String supplierCode)
    {
        SupplierPurchaseCategoryBaseDTO supplierPurchaseCategoryBaseDTOS =
                supplierPurchaseCategoryLogic.getCompanyAndSupplierCode(
                        companyCode, supplierCode);
        return ResponseEntity.ok(supplierPurchaseCategoryBaseDTOS);
    }
}
