package com.sifang.modules.task;

import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.SqlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;
import java.util.TimerTask;

public class SiteFittingApplyExpireTask extends TimerTask {
    private static Logger logger = LoggerFactory.getLogger(SiteFittingApplyExpireTask.class);

    @Override
    public void run() {
        Date now = new Date();
        String sn = DateUtils.formatDate(now, "yyyyMMddHHmmss");
        System.out.println("计算统计----" + sn);
        long s1 = System.currentTimeMillis();
        ckeckSiteFitting();
        long s2 = System.currentTimeMillis();
        logger.info(" >> [{}] doSave use {}ms ", sn, (s2 - s1));

   /*     logger.info(" >> [{}] start saving statistic... ", sn);
        //   saveSiteMonth();
        long s3 = System.currentTimeMillis();
        logger.info(" >> [{}] end saving statistic use {}ms", sn, (s3 - s2));*/
    }

    public void ckeckSiteFitting() {
        StringBuilder sf = new StringBuilder();

        sf.append(" SELECT a.* FROM crm_platform_fitting_apply a WHERE a.status='3'  AND DATEDIFF(NOW(),a.out_fitting_time)>=15  ");

        List<Record> rds = Db.find(sf.toString());
        logger.info(" 待确认入库 数量： {}", rds.size());
        if (rds.size() > 0) {
            List<String> Ids = Lists.newArrayList();
            Date time = new Date();
            for (Record r : rds) {
                Ids.add(r.getStr("id"));
                String fittingId = r.getStr("fitting_id");
                String siteFittId = "";
                Record rd = Db.findFirst("SELECT a.* FROM crm_site_fitting a WHERE a.platform_fitting_id =? AND a.site_id=? AND a.status='1' ", fittingId, r.getStr("site_id"));
                logger.info(" fittingId : {} , 服务商备件 siteFitting : {}", fittingId, rd);
                //获取平台配件信息
                Record plat = Db.findFirst("select * from crm_platform_fitting where id=? ", fittingId);
                if (plat == null) {
                    continue;
                }

                String uuId = IdGen.uuid();
                if (rd != null) {
                    siteFittId = rd.getStr("id");
                    //修改库存信息
                    Db.update("UPDATE crm_site_fitting SET CODE = ?, NAME = ? , warning = warning+" + r.getBigDecimal("fitting_audit_num") + " , site_price = ? , customer_price = ? , newest_storage_time = ? WHERE id = ? ",
                            r.getStr("fitting_code"), r.getStr("fitting_name"), r.getBigDecimal("site_price"), r.getBigDecimal("customer_price"), time, rd.getStr("id"));
                } else {
                    siteFittId = uuId;
                    //新增备件库存Order
                    Db.update("INSERT INTO crm_site_fitting " +
                                    "VALUES(?, ?, ?, ?, ?, ?, ?, '', ?, '1', ?, ?, '', '',?, 0, 0,?, 0, ?, null, ?, ?, '', ?)"
                            , uuId, r.getStr("fitting_code")
                            , r.getStr("fitting_name"), r.getStr("fitting_img"), r.getStr("fitting_version"), plat.getStr("remarks"), plat.getStr("unit"), r.getStr("old_fitting_flag"),
                            r.getStr("site_id"), time, r.getBigDecimal("fitting_audit_num"), r.getBigDecimal("site_price"), r.getBigDecimal("customer_price"), time, r.getStr("suit_printer"), fittingId);

                }
                //新增出入库明细
                Db.update("INSERT INTO crm_site_fitting_keep " +
                                "VALUES (?,?, '0', ?,?, ?, ?, ?,0,?, " +
                                " '到期自动入库', ?,?, ?, '', ?, '','')",
                        IdGen.uuid(), CrmUtils.no(), siteFittId, r.getStr("fitting_code"), r.getStr("fitting_name"), r.getBigDecimal("fitting_audit_num"), r.getBigDecimal("site_price"),
                        r.getBigDecimal("customer_price"), time, time, r.getStr("applicant_name"), r.getStr("site_id"));
            }
            String siteIdsParam = " IN(" + SqlUtils.inParam(Ids) + ")";
            Db.update("update crm_platform_fitting_apply set status='4',send_time = ? , update_time = ? , update_name = '到期自动' , confirm_storage = '到期自动' where id " + siteIdsParam, time, time);
        }


    }
}
