package com.sifang.modules.flowpath.dao;


import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.utils.EmployeRoleUtils;
import com.sifang.modules.flowable.utils.FormUtils;
import com.sifang.modules.flowpath.entity.DistributionGoodsApply;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DistributionGoodsApplyDao extends BaseDao<DistributionGoodsApply> {

    Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    private BondApplyDao bondApplyDao;

    public DistributionGoodsApply getByApplyId(String applyId){
        return getByHql("from DistributionGoodsApply 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,DATE_FORMAT(a.create_time,'%Y-%m-%d %H:%i:%s')AS createTime,a.examine_opinion,a.content,d.name as department_name");
        sb.append(" FROM `crm_distribution_goods_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){
        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");
        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,a.create_by,a.department_id");
        sf.line(", DATE_FORMAT(a.finish_time,'%Y-%m-%d %H:%i:%s')AS finishTime,a.process_def_id,a.department_name as departmentName ");
        sf.line(" ,(SELECT ta.basic_quota_amount_balance FROM crm_trader_account ta WHERE ta.trader_id=t.id) AS basicQuotaAmountBalance ");
        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_distribution_goods_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_='04' 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_distribution_goods_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("traderId"))) {
            sf.line(" AND a.trader_id = ? ", map.get("traderId"));
        }
        if (StringUtil.isNotBlank(map.get("traderSearch"))) {
            sf.line(" AND a.trader_id = ? ", map.get("traderSearch"));
        }
        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");
        }

    }

    public List<Record> getTrader(User user) {
        Map<String,String> map=new HashMap<>();
        if (User.USER_TYPE_WXG.equals(user.getUserType())) {
            //平台人员
            logger.info(">>>>>getTrader  userType:{}",user.getUserType());
            EmployeRoleUtils.getUserDataAuthority(user.getId(),map);
        }else if(User.USER_TYPE_KJ.equals(user.getUserType()) || User.USER_TYPE_ADVISOR.equals(user.getUserType())){
            map.put("traderIdsE",user.getTraderId());
            logger.info(">>>>>getTrader2  userType:{}",user.getUserType());
        }
        SqlBuilder sb = new SqlBuilder();
        sb.line("SELECT t.id,t.name,t.contacts,");
        sb.line("CONCAT(t.province,t.city,t.area,t.address) AS traderAddress,");
        sb.line("t.mobile,t.bank_name,t.bank_code");
        sb.line("FROM crm_trader t");
        sb.line("WHERE t.status='0' AND t.type = '1'");
        if(StringUtil.isNotBlank(map.get("provinceE"))){
            sb.inst(" and t.province in ",map.get("provinceE").split(","));
        }
        if(StringUtil.isNotBlank(map.get("cityE"))){
            sb.inst(" and t.city in  ",map.get("cityE").split(","));
        }
        if(StringUtil.isNotBlank(map.get("traderIdsE"))){
            sb.inst(" and t.id in ",map.get("traderIdsE").split(","));
        }
        sb.line("ORDER BY t.create_time DESC");
        logger.info(">>>getTrader  sql:{}",sb.build());
        return Db.find(sb.build(), sb.params());
    }

}
