package com.jeeplus.assess.invoice.controller;

import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.aop.demo.annotation.DemoMode;
import com.jeeplus.assess.projectRecords.Utils.EasyPoiUtil;
import com.jeeplus.common.excel.ExcelOptions;
import com.jeeplus.common.excel.ExportMode;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.assess.invoice.service.FinanceInvoiceService;
import com.jeeplus.assess.invoice.service.dto.FinanceDTO;
import com.jeeplus.assess.invoice.service.dto.FinanceInvoiceDTO;
import com.jeeplus.assess.invoice.service.dto.FinanceInvoiceDetailDTO;
import com.jeeplus.logging.annotation.ApiLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Api("财务管理-发票")
@RestController
@RequestMapping(value = "/finance/invoice")
@Log4j2
public class FinanceInvoiceController {

    @Resource
    private FinanceInvoiceService financeInvoiceService;

    /**
     * 查询发票列表
     * @param financeInvoiceDTO
     * @param page
     * @return
     * @throws Exception
     */
    @ApiLog("查询发票列表")
    @PreAuthorize("hasAuthority('finance:invoice:list')")
    @GetMapping("list")
    public ResponseEntity<IPage<FinanceInvoiceDTO>> data(FinanceInvoiceDTO financeInvoiceDTO, Page<FinanceInvoiceDTO> page) throws Exception {
        IPage<FinanceInvoiceDTO> result = new Page<FinanceInvoiceDTO>();
        result = financeInvoiceService.findList (page,financeInvoiceDTO);
        return ResponseEntity.ok (result);
    }

    /**
     * 查询发票数据
     * @param id
     * @return
     */
    @ApiLog("查询发票数据")
    @PreAuthorize ("hasAnyAuthority('finance:invoice:view','finance:invoice:add','finance:invoice:edit')")
    @GetMapping("queryById")
    public ResponseEntity queryById(@RequestParam("id") String id) {
        FinanceInvoiceDTO financeInvoiceDTO = financeInvoiceService.queryById ( id );
        return ResponseEntity.ok (financeInvoiceDTO);
    }

    /**
     * 查询发票号是否存在
     * @param number
     * @return
     */
    @ApiLog("查询发票号是否存在")
    @GetMapping("queryByNumber")
    public ResponseEntity queryByNumber(@RequestParam("number") String number, @RequestParam(value="id", required = false) String id) {
        Boolean bool = financeInvoiceService.queryByNumber ( number, id );
        return ResponseEntity.ok (bool);
    }

    /**
     * 保存发票数据
     * @param financeInvoiceDTO
     * @return
     */
    @ApiLog(value = "修改/新增发票数据")
    @PreAuthorize("hasAnyAuthority('finance:invoice:add','finance:invoice:edit')")
    @PostMapping("save")
    public ResponseEntity save(@Valid @RequestBody FinanceInvoiceDTO financeInvoiceDTO) throws Exception {
        financeInvoiceService.saveInvoice(financeInvoiceDTO);
        return ResponseEntity.ok ("操作成功");
    }

    /**
     * 保存发票数据-流程
     * @param financeInvoiceDTO
     * @return
     */
    @ApiLog(value = "保存发票数据-流程")
    @PreAuthorize("hasAnyAuthority('finance:invoice:add','finance:invoice:edit')")
    @PostMapping("saveForm")
    public ResponseEntity saveForm(@Valid @RequestBody FinanceInvoiceDTO financeInvoiceDTO) throws Exception {
        String id = financeInvoiceService.saveForm(financeInvoiceDTO);
        return ResponseUtil.newInstance().add("businessTable", "finance_invoice").add("businessId", id).ok ("操作成功");
    }

    /**
     * 作废发票数据-流程
     * @param financeInvoiceDTO
     * @return
     */
    @ApiLog(value = "作废发票数据-流程")
    @PreAuthorize("hasAnyAuthority('finance:invoice:add','finance:invoice:edit')")
    @PostMapping("saveFormInvalid")
    public ResponseEntity saveFormInvalid(@Valid @RequestBody FinanceInvoiceDTO financeInvoiceDTO) throws Exception {
        String id = financeInvoiceService.saveFormInvalid(financeInvoiceDTO);
        return ResponseUtil.newInstance().add("businessTable", "finance_invoice_invalid").add("businessId", id).ok ("操作成功");
    }

    /**
     * 根据发票作废数据的id查询发票id
     * @param id
     * @return
     */
    @GetMapping("queryIdByInvalidId")
    @ApiOperation(value = "查询发票号是否存在")
    public ResponseEntity<FinanceDTO> queryIdByInvalidId(@RequestParam String id) {
        String businessId = financeInvoiceService.queryIdByInvalidId ( id );
        FinanceDTO financeDTO = new FinanceDTO();
        financeDTO.setBusinessId(businessId);
        return ResponseEntity.ok(financeDTO);
    }

    /**
     * 删除附件类型
     * @param ids
     * @return
     */
    @ApiLog(value = "删除附件类型")
    @PreAuthorize ("hasAuthority('finance:invoice:del')")
    @DeleteMapping("delete")
    public ResponseEntity delete(String ids) {
        return financeInvoiceService.deleteByIds(ids);
    }

    /**
     * 根据id修改状态值status
     * @param dto
     * @return
     */
    @ApiOperation(value = "根据id修改状态值status")
    @PostMapping(value = "/updateStatusById")
    public ResponseEntity<String> updateStatusById(@RequestBody FinanceInvoiceDTO dto) {
        String s = financeInvoiceService.updateStatusById(dto);
        return ResponseEntity.ok(s);
    }

    /**
     * 确认收款
     * @param dto
     * @return
     */
    @ApiOperation(value = "确认收款")
    @PostMapping(value = "/isReceivables")
    public ResponseEntity<String> isReceivables(@RequestBody FinanceInvoiceDTO dto) {
        String s = financeInvoiceService.isReceivables(dto);
        return ResponseEntity.ok(s);
    }

    /**
     * 下载发票明细导入模板
     *
     * @param response
     * @return
     */
    @GetMapping("/importDetail/template")
    @ApiOperation(value = "下载模板")
    public void importFileTemplate(HttpServletResponse response, HttpServletRequest request) {
        try {
            InputStream inputStream = this.getClass().getResourceAsStream("/dot/发票明细导入模板.xlsx");
            //强制下载不打开
            response.setContentType("application/force-download");
            OutputStream out = response.getOutputStream();
            //使用URLEncoder来防止文件名乱码或者读取错误
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("finance_invoice_detail_template.xlsx", "UTF-8"));
            int b = 0;
            byte[] buffer = new byte[1000000];
            while (b != -1) {
                b = inputStream.read(buffer);
                if (b != -1) out.write(buffer, 0, b);
            }
            inputStream.close();
            out.close();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入发票明细数据
     *
     * @return
     */
    @DemoMode
    @PostMapping("/importDetail")
    @ApiLog(value = "导入发票明细数据excel")
    public ResponseEntity importDetail(MultipartFile file, HttpServletRequest request) throws IOException {

        ArrayList<FinanceInvoiceDetailDTO> arrayList = new ArrayList<>();
        HashMap<String,String> hashMap = new HashMap<>();

        List<FinanceInvoiceDetailDTO> listA = new ArrayList<>();
        //获取sheet
        listA = EasyPoiUtil.importExcel(file, 0, 1, FinanceInvoiceDetailDTO.class);
        //去除excel中的空行
        listA = getExcelList(listA);
        //导入前检测数据
        String resultA = financeInvoiceService.importDecide(listA, arrayList, hashMap);
        if(StringUtils.isNotBlank(resultA)){
            //有返回值，说明导入的数据不正确。向用户抛提示
            return ResponseEntity.badRequest().body  (resultA);
        }
        //判断文件中是否有重复的发票号
        if(hashMap.size() != listA.size()){
            return ResponseEntity.badRequest().body  ("文件中存在重复的发票号");
        }

        return ResponseEntity.ok(arrayList);
    }

    /**
     * 去除excel中的空行
     * @param list
     * @return
     */
    public ArrayList<FinanceInvoiceDetailDTO> getExcelList(List<FinanceInvoiceDetailDTO> list){

        ArrayList<FinanceInvoiceDetailDTO> financeInvoiceDetailDTOS = new ArrayList<>();

        list.stream().forEach(item->{
            if(objectCheckIsNull(item)){
                financeInvoiceDetailDTOS.add(item);
            }
        });

        return financeInvoiceDetailDTOS;
    }

    public static boolean objectCheckIsNull(Object object) {
        boolean flag = false; //定义返回结果，默认为true

        if (Objects.isNull(object)) {
            flag = false;
        } else {
            Class clazz = (Class) object.getClass(); // 得到类对象
            Field fields[] = clazz.getDeclaredFields(); // 得到所有属性
            for (Field field : fields) {
                if("serialVersionUID".equals(field.getName()) || "BIZ_CODE".equalsIgnoreCase(field.getName())){
                    continue;
                }
                field.setAccessible(true);
                Object fieldValue = null;
                try {
                    fieldValue = field.get(object); //得到属性值
                    Type fieldType = field.getGenericType();//得到属性类型
                    String fieldName = field.getName(); // 得到属性名
                    log.info("属性类型：" + fieldType + ",属性名：" + fieldName + ",属性值：" + fieldValue);
                } catch (IllegalArgumentException e) {
                    log.error(e.getMessage(), e);
                } catch (IllegalAccessException e) {
                    log.error(e.getMessage(), e);
                }
                if (fieldValue != null && fieldValue != "") {  //只要有一个属性值不为null 就返回false 表示对象不为null
                    flag = true;
                    break;
                }
            }
        }

        return flag;
    }

    /**
     * 导出
     *
     * @param financeInvoiceDTO
     * @param response
     * @throws Exception
     */
//    @GetMapping("/exportFile")
//    @ApiOperation(value = "导出")
//    public void exportList(FinanceInvoiceDTO financeInvoiceDTO,Page<FinanceInvoiceDTO> page, HttpServletResponse response) throws Exception {
//        List<FinanceInvoiceDTO> infos = financeInvoiceService.exportList(page,financeInvoiceDTO);
//        EasyPoiUtil.exportExcel(infos, "发票列表数据",  "发票列表数据", FinanceInvoiceDTO.class, "发票数据导出", response );
//    }



    @ApiLog(value = "导出发票数据")
    @GetMapping("export")
    // @PreAuthorize ("hasAuthority('finance:invoice:export')")
    @ApiOperation(value = "导出发票数据")
    public void exportFile(FinanceInvoiceDTO financeInvoiceDTO, Page <FinanceInvoiceDTO> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename();
        String sheetName = options.getSheetName();
        List<FinanceInvoiceDTO> result = new ArrayList<>();
        if ( ExportMode.current.equals ( options.getMode() ) ) {
            result = financeInvoiceService.findList (page,financeInvoiceDTO).getRecords();
        } else if (ExportMode.selected.equals ( options.getMode() )) {
            result = financeInvoiceService.findList (page,financeInvoiceDTO).getRecords().stream ( ).filter ( item ->
                    options.getSelectIds ( ).contains ( item.getId ( ) )
            ).collect ( Collectors.toList ( ) );
        } else {
            page.setSize (-1);
            page.setCurrent (0);
            result = financeInvoiceService.findList (page,financeInvoiceDTO).getRecords();
        }
        EasyPoiUtil.exportExcel ( result, sheetName,  sheetName, FinanceInvoiceDTO.class, fileName, response );

    }
}
