package com.sifang.modules.flowpath.dao;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.flowable.utils.FormUtils;
import com.sifang.modules.flowpath.entity.CashOutApply;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

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

@Repository
public class CashOutApplyDao extends BaseDao<CashOutApply> {

    @Autowired
    private BondApplyDao bondApplyDao;

    public CashOutApply getByApplyId(String applyId){
        return getByHql("from CashOutApply where id =:p1 ", new Parameter(applyId));
    }

    public Record getDetailById(String id){
        StringBuffer sb=new StringBuffer();
        sb.append(" SELECT a.id,a.trader_id,a.apply_number,a.obj_type,a.out_cash,a.company_name,a.bank,a.bank_code,a.voucher,a.remarks ,t.name AS traderName,a.task_id ");
        sb.append(" ,a.process_instance_id,a.status,a.create_name,d.name as department_name,DATE_FORMAT(a.create_time,'%Y-%m-%d %H:%i:%s')AS createTime ,a.examine_opinion,a.content ");
        sb.append(" ,a.offset_bond_amount ,a.pay_amount,a.settle_ids ");
        sb.append(" FROM `crm_cash_out_apply` a ");
        sb.append(" LEFT JOIN `crm_trader` t ON a.trader_id=t.id ");
        sb.append(" LEFT JOIN `crm_department` d  on d.id=a.department_id");
        sb.append(" where a.id = ?");
        return Db.findFirst(sb.toString(),id);
    }


    public List<Record> cashOutApplyList(LayuiPage<Record> page, Map<String, String> map, User user){
        SqlBuilder sf = new SqlBuilder();
        sf.line(" SELECT a.id,a.apply_number,a.trader_id,a.obj_type,a.out_cash,a.company_name,a.bank,a.bank_code,a.remarks ");
        sf.line(" ,DATE_FORMAT(a.create_time,'%Y-%m-%d %H:%i:%s')AS createTime ");
        sf.line(" ,t.name AS traderName,a.process_def_id,a.task_id ,a.status ,a.create_by  ,a.offset_bond_amount ,a.pay_amount ");
        if(StringUtil.equalsAny(user.getUserType(),User.USER_TYPE_KJ,User.USER_TYPE_ADVISOR)){
            sf.line(" ,(CASE WHEN a.status!='3' THEN '审核中' ELSE a.task_name END) AS task_name ");
        }else{
            sf.line(",a.task_name ");
        }
        sf.line(" ,(case when  k.`ASSIGNEE_`='"+user.getId()+"' then 1 else 0 end) as audit ");
        sf.line(" ,(case when FIND_IN_SET(?,a.operate_user_ids) then 1 else 0 end ) as lookAuth ",user.getId());
        sf.line(" FROM  `crm_cash_out_apply` a ");
        sf.line(" LEFT JOIN `crm_trader` t ON a.trader_id=t.id ");
        sf.line(" LEFT JOIN `act_ru_task` k ON a.`process_instance_id`=k.PROC_INST_ID_ AND k.FORM_KEY_='12' and k.ASSIGNEE_ =? ",user.getId());
        sf.line(" WHERE a.status <>'4' ");
    /*    sf.inst(" AND (a.status='3' OR k.OWNER_ in ",user.getRoleIds().split(","));
        sf.line(" OR k.`ASSIGNEE_`= ?  ",user.getId());
        sf.line("  OR a.`create_by`= ?  ",user.getId());
        sf.line("  OR FIND_IN_SET(?,a.operate_user_ids) ) ",user.getId());*/
        getConditionMap(map, sf);
        sf.line(" ORDER BY a.create_time DESC  ");
        if (page != null) {
            sf.line(" limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
            Long count = getCount(map,user);
            page.setCount(count);
        }
        List<Record> list = Db.find(sf.build(), sf.params());
       return list;
    }

    public long getCount(Map<String, String> map,User user) {
        SqlBuilder sf = new SqlBuilder();
        sf.line(" SELECT COUNT(a.id) FROM `crm_cash_out_apply` a  ");
        sf.line(" LEFT JOIN `crm_trader` t ON a.trader_id=t.id  ");
        sf.line(" LEFT JOIN `act_ru_task` k ON a.`process_instance_id`=k.PROC_INST_ID_ AND k.FORM_KEY_='12' ");
        sf.line(" WHERE a.status<>'4' ");
   /*     sf.inst(" AND (a.status='3' OR k.OWNER_ in ",user.getRoleIds().split(","));
        sf.line(" OR k.`ASSIGNEE_`= ?  ",user.getId());
        sf.line("  OR a.`create_by`= ?  ",user.getId());
        sf.line("  OR FIND_IN_SET(?,a.operate_user_ids) ) ",user.getId());*/
        getConditionMap(map, sf);
        return Db.queryLong(sf.build(), sf.params());
    }

    public void getConditionMap(Map<String, String> map, SqlBuilder sf) {

        if (StringUtil.isNotBlank(map.get("applyNumber"))) {
            sf.like(" AND a.apply_number LIKE ? ", map.get("applyNumber"));
        }
        if (StringUtil.isNotBlank(map.get("traderName"))) {
            sf.like(" AND t.name LIKE ? ", map.get("traderName"));
        }
        if (StringUtil.isNotBlank(map.get("remarks"))) {
            sf.like(" AND a.remarks LIKE ? ", map.get("remarks"));
        }

        if (StringUtil.isNotBlank(map.get("createTimeSta"))) {
            sf.line("AND a.create_time >= ?", map.get("createTimeSta") + " 00:00:00");
        }
        if (StringUtil.isNotBlank(map.get("createTimeEnd"))) {
            sf.line("AND a.create_time <= ?", map.get("createTimeEnd") + " 23:59:59");
        }
        if (StringUtil.isNotBlank(map.get("traderId"))) {
            sf.line(" AND a.trader_id = ? ", map.get("traderId"));
        }
        if(StringUtil.isNotBlank(map.get("provinceE"))){
            sf.inst(" and t.province in ",map.get("provinceE").split(","));
        }
        if(StringUtil.isNotBlank(map.get("cityE"))){
            sf.inst(" and t.city in  ",map.get("cityE").split(","));
        }
        if(StringUtil.isNotBlank(map.get("traderIdsE"))){
            sf.inst(" and t.id in ",map.get("traderIdsE").split(","));
        }
      /*  if (StringUtil.isNotBlank(map.get("status"))) {
            sf.line(" AND a.status = ? ", map.get("status"));
        }
        if (StringUtil.isNotBlank(map.get("finishTimeMin"))) {
            sf.line("AND a.finish_time >= ?", map.get("finishTimeMin") + " 00:00:00");
        }
        if (StringUtil.isNotBlank(map.get("finishTimeMax"))) {
            sf.line("AND a.finish_time <= ?", map.get("finishTimeMax") + " 23:59:59");
        }
        if (StringUtil.isNotBlank(map.get("traderId"))) {
            sf.line(" AND a.trader_id = ? ", map.get("traderId"));
        }*/
    }

    public Record getTraderCanOutCash(String traderId){
        Record record= Db.findFirst(" SELECT a.settle_amount,a.qa_amount_usable,a.bzj_amount,a.yk_bzj_amount," +
                "IFNULL(a.bond_amount_limit,0) as bond_amount_limit " +
                "FROM `crm_trader_account` a WHERE a.trader_id=? ",traderId);
        return record;
    }

    public Record getNoDeduct(String settleId){
        String sql=" SELECT IFNULL(SUM(a.amount),0) AS reduceAmount ,IFNULL(GROUP_CONCAT(a.id),'') AS adjustmentApplyIds " +
                "FROM `crm_trader_account_settle_detail` d " +
                "LEFT JOIN `crm_settlement_amount_adjustment_apply` a  ON a.entry_id=d.entry_id AND a.status='3' AND a.adjust_type='2' AND a.is_deduct='0' " +
                "WHERE d.id IN ( "+StringUtil.joinInSql(settleId.split(",")) + ") ";
        return Db.findFirst(sql);
    }

    public void updateSettleStatus(String settleId,String flag){
       String sql="UPDATE `crm_trader_account_settle_detail` SET flag=? WHERE id IN( " +StringUtil.joinInSql(settleId.split(","))+") ";
       Db.update(sql,flag);
    }

    public void updateSettleApplyStatus(String applyId,String isDeduct){
        String sql="UPDATE `crm_settlement_amount_adjustment_apply` SET is_deduct=? WHERE id IN( " +StringUtil.joinInSql(applyId.split(","))+") ";
        Db.update(sql,isDeduct);
    }

    public BigDecimal getDeductAmount(String applyId){
        String sql=" SELECT IFNULL(SUM(a.amount),0) AS reduceAmount FROM `crm_settlement_amount_adjustment_apply` a WHERE a.status='3' AND a.adjust_type='2' " +
                " AND a.id IN ("+ StringUtil.joinInSql(applyId.split(","))+") ";
        return Db.queryBigDecimal(sql);
    }

    public String getKingDeeId(String settleId,String adjustId){
        if(StringUtil.isBlank(settleId)){
            return "";
        }
        StringBuffer sql=new StringBuffer();
        sql.append(" SELECT king_dee_id FROM `crm_trader_account_settle_detail` ");
        sql.append(" WHERE id IN("+ StringUtil.joinInSql(settleId.split(","))+") AND king_dee_id IS NOT NULL AND king_dee_id!='' ");
        if(StringUtil.isNotBlank(adjustId)){
            sql.append(" UNION ALL ");
            sql.append(" SELECT king_dee_id FROM `crm_settlement_amount_adjustment_apply` ");
            sql.append(" WHERE id IN("+ StringUtil.joinInSql(adjustId.split(","))+ ") AND king_dee_id IS NOT NULL AND king_dee_id!='' ");
        }
        List<String> kingIds= Db.query(sql.toString());
        String str="";
        for(String kingId:kingIds){
            if(StringUtil.isNotBlank(kingId)){
                str+=","+kingId;
            }
        }
        if(str.length()>1){
            return str.substring(1);
        }
         return "";
    }

    public List<Record> getCashOutSettleDetail(String settleIds){
        StringBuilder sb=new StringBuilder();
        sb.append("SELECT s.id,s.scheme_type_name,e.power_station_code,e.trader_name,e.project_name,t.department_name,t.creator,s.type AS settleType,e.province,e.city,CONCAT(e.province,e.city,e.area,e.address)AS addressName, ");
        sb.append(" s.amount,e.roof_type,e.scheme_type,e.scheme_name,e.tenant_name,e.mobile,e.project_code,e.actual_capacity,s.unit_price,r.component_num,DATE_FORMAT(s.`create_time`,'%Y-%m-%d %H:%i:%s') AS createTime");
        sb.append(" FROM `crm_trader_account_settle_detail`s ");
        sb.append(" LEFT JOIN crm_customer_entry e ON e.id=s.entry_id ");
        sb.append(" LEFT JOIN `crm_trader` t ON s.trader_id=t.id ");
        sb.append(" LEFT JOIN crm_accepting_report r ON e.receiving_report_id=r.id ");
        sb.append(" WHERE s.id IN("+StringUtil.joinInSql(settleIds.split(","))+") ");
        return Db.find(sb.toString());
    }
}
