package com.sifang.modules.sunshine.SystemSetting.service;

import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.SourceConstants;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.dao.CrmSiteCashOutDao;
import com.sifang.modules.sunshine.SystemSetting.dao.SiteReceiptInformationDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmSite;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmSiteCashOut;
import com.sifang.modules.sunshine.SystemSetting.entity.SiteReceiptInformation;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.site.siteInfo.dao.SiteCompanyInfoDao;
import com.sifang.modules.sunshine.financialManagement.dao.CrmOrderSiteSettlementDao;
import com.sifang.modules.sunshine.financialManagement.entity.CrmOrderSiteSettlement;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SiteReceiptInformationService extends BaseService{

    @Autowired
    SiteReceiptInformationDao receDao;
    @Autowired
    CrmSiteCashOutDao siteoutDao;
    @Autowired
    private SiteCompanyInfoDao siteCompanyInfoDao;

    @Autowired
    private CrmOrderSiteSettlementDao settlementDao;

    public SiteReceiptInformation getBySiteId(String siteId){
        return receDao.getSiteReceiptInformationBySiteId(siteId);
    }
    public Record getSiteReceiptInformation(String siteId){
        String sql="SELECT id, site_id, IFNULL(opening_bank,'') AS opening_bank, IFNULL(account_name,'') AS account_name, IFNULL(account_number,'') AS account_number, IFNULL(alipay_name,'') AS alipay_name, IFNULL(alipay_number,'') AS alipay_number, create_time FROM crm_site_receipt_information  WHERE site_id=?";
        Record record=Db.findFirst(sql,siteId);
        return record;
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveSiteReceipt(SiteReceiptInformation siterece){
        SiteReceiptInformation siteInfo = receDao.getSiteReceiptInformationBySiteId(siterece.getSiteId());
        if(siteInfo== null){
            receDao.save(siterece);
        }else{
            siteInfo.setAccountName(siterece.getAccountName());
            siteInfo.setAccountNumber(siterece.getAccountNumber());
            siteInfo.setOpeningBank(siterece.getOpeningBank());
            siteInfo.setAlipayName(siterece.getAlipayName());
            siteInfo.setAlipayNumber(siterece.getAlipayNumber());
            receDao.save(siteInfo);
        }

    }

    public Record getSiteInformation(String siteId) {
        String sql = "select id,user_id, name,withdrawable_cash,total_wallet from `crm_site`where id=? ";
        Record record = Db.findFirst(sql, siteId);
        return record;
    }



    public Map<String,Object> getAllApplyList(LayuiPage page, Map<String, String> map, String siteId) {
        List<Record> list =getCashOutList(page, map, siteId);
        List<Map<String,Object>> mapx = CrmUtils.returnListMap(list);
        Map<String,Object> sitemap = Maps.newHashMap();
        sitemap.put("count",querytCashOutCount(map,siteId));
        sitemap.put("list",mapx);
        return sitemap;
    }

    /**
     * 平台查看请款明细
    */
    public LayuiPage<Record> getCashOutPage(LayuiPage<Record> page ,  Map<String,String> map ,String siteId){
        List<Record> list = getCashOutList(page,map,siteId);
        long count = querytCashOutCount(map,siteId);
        page.setCount(count);
        page.setData(list);
        return page;
    }


    public List<Record> getCashOutList(LayuiPage page, Map<String, String> map, String siteId){
        StringBuilder sb = new StringBuilder();
        sb.append("select a.* ");
      /*  sb.append(",DATE_FORMAT(a.create_time,'%Y-%m-%d %H:%i:%s') as createTime ,DATE_FORMAT(a.finish_time,'%Y-%m-%d %H:%i:%s') as finishTime");*/
        sb.append(" from crm_site_cash_out a where  a.status in('1','2','4','3')");
        if(StringUtil.isNotBlank(siteId)){
            sb.append(" and a.site_id= '"+siteId+"' ");
        }
        //根据请款id获取请款记录
        if(StringUtil.isNotBlank(map.get("id"))){
            sb.append("and a.id= '"+map.get("id")+ "'");
        }
        sb.append(queryCondition(map));
        sb.append(" order by a.create_time desc ");
        sb.append(" limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
        return Db.find(sb.toString());
    }
    public Long  querytCashOutCount(Map<String, String> map, String siteId){
        StringBuilder sb = new StringBuilder();
        sb.append("select count(*) from crm_site_cash_out a where a.status in('1','2','4','3')");
        if(StringUtil.isNotBlank(siteId)){
            sb.append(" and a.site_id= '"+siteId+"' ");
        }
        sb.append(queryCondition(map));
        return Db.queryLong(sb.toString());
    }
    public String queryCondition(Map<String, String> map){
        if (map == null || map.size() == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        //申请状态
        if(StringUtils.isNotBlank( map.get("status"))){
            sb.append(" and a.status = '" + map.get("status")+ "' ");
        }
        //结账类型
        if(StringUtil.isNotBlank(map.get("checkoutType"))){
            sb.append(" and  a.checkout_type ='" + map.get("checkoutType") +"' ");
        }
        if(StringUtils.isNotBlank( map.get("withdrawalNumber"))){
            sb.append(" and a.withdrawal_number = '" + map.get("withdrawalNumber")+ "' ");
        }
        //申请时间
        if(StringUtils.isNotBlank( map.get("startTime"))){
            sb.append(" and a.create_time >= '" + map.get("startTime") + " 00:00:00' ");
        }
        if(StringUtils.isNotBlank( map.get("endTime"))){
            sb.append(" and a.create_time <= '" + map.get("endTime") + " 23:59:59' ");
        }
        //请款结账时间
        if(StringUtils.isNotBlank( map.get("timeStart"))){
            sb.append(" and a.finish_time >= '" + map.get("timeStart") + " 00:00:00' ");
        }
        if(StringUtils.isNotBlank( map.get("timeEnd"))){
            sb.append(" and a.finish_time <= '" + map.get("timeEnd") + " 23:59:59' ");
        }
        return  sb.toString();
    }

    /***
     * 服务商申请请款
     */
    @Transactional(rollbackFor=Exception.class)
    public Result applicantCashOut(Map<String,String> map){
        Result result = new Result();
        String siteId=map.get("siteId");
        String orderIds=map.get("orderIds");
        //获取请款的工单结算费用
        String sql =" SELECT SUM(service_costs+reward_costs+other_cost+mileage_cost) AS amount FROM crm_order_site_settlement WHERE  jz_flag='0' AND order_id in (" + StringUtil.joinInSql(orderIds.split(",")) + ")";
        if(StringUtil.isEmpty(orderIds)){
            return Result.fail("202","选择数据有误");
        }
        BigDecimal outCash = Db.queryBigDecimal(sql);
        //获取服务商相关信息
        CrmSite site = siteCompanyInfoDao.get(siteId);
        //获取服务商请款账号的数据
        CrmSiteCashOut out = new CrmSiteCashOut();
        String applicantName=map.get("applicantName");
        String applicantId=map.get("applicantId");
        out.setApplicantId(applicantId);
        out.setApplicantName(applicantName);
        out.setSiteId(siteId);
        out.setSiteName(site.getName());
        out.setWithdrawalAmount(outCash== null? new BigDecimal("0.00"):outCash);
        out.setStatus("1");
        out.setWithdrawalNumber(PlantformUtils.getSiteNumber());
        out.setCheckoutType(map.get("type"));
        out.setSiteImg(map.get("imgs"));
        siteoutDao.save(out);
            //修改结算请款标记

        SQLQuery sqlQuery = settlementDao.getSession().createSQLQuery("UPDATE crm_order_site_settlement SET jz_flag = '2' , site_billing_id = :sbId WHERE order_id IN (" + StringUtil.joinInSql(orderIds.split(",")) + ")");
        sqlQuery.setParameter("sbId", out.getId());
        sqlQuery.executeUpdate();

        result.setCode("200");
        return result;
    }
    @Transactional(rollbackFor=Exception.class)
    public Result cancelRejection(String id,String title){
        try {

            CrmSiteCashOut out = siteoutDao.get(id);
            out.setStatus(SourceConstants.THREE);
            out.setRegisterRemarks(title);
            out.setRegisterTime(new Date());
            siteoutDao.save(out);
            SQLQuery sqlQuery = settlementDao.getSession().createSQLQuery("UPDATE crm_order_site_settlement SET jz_flag = '0'  WHERE site_billing_id = :sbId ");
            sqlQuery.setParameter("sbId", out.getId());
            sqlQuery.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("202","取消驳回失败");
        }
        return Result.ok();
    }


    public CrmSiteCashOut getById(String id){
        return siteoutDao.get(id);
    }

    @Transactional(rollbackFor=Exception.class)
    public Object CashSettlement(String id,String imgs){
        User user = UserUtils.getUser();
        String name = CrmUtils.getUserXM(user);
        CrmSiteCashOut out = siteoutDao.get(id);
        CrmSite site = siteCompanyInfoDao.get(out.getSiteId());
        int result_cash=site.getTotalWallet().compareTo(out.getWithdrawalAmount());
        //请款金额大于可请款金额
        if(result_cash < 0 ){
            logger.error("请款金额大于钱包金额 CashSettlement 钱包总额 ："+site.getTotalWallet() +" 请款金额："+ out.getWithdrawalAmount());
            return Result.fail("402","请款金额大于钱包金额");
        }
        out.setImgs(imgs);
        out.setStatus(SourceConstants.TWO);
        out.setFinishTime(new Date());
        out.setSenderName(name);
        site.setTotalWallet(site.getTotalWallet().subtract(out.getWithdrawalAmount()));
        siteoutDao.save(out);
        siteCompanyInfoDao.save(site);
        SQLQuery sqlQuery = settlementDao.getSession().createSQLQuery("UPDATE crm_order_site_settlement SET jz_flag = '1' WHERE site_billing_id = :sbId  ");
        sqlQuery.setParameter("sbId", out.getId());
        sqlQuery.executeUpdate();
    return Result.ok();
    }

    public void registerCashOut(String id ,String remark){
        SQLQuery sqlQuery = settlementDao.getSession().createSQLQuery("UPDATE crm_site_cash_out SET status = '4',register_time = NOW(),register_remarks=:remar  WHERE status ='1' and id=:id  ");
       sqlQuery.setParameter("remar",remark);
        sqlQuery.setParameter("id",id);
        sqlQuery.executeUpdate();
    }

    public CrmSite getCrmSiteById(String siteId){
        return siteCompanyInfoDao.get(siteId);
    }

}
