package com.awspaas.user.apps.donenow_ctt.controller;

import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.commons.formfile.model.delegate.FormFile;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.bind.annotation.Controller;
import com.actionsoft.bpms.server.bind.annotation.Mapping;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.awspaas.user.apps.donenow_ctt.QrCodeReaderUtil;
import com.awspaas.user.apps.donenow_ctt.service.InvoiceDealDto;
import com.awspaas.user.apps.donenow_ctt.service.InvoiceService;
import org.apache.commons.lang3.StringUtils;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.List;

/**
 * 账单管理
 */
@Controller
public class invoiceController {
    /**
     * 预览发票
     * @param uc
     * @param accDeduIds
     * @return
     */
    @Mapping("com.awspaas.user.apps.donenow_ctt.preview_invoice")
    public ResponseObject previewInvoice(UserContext uc, String accDeduIds) {
        InvoiceDealDto invoiceDealDto = new InvoiceDealDto();
        invoiceDealDto.setIds(accDeduIds);
        String result = InvoiceService.getInstance().processInvoice(uc, accDeduIds, invoiceDealDto, false);

        if (StringUtils.isNotBlank(result) && !result.contains("成功")) return ResponseObject.newErrResponse(result);


        return ResponseObject.newOkResponse();
    }


    /**
     * 处理发票
     * @param uc
     * @param accDeduIds
     * @return
     */
    @Mapping("com.awspaas.user.apps.donenow_ctt.deal_invoice")
    public ResponseObject dealInvoice(UserContext uc, String accDeduIds, String startDate, String endDate) {
        InvoiceDealDto invoiceDealDto = new InvoiceDealDto();
        invoiceDealDto.setIds(accDeduIds);

        SDK.getLogAPI().consoleInfo("处理账单：" + accDeduIds + "账单开始时间：" + startDate + "账单结束时间：" + endDate);

        if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate))
            return ResponseObject.newErrResponse("请选择账单时间");

        invoiceDealDto.setDateRangeFromStr(startDate);
        invoiceDealDto.setDateRangeToStr(endDate);

        String result = InvoiceService.getInstance().processInvoice(uc, accDeduIds, invoiceDealDto, true);
        if (StringUtils.isNotBlank(result) && !result.contains("成功"))
            return ResponseObject.newErrResponse(result);

        String bindid = result.replace("成功--", "");

        return ResponseObject.newOkResponse().put("BINDID", bindid);
    }


    /**
     * 发票更新
     * @param uc
     * @param invoiceIds
     * @return
     */
    @Mapping("com.awspaas.user.apps.donenow_ctt.invoiceUpdate")
    public ResponseObject invoiceUpdate(UserContext uc, String invoiceIds, String dealStatus) throws SQLException {
        if (StringUtils.isBlank(dealStatus))
            return ResponseObject.newErrResponse("请选择处理状态");
        if (StringUtils.isBlank(invoiceIds))
            return ResponseObject.newErrResponse("请选择");

        //已申请开票的账单不允许作废
        if (dealStatus.contains("作废发票"))
            for (String invoiceId : invoiceIds.split(",")) {
                if (StringUtils.isBlank(invoiceId))
                    return ResponseObject.newErrResponse("请选择账单");
                String sql = "SELECT d.ID,d.INVOICE_NO,COUNT(b.ID) CNT from BO_EU_DNCTT_INVOICE_PLAN a JOIN BO_EU_DNCTT_INVOICE_PLAN_DETAIL b ON a.BINDID=b.BINDID JOIN BO_EU_DNCTT_INVOICE_DETAIL c ON b.INVOICE_DETAIL_ID=c.ID JOIN BO_EU_DNCTT_INVOICE d ON c.BINDID=d.BINDID where d.ID=? GROUP BY d.ID,d.INVOICE_NO";
                RowMap invoice = DBSql.getMap(sql, new Object[]{invoiceId});
                if (invoice != null) {
                    if (invoice.getInt("CNT") > 0) {
                        return ResponseObject.newErrResponse(invoice.getString("INVOICE_NO") + "已申请开票的账单不允许作废");
                    }
                }
            }
        InvoiceService.getInstance().invoiceUpdate(uc, invoiceIds, dealStatus);
        return ResponseObject.newOkResponse();
    }


    /**
     * 删除发票计划
     * @param uc
     * @param bindids
     * @return
     */
    @Mapping("com.awspaas.user.apps.donenow_ctt.delInvoicePlan")
    public ResponseObject delInvoicePlan(UserContext uc, String bindids) {

        for (String bindid : bindids.split(",")) {
            SDK.getProcessAPI().deleteById(bindid, uc.getUID());
            SDK.getBOAPI().removeByBindId("BO_EU_DNCTT_INVOICE_PLAN_DETAIL", bindid);
            SDK.getBOAPI().removeByBindId("BO_EU_DNCTT_INVOICE_PLAN", bindid);
        }

        return ResponseObject.newOkResponse();
    }


    /**
     * 获取税率
     * @param uc
     * @param taxCategoryId
     * @return
     */
    @Mapping("com.awspaas.user.apps.donenow_ctt.getTaxRate")
    public ResponseObject getTaxRate(UserContext uc, String taxCategoryId) {
        String taxRate = DBSql.getString("select EXT1 from bo_eu_dnd_general where is_active=1 and closed=0 and general_table_id=44 AND OID=? AND ORGID=?", new Object[]{taxCategoryId, uc.getCompanyModel().getId()});
        return ResponseObject.newOkResponse().put("taxRate", taxRate);
    }


    /**
     * 识别二维码
     * @param uc
     * @return
     */
    @Mapping("com.awspaas.user.apps.donenow_ctt.QRReader")
    public ResponseObject QRReader(UserContext uc) {

        String qrContent = "";

        List<FormFile> jars = SDK.getBOAPI().getFiles("6da746b2-c84a-4502-ada8-f0b681d19ac3", "TU");
        for (FormFile jar : jars) {
            DCContext dcContext = SDK.getBOAPI().getFileDCContext(jar);

            Path source = Paths.get(dcContext.getFilePath());

            qrContent = qrContent + "\n" + QrCodeReaderUtil.readQrCode(source.toFile());

        }

        /*
        String sql = "SELECT * FROM APP_ACT_UI_OCR_FILE WHERE BOID=? AND BOFIELDNAME=? ORDER BY CREATEDATE DESC";
        RowMap rowMap = DBSql.getMap(sql, new Object[]{"boid", "fieldName"});

        DCContext dc = new DCContext(uc, DCProfileManager.getDCProfile(rowMap.getString("APPID"), "!ocr-ui-file-"), rowMap.getString("APPID"), rowMap.getString("ID"),  rowMap.getString("BOFIELDNAME"), rowMap.getString("FILENAME"));

        InputStream is = ReadDCFile.getInstance().read(dc);


        FormFileModel ffm = new FormFileModel();
        ffm.setAppId(rowMap.getString("APPID"));
        ffm.setBoId(rowMap.getString("BOID"));
        ffm.setBoItemName(rowMap.getString("BOFIELDNAME"));
        ffm.setBoName(rowMap.getString("BONAME"));
        //ffm.setProcessInstId(bindid);
        ffm.setFileName(rowMap.getString("FILENAME"));

        SDK.getBOAPI().upFile(ffm, is);
*/
        return ResponseObject.newOkResponse().put("qrContent", qrContent);
    }


    /**
     * 开票申请
     * @param uc
     * @param accDeduIds
     * @return
     */
    @Mapping("com.awspaas.user.apps.donenow_ctt.invoice_plan")
    public ResponseObject invoicePlan(UserContext uc, String accDeduIds) {
        InvoiceDealDto invoiceDealDto = new InvoiceDealDto();
        invoiceDealDto.setIds(accDeduIds);

        SDK.getLogAPI().consoleInfo("处理账单：" + accDeduIds);

        String result = InvoiceService.getInstance().invoicePlan(uc, accDeduIds);
        if (StringUtils.isNotBlank(result) && !result.contains("成功"))
            return ResponseObject.newErrResponse(result);

        String bindid = result.replace("成功--", "");

        return ResponseObject.newOkResponse().put("BINDID", bindid);
    }


}
