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.SettlementAmountAdjustmentApply;
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.util.List;
import java.util.Map;

@Repository
public class SettlementAmountAdjustmentApplyDao extends BaseDao<SettlementAmountAdjustmentApply> {

    @Autowired
    private BondApplyDao bondApplyDao;

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

    public Record getDetailById(String id){
        StringBuffer sb=new StringBuffer();
        sb.append(" SELECT a.id,a.trader_id,a.adjust_type as adjustType,a.amount,a.voucher,a.remarks ,t.name AS traderName,t.contacts,t.mobile,t.address AS traderAddress,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.entry_id,e.power_station_code ");
        sb.append(" FROM `crm_settlement_amount_adjustment_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(" LEFT JOIN crm_customer_entry e on e.id=a.entry_id ");
        sb.append(" where a.id = ?");
        return Db.findFirst(sb.toString(),id);
    }


    public void applyList(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.adjust_type,a.amount,a.remarks, a.create_time,a.create_name,a.department_name,a.task_name,a.task_id ,a.status");
        sf.line(" ,t.name AS traderName,t.contacts AS traderContacts,t.mobile AS traderMobile,t.address AS traderAddress,DATE_FORMAT(a.create_time,'%Y-%m-%d %H:%i:%s')AS createTime ");
        sf.line(", t.telephone, concat(t.province, t.city, t.area, t.address) as trader_address");
        sf.line(", DATE_FORMAT(a.finish_time,'%Y-%m-%d %H:%i:%s')AS finishTime,a.create_by,a.department_id");
        sf.line(" ,a.process_def_id,e.power_station_code ");
        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_settlement_amount_adjustment_apply` a ");
        sf.line(" LEFT JOIN `crm_trader` t ON a.trader_id=t.id ");
        sf.line(" LEFT JOIN crm_customer_entry e on e.id=a.entry_id ");
        sf.line(" LEFT JOIN `act_ru_task` k ON a.`process_instance_id`=k.PROC_INST_ID_ AND k.FORM_KEY_='07' and k.ASSIGNEE_ =? ",user.getId());
        sf.line(" WHERE a.status <>'4' ");
        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());
        page.setData(list);
    }

    public long getCount(Map<String, String> map,User user) {
        SqlBuilder sf = new SqlBuilder();
        sf.line(" SELECT COUNT(a.id) FROM `crm_settlement_amount_adjustment_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_='07'  ");
        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("traderId"))) {
            sf.line(" AND a.trader_id = ? ", map.get("traderId"));
        }
        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("adjustType"))) {  // 0：启动，1：禁用
            sf.line(" AND a.adjust_type = ? ", map.get("adjustType"));
        }
        if (StringUtil.isNotBlank(map.get("status"))) {
            sf.line(" AND a.status = ? ", map.get("status"));
        }
        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("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("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(","));
        }
    }

    //结算扣减选择的电站，是安装完成后的电站
    public List<Record> getEntryList(String traderId){
        String sql=" SELECT e.id,e.tenant_name,e.power_station_code FROM `crm_customer_entry` e WHERE e.status IN('6','d','e','7','10','a') AND e.distributor_id=? ";
        List<Record> list=Db.find(sql,traderId);
        return list;
    }


}
