package com.sifang.modules.task;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.q7link.openapi.model.*;
import com.sifang.modules.q7link.dao.CrmSupplyMaterialProjectPriceDao;
import com.sifang.modules.q7link.entity.CrmSupplyMaterialProjectPrice;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.util.SqlBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.sifang.modules.q7link.utils.Q7linkUtils.getSdkRequestConfig;
import static com.sifang.modules.q7link.utils.Q7linkUtils.openapi;


@Component
//@Controller
//@RequestMapping(value = "${adminPath}/q")
public class DateTask {

    @Resource
    private CrmSupplyMaterialProjectPriceDao dao;
    private Logger log = LoggerFactory.getLogger(this.getClass());

    //@Scheduled(cron = "0 0/10 * * * ? ")
    //@RequestMapping(value = "q")
    @Scheduled(cron = "0 0 5 * * ? ")
    public void testBankQuery() {
        queryMaterialInfo();
    }


    public void queryMaterialInfo(){
        String updateSql="UPDATE crm_supply_material_project_price SET price= ?,cs_jia_ge_han_shui=?, cs_shui_lv=?,primary_unit=?,status= '0',create_time=? WHERE qq_project_code=? and qq_material_code= ?";
        String querySql="select id from crm_supply_material_project_price where qq_project_code=? and qq_material_code=? and status='0'";
        String insertSql="INSERT INTO crm_supply_material_project_price(id,qq_project_code,qq_material_code,price,cs_jia_ge_han_shui,cs_shui_lv,status,create_time,qid,primary_unit) VALUES (?,?,?,?,?,?,'0',?,?,?)";
        String delete="delete from crm_supply_material_project_price where id=?";
        System.out.print("开始进入项目价格成本查询");
        ApiResponse apiResponse = testQuery().getApiResponse();
        Map map=(Map) JSONObject.parseObject(apiResponse.getJson());
        String createTime=String.valueOf(DateUtil.date());
        if(map.get("data") != null){
            Map map1=(Map) JSONObject.parseObject(String.valueOf(map.get("data")));
            if(map1.get("list") != null){
                List<Map> list= JSONObject.parseArray(String.valueOf(map1.get("list")),Map.class);
                if(CollectionUtil.isNotEmpty(list)) {
                    List<String> qids=new ArrayList<>();
                    for (Map obj : list) {
                        //项目编码
                        String qqProjectCode = String.valueOf(obj.get("code"));
                        List<Map> listMap = JSONObject.parseArray(String.valueOf(obj.get("csXmjgbck5pj30cj701Items")), Map.class);
                        if(CollectionUtil.isNotEmpty(listMap)){
                            for(Map objM: listMap){
                                Map m=(Map) JSONObject.parseObject(String.valueOf(objM.get("csCunHuoCcjf6cj0c8601")));
                                CrmSupplyMaterialProjectPrice pri=new CrmSupplyMaterialProjectPrice();
                                pri.setCreateTime(createTime);
                                pri.setQqProjectCode(qqProjectCode);
                                //价格含税
                                pri.setCsJiaGeHanShui(String.valueOf(objM.get("csJiaGeHanShuiCcjhstm0cft01")));
                                //税率
                                pri.setCsShuiLv(new BigDecimal(String.valueOf(objM.get("csShuiLCcjht0r0cft01"))).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                                //含税单价
                                pri.setPrice(new BigDecimal(String.valueOf(objM.get("csHanShuiDanJiaCcjf6d30c2h01"))).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                                pri.setStatus("0");//数据状态0正常1删除
                                pri.setQqMaterialCode(String.valueOf(m.get("code")));//存货
                                pri.setPrimaryUnit(String.valueOf(objM.get("csZhuDanWeiCcjf6x80c8602")));//主单位
                                pri.setQid(String.valueOf(objM.get("id"))); // 企企id
                                pri.setId(IdGen.uuid());
                                qids.add(pri.getQid());
                                int result=Db.update(updateSql,pri.getPrice(), pri.getCsJiaGeHanShui(),pri.getCsShuiLv(),pri.getPrimaryUnit(),pri.getCreateTime(),pri.getQqProjectCode(),pri.getQqMaterialCode());
                                if(result==0){
                                    Db.update(insertSql,pri.getId(),pri.getQqProjectCode(),pri.getQqMaterialCode(),pri.getPrice(),pri.getCsJiaGeHanShui(),pri.getCsShuiLv(),DateUtil.now(),pri.getQid(),pri.getPrimaryUnit());
                                }else{
                                    if(result>1){
                                        List<Record> records = Db.find(querySql, pri.getQqProjectCode(), pri.getQqMaterialCode());
                                        if(records.size()>1){
                                            records=records.subList(1,records.size());
                                            for(Record r:records){
                                                Db.update(delete,r.getStr("id"));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if(CollectionUtil.isNotEmpty(qids)){
                        String deleteSql="delete from crm_supply_material_project_price where qid not in( ";
                        for(int i=0;i<qids.size();i++){
                            String arr=qids.get(i);
                            deleteSql+=" '"+arr+"' ";
                            if(i != qids.size()-1){
                                deleteSql+=",";
                            }
                        }
                        deleteSql+=" ) ";
                        int deleteResult= Db.update(deleteSql);
                        System.out.println("删除数据deleteResult---->>>>"+deleteResult);
                    }
                }
            }
        }else{
            System.out.print("项目价格成本查询错误");
        }
    }



    /**
     * 表重新更新数据  历史数据添加到历史数据表
     */
    private void dateToHistory(){
        SqlBuilder insertSql=new SqlBuilder();
        insertSql.line(" insert into crm_supply_material_project_price_history(id,qq_project_code,qq_material_code,price,cs_jia_ge_han_shui,cs_shui_lv,primary_unit,status,create_time,qid) ")
                .line(" select id,qq_project_code,qq_material_code,price,cs_jia_ge_han_shui,cs_shui_lv,primary_unit,status,create_time,qid from crm_supply_material_project_price ");
        Db.update(insertSql.build());
        SqlBuilder deleteSql=new SqlBuilder();
        deleteSql.line(" delete from crm_supply_material_project_price");
        Db.update(deleteSql.build());
        SqlBuilder deleteHisSql=new SqlBuilder();
        deleteHisSql.line(" delete from crm_supply_material_project_price_history where DATEDIFF(now(),create_time) >30 ");
        Db.update(deleteHisSql.build());

    }




    public static PostListResult testQuery() {

        PostListRequest request = new PostListRequest();
        ApiParams apiParams = new ApiParams();
        apiParams.setJson("{\n" +
                "  \"objectType\":\"Project\",\n" +
                "  \"fields\": [\n" +
                "    \"id\",\n" +            //项目id
                "    \"name\",\n" +          //项目名称
                "    \"code\",\n" +          //项目编码
                // 项目信息
                "    {\n" +
                "      \"fieldName\": \"csXmjgbck5pj30cj701Items\",\n" +
                "      \"fields\": [\n" +
                "        \"id\",\n" +                           //主键id
                "        \"projectId\",\n" +                    //项目Id
                "        \"csShuiLCcjht0r0cft01\",\n" +         //税率
                //"        \"csCunHuoCcjf6cj0c8601\",\n" +        //存货
                // 项目价格本
                "    {\n" +
                "      \"fieldName\": \"csCunHuoCcjf6cj0c8601\"," +
                "      \"fields\": [\n" +
                "        \"code\"" +     //存货编码
                "      ]\n" +
                "    },\n" +
                "        \"csZhuDanWeiCcjf6x80c8602\",\n" +     //主单位
                "        \"csJiaGeHanShuiCcjhstm0cft01\",\n" +  //价格含税
                "        \"csHanShuiDanJiaCcjf6d30c2h01\"\n" +  //含税单价
                "      ]\n" +
                "    }\n" +
                "  ]\n" +
                "}");
        request.sdkRequestConfig(getSdkRequestConfig(request));
        request.setApiParams(apiParams);
        PostListResult postListResult = openapi().postList(request);
        return postListResult;
    }






}
