package com.sifang.modules.changes.dao;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.changes.entity.CrmMaterialInformationChangeApply;
import com.sifang.modules.changes.vo.MaterialInformationChangeVo;
import com.sifang.modules.customer.constant.UserConstants;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.platform.utils.PlantformUtils;
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.entity.Operator;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import com.sifang.modules.taskdispatch.util.ItemDispatchUtil;
import org.springframework.stereotype.Repository;

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

@Repository
public class CrmMaterialInformationChangeApplyDao  extends BaseDao<CrmMaterialInformationChangeApply> {

    /**
     * 校验是否存在流程中的申请单
     */
    public boolean checkRepeatByEntryId(String entryId) {
        return Db.queryLong("SELECT COUNT(1) FROM crm_material_information_change_apply WHERE entry_id = ? AND unique_key = '1'", entryId) > 0;
    }

    public Long getMaxChangeTime(String entryId){
        return Db.queryColumn("SELECT IFNULL(max(change_time),0) from crm_material_information_change_apply where  entry_id = ? ",entryId);
    }

    /**
     * 创建申请单
     */
    public CrmMaterialInformationChangeApply createOne(String reason, CustomerEntry entry, Operator operator, Date now){
        CrmMaterialInformationChangeApply apply = new CrmMaterialInformationChangeApply();
        apply.setUniqueKey("1");
        apply.setNumber(PlantformUtils.getOrderNumber());
        apply.setEntryId(entry.getId());
        apply.setPowerStationCode(entry.getPowerStationCode());
        apply.setChangeReason(reason);
        Long maxChangeTime = getMaxChangeTime(entry.getId());
        apply.setChangeTime((int) (maxChangeTime+1));
        apply.setStatus("0");
        apply.setCreateBy(operator.getUserId());
        apply.setCreator(operator.getUserName());
        apply.setCreateTime(now);
        apply.setAuditRemarks("");
        save(apply);
        return apply;
    }

    /**
     * 列表数据
     */
    public List<Record> findPageData(LayuiPage page, Map<String, String> map, Operator operator) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("SELECT  a.* ,b.tenant_name,b.id_code,m.assign_audit_user_id ,r.change_status,r.change_reason ");
        sql.line("FROM crm_material_information_change_apply a");
        sql.line("LEFT JOIN crm_customer_entry b ON b.id = a.entry_id");
        sql.line("left join crm_item_manage as m on m.process_instance_id=a.id");
        sql.line(" left join crm_customer_entry_change_record r on r.change_id=a.id");
        sql.line("WHERE 1 = 1");
        queryCondition(sql, map, operator);
        sql.line("ORDER BY a.create_time DESC");
        if (StrKit.notNull(page)) {
            sql.limit(page.getPage(), page.getLimit());
        }
        List<Record> records = Db.find(sql.build(), sql.params());
        ItemDispatchUtil.setReviewFlag(records);
        return records;
    }

    /**
     * 列表数据统计
     */
    public long findPageCount(Map<String, String> map, Operator operator) {
        SqlBuilder sql = new SqlBuilder();
        sql.line("SELECT COUNT(1)");
        sql.line("FROM crm_material_information_change_apply a");
        sql.line("LEFT JOIN crm_customer_entry b ON b.id = a.entry_id");
        sql.line("WHERE 1 = 1");
        queryCondition(sql, map, operator);
        return Db.queryLong(sql.build(), sql.params());
    }

    private void queryCondition(SqlBuilder sql, Map<String, String> map, Operator operator) {
        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");
            String type = record.getStr("type");
            if(UserConstants.TYPE_TRADER.equals(operator.getUserType())){  //代理商
                if ("1".equals(type)){  // 1.一级代理商 2.二级代理商
                    sql.line(" and b.distributor_id =?" , traderId );
                }else{  //二级代理商
                    if (UserConstants.TYPE_TRADER.equals(operator.getUserType())) {
                        //代理商只能查看自己的
                        sql.line(" and b.create_trader_id =?" , traderId );
                    }
                }
            }else { //代理商人员
                String dataAuthority=record.getStr("data_authority");
                //一级代理商人员 且拥有查看所有数据的权限  则可以查看到一二级所有数据
                if("1".equals(type) && UserConstants.DATA_AUTHORITY_ALL.equals(dataAuthority)) {
                    sql.line(" and b.distributor_id =?", traderId);
                }else {
                    sql.line(" and b.create_trader_id =?" , traderId );
                    if(StringUtil.isBlank(dataAuthority) || UserConstants.DATA_AUTHORITY_ONLY.equals(dataAuthority)){
                        sql.line(" and a.create_by =? ", operator.getUserId());
                    }
                }

            }
        }
        //type 1.待审核 2.变更记录
        if ("1".equals(map.get("type"))){
            sql.line("AND a.status = '0' ");
        } else if ("2".equals(map.get("type"))) {
            sql.line("AND a.status in('1','2','3') ");
        }
        // 变更单号
        if (StringUtil.checkParamsValid(map.get("number"))) {
            sql.line("AND a.number like concat('%', ?, '%')", map.get("number"));
        }
        // 电站编码
        if (StringUtil.checkParamsValid(map.get("powerStationCode"))) {
            sql.line("AND a.power_station_code like concat('%', ?, '%')", map.get("powerStationCode"));
        }
        // 状态
        if (StringUtil.checkParamsValid(map.get("status"))) {
            sql.line("AND a.status = ?", map.get("status"));
        }
        // 业主姓名
        if (StringUtil.checkParamsValid(map.get("tenantName"))) {
            sql.line("AND b.tenant_name like concat('%', ?, '%')", map.get("tenantName"));
        }
        // 申请时间
        if (StringUtil.checkParamsValid(map.get("createTimeSta"))) {
            sql.line("AND a.create_time >= concat(?, ' 00:00:00')", map.get("createTimeSta"));
        }
        if (StringUtil.checkParamsValid(map.get("endEndTime"))) {
            sql.line("AND a.create_time <= concat(?, ' 23:59:59')", map.get("endEndTime"));
        }
        // 审核时间
        if (StringUtil.checkParamsValid(map.get("auditTimeSta"))) {
            sql.line("AND a.audit_time >= concat(?, ' 00:00:00')", map.get("auditTimeSta"));
        }
        if (StringUtil.checkParamsValid(map.get("auditTimeEnd"))) {
            sql.line("AND a.audit_time <= concat(?, ' 23:59:59')", map.get("auditTimeEnd"));
        }
    }
}
