package com.xhpc.user.controller;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSSClient;
import com.xhpc.common.api.WorkOrderYuService;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.utils.DateUtils;
import com.xhpc.common.core.web.controller.BaseController;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.user.constant.InvoiceStatusConst;
import com.xhpc.user.domain.AllInvoiceOrdersRequest;
import com.xhpc.user.domain.AllInvoiceOrdersResponse;
import com.xhpc.user.domain.InvoiceToUserRequest;
import com.xhpc.user.domain.SpecificInvoiceWrap;
import com.xhpc.user.service.XhpcInvoiceService;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 关于后台处理发票的接口
 *
 * @author WH
 * @date 2021/12/20 10:47
 * @since version-1.0
 */
@RestController
@RequestMapping("/invoice")
public class XhpcInvoiceController extends BaseController {

    @Resource
    XhpcInvoiceService xhpcInvoiceService;
    @Resource
    Environment environment;
    @Resource
    WorkOrderYuService workOrderMessage;

    /**
     * 导出发票Excel接口
     *
     * @author WH
     * @date 2021/12/29 16:45
     * @since version-1.0
     */
    @GetMapping("/excel")
    public AjaxResult exportExcel(@RequestParam("invoiceIds") String invoiceIds, HttpServletResponse response) throws IOException {
        //处理字符串，转换成数组
        String[] ids = invoiceIds.split(",");
        List<String> resultList = Arrays.asList(ids);
        xhpcInvoiceService.exportExcel(resultList, response);
        return AjaxResult.success();
    }


    /**
     * 上传图片到阿里云接口
     *
     * @param invoicePdf 文件二进制对象
     * @return 该文件在阿里云中的地址
     *
     * @author WH
     * @date 2021/12/29 16:40
     * @since version-1.0
     */
    @PostMapping("/pdf")
    public AjaxResult uploadPdf(MultipartFile invoicePdf) throws IOException {

        String filename = "electricInvoice" + DateUtils.dateTimeNow() + ".pdf";
        // 上传文件到阿里云
        OSSClient ossClient = new OSSClient(environment.getProperty("oss.endpoint"), environment.getProperty("oss.access-key"), environment.getProperty("oss.secret-key"));
        // 放置到哪个块中去，key为目录，file为文件
        ossClient.putObject(environment.getProperty("oss.bucket-name"), environment.getProperty("file.aliyunPath") + filename, invoicePdf.getInputStream());
        ossClient.shutdown();
        // 返回上传到阿里云中的文件的uri地址
        String fileAddress = "/" + environment.getProperty("file.aliyunPath") + filename;
        return AjaxResult.success(fileAddress);
    }

    /**
     * 给指定用户开发票，开票完成之后将开出的电子发票发送至用户的接收邮箱
     * 如果失败，则标记发票为失败发票
     *
     * @author WH
     * @date 2021/12/22 12:03
     * @since version-1.0
     */
//    @Log(title = "用户提交发票状态", businessType = BusinessType.UPDATE)
//    @PatchMapping()
//    public AjaxResult invoiceToUser(@RequestBody InvoiceToUserRequest requestData) {
//        //前置条件
//        if (requestData.getInvoiceId() == null) {
//            return AjaxResult.error("必须上传发票id");
//        }
//        if (requestData.getStatus() == null || requestData.getStatus().equals(InvoiceStatusConst.INVOICING)) {
//            return AjaxResult.error("必须传递发票状态或发票状态不能为0");
//        }
//        //开失败发票
//        if (requestData.getStatus().equals(InvoiceStatusConst.FAIL)) {
//            try {
//                xhpcInvoiceService.failInvoiceToUser(requestData);
//                return AjaxResult.success();
//            } catch (Exception e) {
//                return AjaxResult.error("开失败发票失败");
//            }
//        } else {
//            //开成功发票
//            try {
//                //捕获参数异常
//                Boolean flagOfjudge = xhpcInvoiceService.invoiceToUser(requestData);
//                if (!flagOfjudge) {
//                    return AjaxResult.error("客户邮箱有误，邮件未发送成功，请通知用户修改邮箱");
//                }
//            } catch (Exception e) {
//                return AjaxResult.error(e.getMessage());
//            }
//        }
//        return AjaxResult.success();
//    }


    //@Log(title = "用户提交发票状态", businessType = BusinessType.UPDATE)
    @PostMapping("/add")
    public AjaxResult postInvoiceToUser(@RequestBody InvoiceToUserRequest requestData) {
        System.out.println("<<<<<<<<<<<<<<<<<<<进入开发票>>>>>>>>>>>>>>>>>>");
        System.out.println("<<<<<<<<<<<<<<<<<<<进入开发票>>>>>>>>>>>>>>>>>>");
        System.out.println("<<<<<<<<<<<<<<<<<<<进入开发票>>>>>>>>>>>>>>>>>>");
        //前置条件
        if (requestData.getInvoiceId() == null) {
            return AjaxResult.error("必须上传发票id");
        }
        if (requestData.getStatus() == null || requestData.getStatus().equals(InvoiceStatusConst.INVOICING)) {
            return AjaxResult.error("必须传递发票状态或发票状态不能为0");
        }
        //开失败发票
        if (requestData.getStatus().equals(InvoiceStatusConst.FAIL)) {
            try {
                xhpcInvoiceService.failInvoiceToUser(requestData);
                return AjaxResult.success();
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error("开失败发票失败");
            }
        } else {
            //开成功发票
            try {
                //捕获参数异常
                Boolean flagOfjudge = xhpcInvoiceService.invoiceToUser(requestData);
                if (!flagOfjudge) {
                    return AjaxResult.error("客户邮箱有误，邮件未发送成功，请通知用户修改邮箱");
                }
            } catch (Exception e) {
                return AjaxResult.error(e.getMessage());
            }
        }
        return AjaxResult.success();
    }


    /**
     * 用于在后台显示所有发票信息，包括待开发票和已开发票的信息
     *
     * @param requestData 前端传递过来的要查询的参数
     * @return AllInvoiceOrdersResponse 装着回显数据的包装类
     * @author WH
     * @date 2021/12/21 11:33
     * @since version-1.0
     */
    @GetMapping("/all-info")
    public AjaxResult findAllInvoiceOrders(AllInvoiceOrdersRequest requestData) {

        if (requestData.getCurrentPage() == null || requestData.getItems() == null) {
            return AjaxResult.error("当前页数、每页要显示的条数为必传递项");
        }
        AllInvoiceOrdersResponse allInvoiceOrdersResponse = xhpcInvoiceService.findAllInvoiceOrders(requestData);
        return AjaxResult.success(allInvoiceOrdersResponse);
    }

    /**
     * 用于在财务点击开票时，回显开票数据
     *
     * @param invoiceIdMap 一个存储着invoiceId的Map集合
     * @return specificInvoiceWrap 装着回显数据的包装类
     * @author WH
     * @date 2021/12/20 10:48
     * @since version-1.0
     */
    @GetMapping("/detail")
    public AjaxResult findSpecificInvoice(@RequestParam Map<String, Object> invoiceIdMap) {

        Long invoiceId = Long.valueOf(String.valueOf(invoiceIdMap.get("invoiceId")));
        SpecificInvoiceWrap specificInvoiceWrap = xhpcInvoiceService.findSpecificInvoice(invoiceId);
        if (specificInvoiceWrap == null) {
            return AjaxResult.error("要回显的订单发票id有误");
        }
        return AjaxResult.success(specificInvoiceWrap);
    }




    //@Scheduled(cron = "0 0/1 * * * ?")
    @GetMapping("/getInvoiceInfo")
    public void getInvoiceInfo(){
        logger.info("++++++++++++每1分钟，扫描一次，申请发票订单，自动生成工单++++++++++++++++");
        try {
            int invoiceInfo = xhpcInvoiceService.getInvoiceInfo();
            if(invoiceInfo>0){
                Date date = DateUtil.date();
                String format = DateUtil.format(date, "yyyy-MM-dd");
                R r = workOrderMessage.workOrderMessage(5, format);
                if(r.getCode()==200){
                    workOrderMessage.addNewOrder("5","有申请发票订单待处理","定时任务自动扫描申请发票订单","","","","");
                }
            }
        }catch (Exception e){
            logger.info("++++++++++++每1分钟，扫描一次，申请发票订单金额，自动生成工单异常++++++++++++++++");
            e.printStackTrace();
            //后期可以增加短信通知
        }
    }
}
