package com.sifang.modules.customer.dao;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.constant.TenantConstants;
import com.sifang.modules.customer.constant.UserConstants;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.customer.entity.CustomerEntryTenant;
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.entity.Operator;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.SqlBuilder;
import org.hibernate.SQLQuery;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Repository
public class CustomerEntryTenantDao extends BaseDao<CustomerEntryTenant> {

    /**
     * 查询客户信息
     */
    public CustomerEntryTenant findOneByTypeAndCode(String type, String idCode, String regno) {
        if (Objects.equals("1", type)) {
            return getByHql("from CustomerEntryTenant where idCode = :p1 and status = '1' and tenantType = '1'", new Parameter(idCode));
        } else {
            return getByHql("from CustomerEntryTenant where regno = :p1 and status = '1' and tenantType = '2'", new Parameter(regno));
        }
    }

    /**
     * 校验客户是否存在
     */
    public boolean checkExistByTypeAndCode(String type, String idCode, String regno) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("SELECT COUNT(1)");
        sql.line("FROM crm_customer_entry_tenant");
        sql.line("WHERE status = '1' AND yx_flag = '1'");
        sql.line("AND tenant_type = ?", type);
        if (Objects.equals("1", type)) {
            sql.line("AND id_code = ?", idCode);
        } else {
            sql.line("AND regno = ?", regno);
        }
        return Db.queryLong(sql.build(), sql.params()) > 0;
    }

    /**
     * 更新客户记录的越秀标记
     * 前提 改之前标记不能为已预审通过
     */
    public boolean updateYxFlag(String id, String yxFlag) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("update crm_customer_entry_tenant a ");
        sql.line("SET a.yx_flag = ? ", yxFlag);
        sql.line("WHERE a.id = ? AND a.yx_flag != '1' and a.status = '1' ", id);
        return Db.update(sql.build(), sql.params()) > 0;
    }

    /**
     * 删除客户记录
     */
    public boolean updateToDelete(String id) {
        SQLQuery sqlQuery = getSession().createSQLQuery("update crm_customer_entry_tenant set status='0' where id = :id AND status = '1' ");
        sqlQuery.setParameter("id", id);
        int cou = sqlQuery.executeUpdate();
        return cou > 0;
    }

    public List<Record> findListByUserAuth(Operator operator, String tenantType) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("SELECT a.id,a.tenant_type AS tenantType,a.tenant_name AS tenantName,a.id_code AS idCode,a.regno,a.birthday_date AS birthdayDate ,a.ic_validity_begin AS icValidityBegin,a.ic_validity_end AS icValidityEnd");
        sql.line("FROM crm_customer_entry_tenant a");
        sql.line("WHERE a.status = '1' AND a.yx_flag = '1'");
        sql.line("AND a.tenant_type = ?", tenantType);
        if (StringUtil.equalsAny(operator.getUserType(), UserConstants.TYPE_TRADER, User.USER_TYPE_ADVISOR)) {
            Record record = CrmUtils.getUserTrader(operator.getUserType(), operator.getUserId());
            String traderId = record.getStr("id");
            if (UserConstants.TYPE_JXS_EMP.equals(operator.getUserType())) {
                //代理商人员
                String dataAuthority = record.getStr("data_authority");
                if(UserConstants.DATA_AUTHORITY_ALL.equals(dataAuthority)) {
                    sql.line(" and a.trader_id =?", traderId);
                }else {
                    if (StringUtil.isBlank(dataAuthority) || UserConstants.DATA_AUTHORITY_ONLY.equals(dataAuthority)) {
                        sql.line("AND a.create_by = ? ", operator.getUserId());
                    }
                }
            }else if (UserConstants.TYPE_TRADER.equals(operator.getUserType())){
                sql.line(" and a.trader_id =?", traderId);
            }
        }

        return Db.find(sql.build(), sql.params());
    }

    public CustomerEntryTenant createOne(CustomerEntry entry, String regnoUrl) {
        CustomerEntryTenant tenant = new CustomerEntryTenant();
        tenant.setTraderId(entry.getCreateTraderId());
        editOne(tenant, entry, regnoUrl);
        tenant.setStatus("1");
        tenant.setBirthdayDate(entry.getBirthdayDate());
        tenant.setIcValidityBegin(entry.getIcValidityBegin());
        tenant.setIcValidityEnd(entry.getIcValidityEnd());
        tenant.setCreateBy(entry.getCreateBy());
        tenant.setCreator(entry.getCreator());
        tenant.setCreateTime(new Date());
        save(tenant);
        return tenant;
    }

    public CustomerEntryTenant createTwo(CustomerEntry entry, String regnoUrl) {
        CustomerEntryTenant tenant = new CustomerEntryTenant();
        tenant.setTraderId(entry.getCreateTraderId());
        editOne(tenant, entry, regnoUrl);
        tenant.setYxFlag(TenantConstants.YX_FLAG_PASS);
        tenant.setStatus("1");
        tenant.setBirthdayDate(entry.getBirthdayDate());
        tenant.setIcValidityBegin(entry.getIcValidityBegin());
        tenant.setIcValidityEnd(entry.getIcValidityEnd());
        tenant.setCreateBy(entry.getCreateBy());
        tenant.setCreator(entry.getCreator());
        tenant.setCreateTime(new Date());
        save(tenant);
        return tenant;
    }

    public void editOne(CustomerEntryTenant tenant, CustomerEntry entry, String regnoUrl) {
        tenant.setTenantType(entry.getTenantType());
        tenant.setTenantName(entry.getTenantName());
        tenant.setGender(entry.getGender());
        tenant.setAge(entry.getAge());
        tenant.setMobile(entry.getMobile());
        tenant.setProvince(entry.getProvince());
        tenant.setCity(entry.getCity());
        tenant.setArea(entry.getArea());
        tenant.setStreet(entry.getStreet());
        tenant.setAddress(entry.getAddress());
        tenant.setLongitude(entry.getLongitude());
        tenant.setLatitude(entry.getLatitude());
        tenant.setIdCode(entry.getIdCode());
        tenant.setIdCardFront(entry.getIdCardFront());
        tenant.setIdCardBack(entry.getIdCardBack());
        tenant.setCorp(entry.getCorp());
        // 统一社会信用代码
        tenant.setRegnoType("07");
        tenant.setRegno(entry.getRegno());
        tenant.setRegnoUrl(regnoUrl);
        tenant.setEntryId(entry.getId());
        if (Objects.equals(CustomerEntryConstants.TENANT_TYPE_COMPANY, entry.getTenantType())) {
            tenant.setYxFlag(TenantConstants.YX_FLAG_PASS);
        } else {
            tenant.setYxFlag(TenantConstants.YX_FLAG_WAIT);
        }
    }

    public CustomerEntryTenant getByTenantId(String tenantId){
        return getByHql("from CustomerEntryTenant where  id = :p1 ", new Parameter(tenantId));
    }


}
