package com.sifang.modules.account.dao;


import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.site.siteInfo.service.SiteEmployeeService;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.dao.UserDao;
import com.sifang.modules.sys.entity.Operator;
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.Arrays;
import java.util.List;
import java.util.Map;

@Repository
public class TotalAssetDetailsDao {

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

    @Autowired
    private UserDao userDao;

    @Autowired
    private SiteEmployeeService siteEmployeeService;


    public List<Record> entryListAccount(LayuiPage<Record> page, Map<String, String> map, Operator operator) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select e.id, e.power_station_code, e.scheme_id, e.scheme_name as planName,e.project_id, e.project_code AS projectCode, e.project_name AS projectName, e.tenant_name ")
                .line(", e.mobile, concat(e.province, e.city, e.area,e.street, e.address) as address, e.roof_type, sr.angle")
                .line(", sr.distance, e.remarks, e.examine_name,e.examine_time,e.examine_remarks, e.order_time, e.receive_time")
                .line(", e.check_accept_name, e.check_accept_time, e.deliver_name, e.deliver_time, e.install_time, e.merge_time, e.deliver_file,e.generator_no,e.retrial,e.whether_to_pay")
                .line(", e.indoc_name, e.indoc_time, e.create_time, e.examine, e.creator, e.status, e.admit_flag, e.receiving_report_id,e.flag,e.uniformity,e.id_code,e.scheme_type,ifnull(e.component_spec,r.component_spec) as component_spec,r.component_spec as componentSpec")
                .line(", e.trader_name as traderName, e.trader_tel as traderMobile,e.accept_flag,e.partner_name")
                .line(", r.capacity, r.component_num,e.apply_change,e.apply_status,e.next_apply_status,e.credit,e.credit_dsc ")
                .line(", e.contract, sr.azimuth, sr.building_height, sr.repayment_method, e.to_examine_time, e.bill, e.sign_status ")
                .line(", e.design_capacity, e.actual_capacity,(r.capacity * e.epc_price) as totalAccount,e.etd,e.eto,e.etdc,e.etoc ")
                .line(", e.design_capacity, e.actual_capacity,(r.capacity * e.epc_price) as totalAccount,e.etd,e.eto,e.etdc,e.etoc ");

        builder.line(" from crm_customer_entry e")
                //进件信息中 capacity 实际安装容量 和 进件信息中基础信息 reserved_field_four 安装容量是一样的
                /*  .line(" LEFT JOIN crm_order_mark_settings m ON m.`id`=e.`flag` AND m.status='0' and m.use_type='2' ")*/
                .line(" left join crm_accepting_report r on e.receiving_report_id=r.id")
                /*             .line(" left join crm_customer_incoming_application_basic b on e.id=b.entry_id and b.status='0' ");*/
                .line("left join crm_customer_entry_survey_record sr on sr.entry_id = e.id");
        builder.line(" where e.status ='a' ");
        appendConditions(builder, map, operator);
        builder.line("   order by e.create_time desc");
        builder.limit(page.getPage(), page.getLimit());
        return Db.find(builder.build(), builder.params());
    }

    public Long countEntryListAccount(Map<String, String> map, Operator operator) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select count(1)")
                .line(" from crm_customer_entry e")
                .line(" where e.status ='a' ");
        appendConditions(builder, map, operator);
        //builder.line(" and e.status in ('8','9','11','a') ");
        return Db.queryLong(builder.build(), builder.params());
    }

    private void appendConditions(SqlBuilder builder, Map<String, String> map, Operator operator) {

        if (StringUtil.checkParamsValid(map.get("status"))) {
            builder.inst("and e.status in ", map.get("status").split(","));
        }

        if (StringUtil.checkParamsValid(map.get("projectCode"))) {
            builder.line("and e.project_id=?", map.get("projectCode"));
        }

        if (StringUtil.checkParamsValid(map.get("projectName"))) {
            builder.like("and e.project_name like ?", map.get("projectName"));
        }

        if (StringUtil.checkParamsValid(map.get("powerStationCode"))) {
            builder.line("and e.power_station_code like concat('%', ?, '%')", map.get("powerStationCode").trim());
        }

        if (StringUtil.checkParamsValid(map.get("traderName"))) {
            builder.line("and e.trader_name like concat('%', ?, '%')", map.get("traderName"));
        }
        if (StringUtil.checkParamsValid(map.get("traderMobile"))) {
            builder.line("and e.trader_tel like concat('%', ?, '%')", map.get("traderMobile"));
        }

        if (StringUtil.checkParamsValid(map.get("tenantName"))) {
            builder.like(" and e.tenant_name like ?",map.get("tenantName"));
        }

        if (StringUtil.checkParamsValid(map.get("mobile"))) {
            builder.like("and e.mobile like ?", map.get("mobile"));
        }
        if (StringUtil.checkParamsValid(map.get("roofType"))) {
            builder.line("and e.roof_type = ?", map.get("roofType"));
        }

        if (StringUtil.checkParamsValid(map.get("remarks"))) {
            builder.like(" and e.remarks like  ? ",map.get("remarks"));
        }

        if (StringUtil.checkParamsValid(map.get("repaymentMethod"))) {
            builder.line("and sr.repayment_method = ?", map.get("repaymentMethod"));
        }


        if (StringUtil.checkParamsValid(map.get("examineRemarks"))) {
            builder.like("and e.examine_remarks like ?", map.get("examineRemarks"));
        }

        if (StringUtil.checkParamsValid(map.get("plan"))) {
            builder.line("and FIND_IN_SET(?, e.scheme_id)", map.get("plan"));
        }


        if (StringUtil.checkParamsValid(map.get("matchTimeMin"))) {
            builder.line("and e.examine_time >= concat(?, ' 00:00:00')", map.get("matchTimeMin"));
        }
        if (StringUtil.checkParamsValid(map.get("matchTimeMax"))) {
            builder.line("and e.examine_time <= concat(?, ' 23:59:59')", map.get("matchTimeMax"));
        }

        long  checkRo= userDao.isDefaultPlatRole(operator.getUserId());
        if (checkRo>0) {
            List<Record> employeeRole = siteEmployeeService.findEmployeeByUserId(operator.getUserId());
            List<String> provinceList = appendColumns(employeeRole, "provices");
            List<String> cityList = appendColumns(employeeRole, "city");
            List<String> numberList = appendColumns(employeeRole, "project_number");
            List<String> traderList = appendColumns(employeeRole, "trader_id");
            logger.info("appendConditions :  count :{}  ,  employeeRole :{}  ，provinceList:{},cityList:{},numberList:{}",checkRo,employeeRole,provinceList,cityList,numberList);
            if (!provinceList.isEmpty()) {
                builder.inst("and e.province in ", provinceList);
            }
            if (!cityList.isEmpty()) {
                builder.inst("and e.city in ", cityList);
            }
            if (!numberList.isEmpty()) {
                builder.inst("and e.project_id in ", numberList);
            }

            if (!traderList.isEmpty()) {
                builder.inst("and e.distributor_id in ", traderList);
            }
        }


    }

    private List<String> appendColumns(List<Record> records, String column) {
        List<String> ret = new ArrayList<>();
        for (Record record : records) {
            String value = record.getStr(column);
            if (StrKit.notBlank(value)) {
                ret.addAll(Arrays.asList(value.split(",")));
            }
        }
        return ret;
    }

}
