package cn.superdesk.uniorder.dubbo.provider.sys.notify;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.superdesk.uniorder.common.enums.sys.notify.SysNotifyCategoryDefaultEnum;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.numerical.AnBeanUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.security.dto.LoginSysUser;
import cn.superdesk.uniorder.dao.entity.sys.notify.SysNotify;
import cn.superdesk.uniorder.dto._constant.ResourceConstant;
import cn.superdesk.uniorder.dto.param.system.notify.SysNotifyClearByDatabaseRecordCriteria;
import cn.superdesk.uniorder.dto.param.system.notify.SysNotifyParam;
import cn.superdesk.uniorder.dubbo.consumer.websocket.WebSocketDubboCustomerService;
import cn.superdesk.uniorder.dubbo.consumer.websocket.biz.dto.W;
import cn.superdesk.uniorder.dubbo.facade.sys.notify.DubboSysNotifyService;
import cn.superdesk.uniorder.service._common.ProviderEnvConstantService;
import cn.superdesk.uniorder.service.sys.notify.SysNotifyService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: linjinyu
 * @Email linjinyu@avic-s.com
 * @CreateDate: 2021-03-01 17:37:17
 * @UpdateUser: linjinyu
 * @UpdateDate: 2021-03-01 17:37:17
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Service(version = "1.0.0", retries = -1, timeout = 10000)
public class DubboSysNotifyServiceImpl implements DubboSysNotifyService {

    private static Integer COMMON_TICK_TOCK = 0;

    @Autowired
    private SysNotifyService sysNotifyService;

    @Resource
    private ProviderEnvConstantService providerEnvConstantService;


    /****************************************** Dubbo Customer start ******************************************/
    @Autowired
    private WebSocketDubboCustomerService webSocketDubboCustomerService;

    /****************************************** Dubbo Customer   end ******************************************/


    private void commonNotifyInvoiceApplyCustomerScore(
            SysNotify sysNotify,
            LoginSysUser loginSysUser,
            String action,
            Integer tickTock) {

//		log.info("#commonNotify20210604# : \n{}", AnJsonUtils.toPrettyJson(loginSysUser));


//		String content = "TODO 未细化 notifyExportExcelInvoiceApplyFocusUnifiedDimGoods ...";
//		sysNotify.setContent(content);

//		sysNotify.setDetailLink("common/excel/export/f" + sysNotify.getContent());

        sysNotify.setToUserId(loginSysUser.getSysUserId());
        sysNotify.setToUserName(loginSysUser.getFullName());
        sysNotify.setIdentifier(loginSysUser.getSysUserName());
//		sysNotifyService.addSysNotify(sysNotify);

//		String identifier = sysNotify.getIdentifier();
//		identifier = "linjy";

        W<SysNotify> message = new W<>();

        message.setAction(action);
        message.setIdentifier(sysNotify.getIdentifier());
        message.setBody(sysNotify);
        message.setTickTock(tickTock);

        try {
            webSocketDubboCustomerService.sendPost(sysNotify.getIdentifier(), AnJsonUtils.toJson(message));
        } catch (Exception e) {

            // java.lang.reflect.InvocationTargetException
            // java.lang.RuntimeException
            e.printStackTrace();
        }
    }

    private static final String SYS_NOTIFY_ACTION_NOTIFY_INVOICE_APPLY_CUSTOMER_SCORE_FIELD_MAKE_INVOICE_STATUS = "notify/invoiceApplyCustomerScore/makeInvoiceStatus";

    public void notifyInvoiceApplyCustomerScoreFieldMakeInvoiceStatus(SysNotify sysNotify, LoginSysUser loginSysUser) {

        commonNotifyInvoiceApplyCustomerScore(
                sysNotify,
                loginSysUser,
                SYS_NOTIFY_ACTION_NOTIFY_INVOICE_APPLY_CUSTOMER_SCORE_FIELD_MAKE_INVOICE_STATUS, COMMON_TICK_TOCK
        );
    }

    private void commonNotifyExportExcel(
            SysNotify sysNotify,
            LoginSysUser loginSysUser,
            String action,
            Integer tickTock) {

//		log.info("#commonNotify20210604# : \n{}", AnJsonUtils.toPrettyJson(loginSysUser));


//		String content = "TODO 未细化 notifyExportExcelInvoiceApplyFocusUnifiedDimGoods ...";
//		sysNotify.setContent(content);

        sysNotify.setCategoryId(SysNotifyCategoryDefaultEnum.导出通知.getKey());

        sysNotify.setDetailLink("common/excel/export/f" + sysNotify.getContent());

        sysNotify.setToUserId(loginSysUser.getSysUserId());
        sysNotify.setToUserName(loginSysUser.getFullName());
        sysNotify.setIdentifier(loginSysUser.getSysUserName());

        sysNotifyService.addSysNotify(sysNotify);

//		String identifier = sysNotify.getIdentifier();
//		identifier = "linjy";

        W<SysNotify> message = new W<>();

        message.setAction(action);
        message.setIdentifier(sysNotify.getIdentifier());
        message.setBody(sysNotify);
        message.setTickTock(tickTock);

        try {
            webSocketDubboCustomerService.sendPost(sysNotify.getIdentifier(), AnJsonUtils.toJson(message));
        } catch (Exception e) {

            // java.lang.reflect.InvocationTargetException
            // java.lang.RuntimeException
            e.printStackTrace();
        }
    }


    /****************************************** 客户结算 开票申请 列表导出 Excel数据 start ******************************************/

    private static final String SYS_NOTIFY_ACTION_NOTIFY_EXPORT_INVOICE_APPLY_FOCUS_UNIFIED_DIM_GOODS = "notify/export/InvoiceApplyFocusUnifiedDimGoods";
    private static final String SYS_NOTIFY_ACTION_NOTIFY_EXPORT_INVOICE_APPLY_FOCUS_SCORE_DIM_CREDIT  = "notify/export/InvoiceApplyFocusScoreDimCredit";

    public void notifyExportExcelInvoiceApplyFocusUnifiedDimGoods(SysNotify sysNotify, LoginSysUser loginSysUser) {

        commonNotifyExportExcel(
                sysNotify,
                loginSysUser,
                SYS_NOTIFY_ACTION_NOTIFY_EXPORT_INVOICE_APPLY_FOCUS_UNIFIED_DIM_GOODS, COMMON_TICK_TOCK
        );
    }

    public void notifyExportExcelInvoiceApplyFocusScoreDimCredit(SysNotify sysNotify, LoginSysUser loginSysUser) {

        commonNotifyExportExcel(
                sysNotify,
                loginSysUser,
                SYS_NOTIFY_ACTION_NOTIFY_EXPORT_INVOICE_APPLY_FOCUS_SCORE_DIM_CREDIT,
                COMMON_TICK_TOCK
        );

    }

    /****************************************** 客户结算 开票申请 列表导出 Excel数据 start ******************************************/

    /****************************************** 客户结算 导出应收账款 start ******************************************/

    private static final String SYS_NOTIFY_ACTION_NOTIFY_EXPORT_INVOICE_INVOICEDS = "notify/export/InvoiceInvoiceds";

    public void notifyExportExcelInvoiceInvoiceds(SysNotify sysNotify, LoginSysUser loginSysUser) {

        commonNotifyExportExcel(
                sysNotify,
                loginSysUser,
                SYS_NOTIFY_ACTION_NOTIFY_EXPORT_INVOICE_INVOICEDS,
                COMMON_TICK_TOCK
        );
    }
    /****************************************** 客户结算 导出应收账款   end ******************************************/


    /****************************************** 业务部分 20210303 start ******************************************/

    // TODO 有空再把 SYS_NOTIFY_ACTION_ 再抽出来
    private static final String SYS_NOTIFY_ACTION_NOTIFY_EXPORT_UNIFIED_CUSTOMER_INVOICE_2_GOODS_DETAIL  = "notify/export/UnifiedCustomerInvoice2GoodsDetail";
    private static final String SYS_NOTIFY_ACTION_NOTIFY_EXPORT_UNIFIED_CUSTOMER_INVOICE_2_CREDIT_DETAIL = "notify/export/UnifiedCustomerInvoice2CreditDetail";

    public void notifyExportExcelUnifiedCustomerInvoice2GoodsDetail(SysNotify sysNotify, LoginSysUser loginSysUser) {

        commonNotifyExportExcel(sysNotify, loginSysUser, SYS_NOTIFY_ACTION_NOTIFY_EXPORT_UNIFIED_CUSTOMER_INVOICE_2_GOODS_DETAIL, COMMON_TICK_TOCK);
    }

    public void notifyExportExcelUnifiedCustomerInvoice2CreditDetail(SysNotify sysNotify, LoginSysUser loginSysUser) {

        commonNotifyExportExcel(sysNotify, loginSysUser, SYS_NOTIFY_ACTION_NOTIFY_EXPORT_UNIFIED_CUSTOMER_INVOICE_2_CREDIT_DETAIL, COMMON_TICK_TOCK);

    }

    private static final String SYS_NOTIFY_ACTION_NOTIFY_EXPORT_DIM_UNIFIED_INVOICE_REGISTER_4_E6 = "notify/export/DimUnifiedInvoiceRegister4E6";

    public void notifyExportExcelDimUnifiedInvoiceRegister4E6(SysNotify sysNotify, LoginSysUser loginSysUser) {

        commonNotifyExportExcel(sysNotify, loginSysUser, SYS_NOTIFY_ACTION_NOTIFY_EXPORT_DIM_UNIFIED_INVOICE_REGISTER_4_E6, COMMON_TICK_TOCK);

    }

    /****************************************** 业务部分 20210303   end ******************************************/

    /****************************************** 订单管理 导出报表 导出成本 20210303 start ******************************************/

    private static final String SYS_NOTIFY_ACTION_NOTIFY_EXPORT_ORDER_MANAGER_GOODS_DATA       = "notify/export/OrderManagerGoodsData";
    private static final String SYS_NOTIFY_ACTION_NOTIFY_EXPORT_ORDER_MANAGER_GOODS_COST_PRICE = "notify/export/OrderManagerGoodsCostPrice";

    public void notifyExportExcelOrderManagerGoodsData(SysNotify sysNotify, LoginSysUser loginSysUser) {

        commonNotifyExportExcel(sysNotify, loginSysUser, SYS_NOTIFY_ACTION_NOTIFY_EXPORT_ORDER_MANAGER_GOODS_DATA, COMMON_TICK_TOCK);


    }

    public void notifyExportExcelOrderManagerGoodsCostPrice(SysNotify sysNotify, LoginSysUser loginSysUser) {

        commonNotifyExportExcel(sysNotify, loginSysUser, SYS_NOTIFY_ACTION_NOTIFY_EXPORT_ORDER_MANAGER_GOODS_COST_PRICE, COMMON_TICK_TOCK);

    }

    /****************************************** 订单管理 导出报表 导出成本 20210303   end ******************************************/

    /****************************************** 客户结算 未对账 商品 导出表格 20210316 start ******************************************/

    private static final String SYS_NOTIFY_ACTION_NOTIFY_EXPORT_ACCOUNTING_CUSTOMER_NOT_YET_DIM_ORDER = "notify/export/AccountingCustomerNotYetDimOrder";
    private static final String SYS_NOTIFY_ACTION_NOTIFY_EXPORT_ACCOUNTING_CUSTOMER_NOT_YET_DIM_GOODS = "notify/export/AccountingCustomerNotYetDimGoods";

    public void notifyExportExcelAccountingCustomerNotYetDimOrder(SysNotify sysNotify, LoginSysUser loginSysUser) {

        commonNotifyExportExcel(sysNotify, loginSysUser, SYS_NOTIFY_ACTION_NOTIFY_EXPORT_ACCOUNTING_CUSTOMER_NOT_YET_DIM_ORDER, COMMON_TICK_TOCK);

    }

    public void notifyExportExcelAccountingCustomerNotYetDimGoods(SysNotify sysNotify, LoginSysUser loginSysUser) {

        commonNotifyExportExcel(sysNotify, loginSysUser, SYS_NOTIFY_ACTION_NOTIFY_EXPORT_ACCOUNTING_CUSTOMER_NOT_YET_DIM_GOODS, COMMON_TICK_TOCK);

    }
    /****************************************** 客户结算 未对账 商品 导出表格 20210316   end ******************************************/


    /****************************************** 积分结算 未对账 start ******************************************/

    private static final String SYS_NOTIFY_ACTION_NOTIFY_EXPORT_SCORE_ORDER_RECONCILIATION_NOT_YET = "notify/export/ExcelScoreOrderReconciliationNotYet";

    public void notifyExportExcelScoreOrderReconciliationNotYet(SysNotify sysNotify, LoginSysUser loginSysUser) {

        commonNotifyExportExcel(sysNotify, loginSysUser, SYS_NOTIFY_ACTION_NOTIFY_EXPORT_SCORE_ORDER_RECONCILIATION_NOT_YET, COMMON_TICK_TOCK);

    }
    /****************************************** 积分结算 未对账   end ******************************************/


    /****************************************** 供应商结算 未对账 详情 start ******************************************/

    private static final String SYS_NOTIFY_ACTION_NOTIFY_EXPORT_ACCOUNTING_SUPPLIER_NOT_YET_DIM_GOODS = "notify/export/AccountingSupplierNotYetDimGoods";

    public void notifyExportExcelAccountingSupplierNotYetDimGoods(SysNotify sysNotify, LoginSysUser loginSysUser) {

        commonNotifyExportExcel(sysNotify, loginSysUser, SYS_NOTIFY_ACTION_NOTIFY_EXPORT_ACCOUNTING_SUPPLIER_NOT_YET_DIM_GOODS, COMMON_TICK_TOCK);

    }
    /****************************************** 供应商结算 未账单 详情   end ******************************************/


    /****************************************** 客户结算 对账单 详情 start ******************************************/

    private static final String SYS_NOTIFY_ACTION_NOTIFY_EXPORT_CUSTOMER_STATEMENTOFACCOUNT_DETAIL_COMPATIBLE = "notify/export/customer/StatementOfAccountDetailCompatible";

    public void notifyExportCustomerStatementOfAccountDetailCompatible(SysNotify sysNotify, LoginSysUser loginSysUser) {

        commonNotifyExportExcel(sysNotify, loginSysUser, SYS_NOTIFY_ACTION_NOTIFY_EXPORT_CUSTOMER_STATEMENTOFACCOUNT_DETAIL_COMPATIBLE, COMMON_TICK_TOCK);

    }
    /****************************************** 客户结算 对账单 详情   end ******************************************/


    /****************************************** 供应商结算 对账单 列表 start ******************************************/
    private static final String SYS_NOTIFY_ACTION_NOTIFY_EXPORT_SUPPLIER_STATEMENT_LIST = "notify/export/supplier/exportExcelAccountingSupplierList";

    @Override
    public void notifyExportExcelUnifiedSupplierList(SysNotify sysNotify, LoginSysUser loginSysUser) {

        commonNotifyExportExcel(sysNotify, loginSysUser, SYS_NOTIFY_ACTION_NOTIFY_EXPORT_SUPPLIER_STATEMENT_LIST, COMMON_TICK_TOCK);
    }
    /****************************************** 供应商结算 对账单 列表 start ******************************************/

    /****************************************** 供应商结算 对账单 详情 start ******************************************/

    private static final String SYS_NOTIFY_ACTION_NOTIFY_EXPORT_SUPPLIER_STATEMENTOFACCOUNT_DETAIL_COMPATIBLE = "notify/export/supplier/StatementOfAccountDetailCompatible";

    public void notifyExportSupplierStatementOfAccountDetailCompatible(SysNotify sysNotify, LoginSysUser loginSysUser) {

        commonNotifyExportExcel(sysNotify, loginSysUser, SYS_NOTIFY_ACTION_NOTIFY_EXPORT_SUPPLIER_STATEMENTOFACCOUNT_DETAIL_COMPATIBLE, COMMON_TICK_TOCK);

    }

    /****************************************** 供应商结算 对账单 详情   end ******************************************/

    /****************************************** 供应商结算 京东对账 start ******************************************/

    public void notifyAsyncExcelImportFullVersion(SysNotify sysNotify, String batchId, LoginSysUser loginSysUser) {
        commonNotifyAsyncTask(
                sysNotify,
                loginSysUser,
                StrUtil.format(SYS_NOTIFY_ACTION_NOTIFY_ASYNC_TASK, "excelImportFullVersion", batchId),
                COMMON_TICK_TOCK
        );
    }

    public void notifyAsyncExcelImportLiteVersion(SysNotify sysNotify, String batchId, LoginSysUser loginSysUser) {
        commonNotifyAsyncTask(
                sysNotify,
                loginSysUser,
                StrUtil.format(SYS_NOTIFY_ACTION_NOTIFY_ASYNC_TASK, "excelImportLiteVersion", batchId),
                COMMON_TICK_TOCK
        );
    }

    public void notifyAsyncCompareOrderAndCheckUpThenReport(SysNotify sysNotify, String batchId, LoginSysUser loginSysUser) {
        commonNotifyAsyncTask(
                sysNotify,
                loginSysUser,
                StrUtil.format(SYS_NOTIFY_ACTION_NOTIFY_ASYNC_TASK, "compareOrderAndCheckUpThenReport", batchId),
                COMMON_TICK_TOCK
        );
    }

    public void notifyAsyncCompareOrderAndCheckUpThenReportOnlyException(SysNotify sysNotify, String batchId, LoginSysUser loginSysUser) {
        commonNotifyAsyncTask(
                sysNotify,
                loginSysUser,
                StrUtil.format(SYS_NOTIFY_ACTION_NOTIFY_ASYNC_TASK, "compareOrderAndCheckUpThenReportOnlyException", batchId),
                COMMON_TICK_TOCK
        );
    }

    /**
     * notify/thirdpart/jd/asyncTask/#{任务名}/#{batchId}
     */
    private static final String SYS_NOTIFY_ACTION_NOTIFY_ASYNC_TASK = "notify/thirdpart/jd/asyncTask/{}/{}";

    private void commonNotifyAsyncTask(SysNotify sysNotify, LoginSysUser loginSysUser, String action, Integer tickTock) {

//		log.info("#commonNotify20210604# : \n{}", AnJsonUtils.toPrettyJson(loginSysUser));


//		String content = "TODO 未细化 notifyExportExcelInvoiceApplyFocusUnifiedDimGoods ...";
//		sysNotify.setContent(content);
        sysNotify.setCategoryId(SysNotifyCategoryDefaultEnum.异步任务.getKey());

        sysNotify.setDetailLink("#");

        sysNotify.setToUserId(loginSysUser.getSysUserId());
        sysNotify.setToUserName(loginSysUser.getFullName());
        sysNotify.setIdentifier(loginSysUser.getSysUserName());

        sysNotifyService.addSysNotify(sysNotify);

        W<SysNotify> message = new W<>();

        message.setAction(action);
        message.setIdentifier(sysNotify.getIdentifier());
        message.setBody(sysNotify);
        message.setTickTock(tickTock);

        try {
            webSocketDubboCustomerService.sendPost(
                    sysNotify.getIdentifier(),
                    AnJsonUtils.toJson(message)
            );
        } catch (Exception e) {

            // java.lang.reflect.InvocationTargetException
            // java.lang.RuntimeException
            e.printStackTrace();
        }
    }

    /****************************************** 供应商结算 京东对账   end ******************************************/


    /****************************************** extends BaseService 部分 start ******************************************/

    @Override
    public void addObj(SysNotifyParam param) {

        SysNotify sysNotify = AnBeanUtils.copy(param, SysNotify.class);
        sysNotifyService.insertSelective(sysNotify);

    }

    @Override
    public void updateObj(SysNotifyParam param) {

        SysNotify sysNotify = AnBeanUtils.copy(param, SysNotify.class);
        sysNotifyService.updateByPrimaryKeySelective(sysNotify);
    }

    @Override
    public void deleteObj(Long id) {
        sysNotifyService.deleteObj(id);
    }

    @Override
    public SysNotify findById(Long id) {
        return sysNotifyService.findById(id);
    }

    @Override
    public PageInfo<SysNotify> findByPaging(Map<String, Object> conditions, Integer pageNun, Integer pageSize) {
        return sysNotifyService.findByPaging(conditions, pageNun, pageSize);
    }

    @Override
    public List<SysNotify> findAll(Map<String, Object> queryMap) {
        return sysNotifyService.findAll(queryMap);
    }

    /****************************************** extends BaseService 部分   end ******************************************/


    @Override
    public void addSysNotify(SysNotifyParam param) {

        SysNotify sysNotify = AnBeanUtils.copy(param, SysNotify.class);
        sysNotifyService.addSysNotify(sysNotify);
    }

    @Override
    public void updateSysNotify(SysNotifyParam param) {

        SysNotify sysNotify = AnBeanUtils.copy(param, SysNotify.class);
        sysNotifyService.updateSysNotify(sysNotify);
    }

    @Override
    public void deleteSysNotify(Long id) {
        sysNotifyService.deleteSysNotify(id);
    }

    @Override
    public SysNotify findSysNotifyById(Long id) {
        return sysNotifyService.findSysNotifyById(id);
    }

    @Override
    public R<List<SysNotify>> pageQuery(Map<String, Object> conditions, int pageNun, int pageSize, LoginSysUser loginSysUser) {
        return sysNotifyService.pageQuery(conditions, pageNun, pageSize, loginSysUser);
    }


    /****************************************** 计划任务 start ******************************************/

    public void clearByDatabaseRecord(SysNotifyClearByDatabaseRecordCriteria sysNotifyClearByDatabaseRecordCriteria) {

        List<SysNotify> resultList = sysNotifyService.findByClearByDatabaseRecord(sysNotifyClearByDatabaseRecordCriteria);

        ResourceConstant resourceConstant = providerEnvConstantService.getResourceConstant();

        resultList.forEach(item -> {

            String filePath = resourceConstant.getPathRoot() + resourceConstant.getPathStorage() + item.getContent();

//			log.info("filePath {}", filePath);

            if (FileUtil.isFile(filePath)) {
                FileUtil.del(filePath);
            }

            deleteSysNotify(item.getId());

        });
    }

    public void clearByFileSystem(SysNotifyClearByDatabaseRecordCriteria sysNotifyClearByDatabaseRecordCriteria) {

        ResourceConstant resourceConstant = providerEnvConstantService.getResourceConstant();
    }
}
