package com.sifang.modules.flowpath.dao;

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

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


@Repository
public class SubpackageStandardPriceApplyDao extends BaseDao<CrmSubconractorSettlementSchemeApply> {

    @Autowired
    private BondApplyDao bondApplyDao;

    public CrmSubconractorSettlementSchemeApply getByApplyId(String applyId) {
        return getByHql("from CrmSubconractorSettlementSchemeApply where id =:p1 ", new Parameter(applyId));
    }

    public Record getDetailById(String id) {
        StringBuffer sb = new StringBuffer();
        sb.append(" SELECT a.id,a.apply_number,a.remarks,a.create_name,a.task_id,DATE_FORMAT(a.create_time,'%Y-%m-%d %H:%i:%s')AS createTime ");
        sb.append(" ,a.process_instance_id,a.status,a.create_name,d.name as department_name,DATE_FORMAT(a.create_time,'%Y-%m-%d %H:%i:%s')AS createTime,a.examine_opinion,a.content ");
        sb.append(" FROM `crm_subconractor_settlement_scheme_apply` a ");
        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 List<Record> getApplyItems(String applyId) {
        String sql = " SELECT s.id,s.name,s.type,s.amount,s.project_ids ,s.project_names,s.trader_ids,s.create_time,s.end_time FROM  `crm_subconractor_settlement_scheme` s WHERE s.apply_id=? ";
        return Db.find(sql, applyId);
    }


    public void applyList(LayuiPage<Record> page, Map<String, String> map, User user) {
        SqlBuilder sf = new SqlBuilder();
        sf.line(" SELECT a.id,s.name,a.apply_number,a.remarks, a.create_time,a.create_name,a.task_name,a.task_id ,a.status");
        sf.line(" ,DATE_FORMAT(a.create_time,'%Y-%m-%d %H:%i:%s')AS createTime,a.create_by,a.department_id ");
        sf.line(" ,a.process_def_id,a.department_name as departmentName ");
        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_subconractor_settlement_scheme_apply` a ");
        sf.line(" LEFT JOIN `act_ru_task` k ON a.`process_instance_id`=k.PROC_INST_ID_ AND k.FORM_KEY_='06'  and k.ASSIGNEE_ =? ",user.getId());
        sf.line(" LEFT JOIN `crm_subconractor_settlement_scheme` s ON s.apply_id = a.id ");
        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_subconractor_settlement_scheme_apply` a  ");
        sf.line(" LEFT JOIN `act_ru_task` k ON a.`process_instance_id`=k.PROC_INST_ID_ AND k.FORM_KEY_='06'  ");
        sf.line(" LEFT JOIN `crm_subconractor_settlement_scheme` s ON s.apply_id = a.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("remarks"))) {
            sf.like(" AND a.remarks LIKE ? ", map.get("remarks"));
        }
        if (StringUtil.isNotBlank(map.get("name"))) {
            sf.like(" AND s.name LIKE ? ", map.get("name"));
        }
        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");
        }

    }

    //这个是未申请过的项目
    public List<Record> getProjectName() {
        String sql = " SELECT s.id,s.name,s.code,l.name as productLineName FROM `crm_project_setting` s " +
                     " left join crm_product_line_set l on l.id=s.product_line_id "+
                "LEFT JOIN `crm_subconractor_settlement_scheme` a ON  FIND_IN_SET(s.id,a.project_ids) AND a.status<>'2' " +
                "WHERE s.status='0' AND a.id IS NULL ";
        return Db.find(sql);
    }

    //这个是已经申请过的项目
    public List<Record> getProjectAsApprove(String id) {
        String sql = " SELECT s.id,s.name,a.trader_ids,a.create_time,a.end_time FROM `crm_project_setting` s " +
                "LEFT JOIN `crm_subconractor_settlement_scheme` a ON  FIND_IN_SET(s.id,a.project_ids) AND a.status<>'2' " +
                "WHERE s.status='0' AND a.id IS not null ";
        if(StringUtil.isNotBlank(id)){
            sql+=" and a.apply_id <> '"+id +"'";
        }
        return Db.find(sql);
    }

    public List<Record> getProjectNameByApply(String applyId) {
        String sql = " SELECT s.id,s.name FROM `crm_project_setting` s "+
                    "LEFT JOIN `crm_subconractor_settlement_scheme` a ON  FIND_IN_SET(s.id,a.project_ids) AND a.status<>'2' " +
                "WHERE s.status='0' AND (a.id IS NULL OR a.apply_id=? ) ";
        return Db.find(sql,applyId);
    }


    //修改分包内容的状态
    public void updateSettlementScheme(String applyId){
        Db.update(" UPDATE `crm_subconractor_settlement_scheme` SET status='1' WHERE apply_id=?  AND status='0' and DATE(create_time) <= CURDATE() ",applyId);

        Db.update(" UPDATE `crm_subconractor_settlement_scheme` SET status='3' WHERE apply_id=?  AND status='0' and DATE(create_time) > CURDATE() ",applyId);
    }
}