package com.sifang.modules.customer.dao;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.entity.CrmTenantYxBankCard;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.site.siteInfo.service.SiteEmployeeService;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.dao.UserDao;
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.List;
import java.util.Map;


@Repository
public class TenantYxBankCardDao extends BaseDao<CrmTenantYxBankCard> {

    @Autowired
    private SiteEmployeeService siteEmployeeService;



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

    @Autowired
    private UserDao userDao;

    /**
     * 状态 1-申请已受理 2-预开户成功 3-预开户失败 4-正式开户成功 5-正式开户失败 7-销户失败 8-销户中 9-工行受理中 10-过期 11暂存
     * 根据 身份证、项目公司 获取开卡记录，状态进行排序，规则： 4 2 9 1 8 11 3 5 7 10
     */
    public List<Record> getListByIdCard(String idCard,String managementType){
        return Db.find(" SELECT * FROM crm_tenant_yx_bank_card a " +
                "WHERE a.`status` NOT IN ('0','6') AND a.`id_code` = ? AND a.`management_type` = ? AND a.partner_id = '01'" +
                        "ORDER BY FIELD(a.`status`,'10','7','5','3','11','8','1','9','2','4') DESC",
                idCard, managementType);
    }

    /**
     * 删除 多余的开卡记录
     */
    public int delUnnecessaryData(String idCard,String managementType, String retainId){
        // 先备份
        SqlBuilder copy = new SqlBuilder();
        copy.line(" INSERT INTO crm_tenant_yx_bank_card_copy ");
        copy.line(" SELECT * FROM crm_tenant_yx_bank_card a ");
        copy.line(" WHERE a.`status` NOT IN ('0','6') AND " +
                "a.`id_code` = ? AND a.`management_type` = ? AND a.id != ? AND a.partner_id = '01'", idCard, managementType, retainId);
        Db.update(copy.build(), copy.params());

        return Db.update("DELETE FROM crm_tenant_yx_bank_card " +
                "WHERE `status` NOT IN ('0','6') AND `id_code` = ? AND `management_type` = ? AND `id` != ? AND partner_id = '01'",
                idCard, managementType, retainId);
    }

    public CrmTenantYxBankCard getByIdCard(String idCard,String managementType, String partnerId){
        return getByHql(" from CrmTenantYxBankCard " +
                "where status not in('0','6') and idCode =:p1 and managementType=:p2 and partnerId=:p3",
                new Parameter(idCard,managementType,partnerId));
    }

    public CrmTenantYxBankCard getInfoByIdCard(String idCard, String partnerId){
        return getByHql(" from CrmTenantYxBankCard where status not in('0','6') and idCode =:p1 and partnerId =:p2 ", new Parameter(idCard, partnerId));
    }

    public CrmTenantYxBankCard getByCorpCommSerno(String corpCommSerno){
        return getByHql(" from CrmTenantYxBankCard where corpCommSerno=:p1 ", new Parameter(corpCommSerno));
    }



    public List<Record> selectList(LayuiPage<Record> page, Map<String, String> map,String traderId) {
        SqlBuilder builder = new SqlBuilder();
        builder.line(" SELECT c.id,c.name as tenantName,c.mobile as tenantMobile,c.id_code as idCode ")
                .line(" ,c.management_type as managementType,c.account_code as account_code,c.account_name as account_name, ")
                .line("c.status as status,c.reason as reason,s.name as companyName, ")
                .line("(SELECT COUNT(1)  ")
                .line(" FROM crm_customer_entry ce  ")
                .line(" WHERE ce.first_apply_status IN ('NEW','APPROVING', 'APPROVED') ")
                .line("  AND ce.id_code=c.id_code ")
                .line("  AND ce.partner_id=c.partner_id ")
                .line(") as coun ,c.partner_id as partnerId,p.name")
                .line("FROM `crm_tenant_yx_bank_card` c  ")
                .line(" LEFT JOIN `crm_project_company_settings` s on s.company_code=c.management_type ");
        if(StringUtil.isNotBlank(traderId)){
            builder.line("  left join crm_customer_entry e on e.id_code=c.id_code and e.status<>'b' AND e.partner_id=c.partner_id");
        }
        builder.line(" left join crm_partner p on p.id=c.partner_id");
        builder.line(" WHERE c.`status` NOT IN('0','6','10','11') ");
        if (StringUtil.checkParamsValid(map.get("partner"))) {
            builder.line("AND c.partner_id = "+map.get("partner"));
        }
        appendCondition(builder, map);
        if(StringUtil.isNotBlank(traderId)){
            builder.line("  group by c.id ");
        }
        builder.line("ORDER BY c.id desc")
                .limit(page.getPage(), page.getLimit());
        return Db.find(builder.build(), builder.params());
    }

    public Long countList(Map<String, String> map,String traderId) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT count(1)")
                .line(" FROM `crm_tenant_yx_bank_card` c ");
        if(StringUtil.isNotBlank(traderId)){
            builder.line("  left join crm_customer_entry e on e.id_code=c.id_code and e.status<>'b' ");
        }
        builder.line(" WHERE c.`status` NOT IN('0','6','10','11')  ");
        if (StringUtil.checkParamsValid(map.get("partner"))) {
            builder.line("AND c.partner_id = "+map.get("partner"));
        }
        appendCondition(builder, map);

        return Db.queryLong(builder.build(), builder.params());
    }


    private void appendCondition(SqlBuilder builder, Map<String, String> map) {
        if (StringUtil.checkParamsValid(map.get("customerName"))) {
            builder.line("AND c.name like concat('%', ?, '%')", map.get("customerName").trim());
        }
        if (StringUtil.checkParamsValid(map.get("mobile"))) {
            builder.line("AND c.mobile = ?", map.get("mobile"));
        }
        if (StringUtil.checkParamsValid(map.get("idCode"))) {
            builder.line("AND c.id_code like concat('%', ?, '%')", map.get("idCode").trim());
        }
        if (StringUtil.checkParamsValid(map.get("status"))) {
            builder.line("AND c.status = ?", map.get("status").trim());
        }
        if (StringUtil.checkParamsValid(map.get("tStatus"))) {
            String status = map.get("tStatus");
            if ("1".equals(status)) {
                builder.line("AND cm.status = '1' ");
            }
            else if ("2".equals(status)) {
                builder.line("AND cm.status in ('2','3') ");
            }
        }
        if(StringUtil.checkParamsValid(map.get("traderId"))){
            builder.line("AND e.distributor_id = ?", map.get("traderId"));
        }

    }


    public  List<String> isCancel(){
        return Db.query(" SELECT ty.id_code FROM crm_tenant_yx_bank_card ty LEFT JOIN crm_customer_entry ce ON ty.id_code = ce.id_code WHERE ce.first_apply_status IN ('APPROVING', 'APPROVED') AND ty.partner_id = '01' GROUP BY ty.id_code ");
    }

//    public  List<Record> findCustomerEntryByIdCode(String idCode){
//        return Db.query("SELECT * FROM crm_customer_entry WHERE id_code = ? ",idCode);
//    }

    public List<CustomerEntry> findCustomerEntryByIdCode(String idCode, String partnerId){
        return find("from CustomerEntry where idCode=:p1  and partnerId =:p2 ", new Parameter(idCode, partnerId));
    }

}
