/**
 */
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.constant.BondApplyConstant;
import com.sifang.modules.flowpath.entity.DistributionGoodsApply;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.UserUtils;
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.common.utils.IdGen;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import org.springframework.stereotype.Repository;


import com.sifang.modules.flowpath.entity.BondApply;

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

/**
 * 审批业务信息DAO接口
 * @author lzp
 * @version 
 */
@Repository
public class BondApplyDao extends BaseDao<BondApply> {

    public BondApply getByApplyId(String applyId){
        return getByHql("from BondApply 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.examine_opinion,a.content,DATE_FORMAT(a.create_time,'%Y-%m-%d %H:%i:%s')AS createTime,a.create_name,d.name as department_name ");
        sb.append(" FROM `crm_bond_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 void applyList(LayuiPage<Record> page, Map<String, String> map,User user){
        //判断是否有审批权限
        String roleIds=user.getRoleIds();    //用户角色
        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.task_name,a.task_id ,a.status,a.create_by,a.department_id");
        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(" ,a.process_def_id,d.front_department ,d.name as departmentName ,DATE_FORMAT(a.finish_time,'%Y-%m-%d %H:%i:%s')AS finishTime ");
        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(" ,ca.id as cashOutId ");
        sf.line(" FROM `crm_bond_apply` a ");
        sf.line(" LEFT JOIN `crm_trader` t ON a.trader_id=t.id ");
        sf.line(" LEFT JOIN `crm_department` d  on d.id=a.department_id");
        sf.line(" LEFT JOIN `act_ru_task` k ON a.`process_instance_id`=k.PROC_INST_ID_ AND k.FORM_KEY_='03' and k.ASSIGNEE_ =? ",user.getId());
        sf.line(" left join crm_cash_out_apply ca on ca.id=a.relate_id ");
        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 List<Record> accountDetailList(Map<String, String> map,User user){
        //判断是否有审批权限
        String roleIds=user.getRoleIds();    //用户角色
        SqlBuilder sf = new SqlBuilder();
        sf.line(" SELECT a.id,a.apply_number,a.trader_id,a.adjust_type,  (CASE adjust_type WHEN 1 THEN'打款' WHEN 2 THEN'扣款' WHEN 3 THEN'退还' WHEN 4 THEN'结算抵扣' ELSE '' END) as adjust_type_name,a.amount,a.remarks, a.create_time,a.create_name,a.task_name,a.task_id ,a.status,a.create_by,a.department_id");
        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(" ,a.process_def_id,d.front_department ,d.name as departmentName ,DATE_FORMAT(a.finish_time,'%Y-%m-%d %H:%i:%s')AS finishTime ");
        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(" ,ca.id as cashOutId ");
        sf.line(" FROM `crm_bond_apply` a ");
        sf.line(" LEFT JOIN `crm_trader` t ON a.trader_id=t.id ");
        sf.line(" LEFT JOIN `crm_department` d  on d.id=a.department_id");
        sf.line(" LEFT JOIN `act_ru_task` k ON a.`process_instance_id`=k.PROC_INST_ID_ AND k.FORM_KEY_='03' and k.ASSIGNEE_ =? ",user.getId());
        sf.line(" left join crm_cash_out_apply ca on ca.id=a.relate_id ");
        sf.line(" WHERE a.status <>'4' ");
        getConditionMap(map, sf);
        sf.line(" ORDER BY a.create_time DESC  ");
        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_bond_apply` a  ");
        sf.line("  LEFT JOIN `crm_trader` t ON a.trader_id=t.id ");
        sf.line(" WHERE a.status <>'4' ");
        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("adjustType"))) {  // 0：启动，1：禁用
            sf.line(" AND a.adjust_type = ? ", map.get("adjustType"));
        }
        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("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("traderIds"))) {
            sf.inst(" AND a.trader_id in ", map.get("traderIds").split(","));
        }
        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(","));
        }
    }

    //改成了不考虑部门
    public void checkPermission(List<Record> list,String userRoleIds,String userDepartment,String formId){
        Map<String,Record> processMap=FormUtils.getAllProcessByForm(formId);  //获取 该表单的所有流程设置（包括历史设置）
        for(Record r:list){
            if(StringUtil.equalsAny(r.getStr("status"), BondApplyConstant.APPLYSTATUS_ONE,BondApplyConstant.APPLYSTATUS_TWO)){
                Record record=processMap.get(r.getStr("process_def_id")+"_"+r.getStr("task_name"));
                if(record!=null){    //流程设置的内容
                    String auditRoleId= record.get("role_id"); // 获取审批角色
                    String transDepartment=record.getStr("trans_department");
                    if(userRoleIds.contains(auditRoleId)){
                        /*if("0".equals(transDepartment)){  //不跨部门
                            r.set("audit","1");
                        }else{   //跨部门
                            //获取提交人的所有上级部门
                            String topDepts=r.getStr("front_department");
                            if(StringUtil.isNotBlank(topDepts)){
                                if(topDepts.contains(userDepartment) || r.getStr("department_id").equals(userDepartment)){
                                    r.set("audit","1");
                                }
                            }else{
                                r.set("audit","1");
                            }

                        }*/
                        r.set("audit","1");
                    }
                }else{
                 /*   r.set("audit","1");*/
                }

            }
        }
        if(FormUtils.SUPPLY_ORDER_APPLICATION.equals(formId)){   //如果是订单审批  那么编辑的话 判断提交人的角色
           Map<String,String> submitMap=FormUtils.getAllProcessSubmitByForm(formId);
            for(Record r:list){
                 if(BondApplyConstant.APPLYSTATUS_ZERO.equals(r.getStr("status"))){
                        String roleId=submitMap.get(r.getStr("process_def_id"));
                        if(StringUtil.isNotBlank(roleId)){
                            if(userRoleIds.contains(roleId)){
                                r.set("audit","1");   //可编辑
                            }
                        }
                 }
            }
        }
    }

    // 待结算账户 请款时，抵消的保证金记录
    public BondApply createBondRecord(String traderId, BigDecimal amount,Date date){
        BondApply bondApply=new BondApply();
        bondApply.setId(IdGen.uuid());
        bondApply.setApplyNumber(PlantformUtils.getOrderNumber());
        bondApply.setTraderId(traderId);
        bondApply.setAdjustType("4");
        bondApply.setAmount(amount);
        bondApply.setRemarks("请款抵消的保证金");
        bondApply.setCreateTime(date);
        bondApply.setFinishTime(date);
        bondApply.setStatus(BondApplyConstant.APPLYSTATUS_THREE);
        return bondApply;
    }

}
