package com.sifang.modules.task;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.q7link.openapi.model.ApiParams;
import com.q7link.openapi.model.ApiResponse;
import com.q7link.openapi.model.PostListRequest;
import com.q7link.openapi.model.PostListResult;
import com.sifang.modules.alioss.AliyunOSSClientUtil;
import com.sifang.modules.ginlang.constant.GinLangConstan;
import com.sifang.modules.q7link.utils.OpenapiTemplate;
import com.sifang.modules.supply.order.controller.CheckPendingOrderController;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrder;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.util.IOUtil;
import com.sifang.modules.sys.util.SqlBuilder;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.sifang.modules.q7link.utils.OpenapiTemplate.getSdkRequestConfig;
import static com.sifang.modules.q7link.utils.OpenapiTemplate.openapi;


//@Scheduled(cron = "0 0/10 * * * ? ")
@Component
//@Controller
//@RequestMapping(value = "${adminPath}/s")
public class QqOrderTask {

    Logger logger = LoggerFactory.getLogger(QqOrderTask.class);




    @Scheduled(cron = "0 0/10 * * * ? ")
    //@RequestMapping(value = "s")
    public void testBankQuery() {
        Date now=new Date();
        StringBuilder insertSql=new StringBuilder();
        insertSql.append("insert into crm_supply_material_deliver_order(id,type,status,number,create_time,supply_id,pattern,in_warehouse_id,in_stock_time_qq,place_time,in_stock_attachment_name,in_stock_attachment_url,in_stock_attachment_key,deliver_name,receive_time)")
                .append("values(?,'6','10',?,?,?,'1',?,?,?,?,?,?,?,?)");
        StringBuilder queryMater= new StringBuilder();
        queryMater.append(" select a.material_name as materialName,b.name,a.material_specs AS materialSpecs,a.id ")
                .append(" from crm_supply_material  as a ")
                .append(" left join crm_supply_material_type as b on b.id=a.material_type_id WHERE a.qq_code=?  limit 1");
        StringBuilder insertDetail=new StringBuilder();
        insertDetail.append(" INSERT INTO crm_supply_material_deliver_order_detail(id,main_id,material_type,material_spec,material_id, ")
                .append(" apply_amount,out_amount,in_amount,sort,status,barcode_count,sales_price,purchase_price,contract_code,qq_code,project_code) VALUES (?,?,?, ?,?,?,?,?,?,'0','0',?,?,?,?,?) ");
        StringBuilder insertLogSql=new StringBuilder();
        insertLogSql.append(" INSERT INTO crm_supply_material_deliver_order_msg(id,order_id,type,operator,operator_id,content,operate_time) VALUES (?,?,1,'system','0','创建订单',?)");
        StringBuilder queryOrder=new StringBuilder();
        queryOrder.append(" select count(*) from crm_supply_material_deliver_order where number =? limit 1 ");
        StringBuilder sync=new StringBuilder();
        sync.append(" INSERT INTO crm_supply_material_deliver_order_sync(business_date,code,attachments_name,attachments_key,gys_name,ck_name,zt_code,zt_name,create_time,product_id,base_qty) VALUES (?,?,?,?,?,?,?,?,?,?,?) ");
        String result= queryQqOrder();
        Map map=(Map) JSONObject.parseObject(result);
        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);

                list=list.stream().filter(m ->  "BillStatus.effective".equals(m.get("billFullStatus"))).collect(Collectors.toList());
                for(Map m:list){
                    String longTime=String.valueOf(m.get("businessDate"));//数据入库时间
                    String code=String.valueOf(m.get("code")); //订单编号
                    String contractCode="";
                    if(m.containsKey("purObject")){
                        Map ma = (Map) JSONObject.parseObject(String.valueOf(m.get("purObject")));
                        if(ma.containsKey("code")){
                            contractCode=String.valueOf(ma.get("code"));
                        }
                    }
                    if(m.containsKey("billType")){
                        Map ma = (Map) JSONObject.parseObject(String.valueOf(m.get("billType")));
                        if(ma.containsKey("name")){
                            if(!"采购入库单".equals(String.valueOf(ma.get("name")))){
                                continue;
                            }
                        }
                    }
                    String projectId="";
                    if(m.containsKey("project")){
                        Map project = (Map) JSONObject.parseObject(String.valueOf(m.get("project")));
                        if(project.containsKey("code")){
                            projectId=String.valueOf(project.get("code"));
                        }
                    }
                    String gysName="";//供应商名称
                    String ckName="";//仓库名称
                    String ckId=""; //仓库id
                    String orderCode=code;//订单编号
                    String uuid=IdGen.uuid();
                    String time=longTimeToStringTime(Long.valueOf(longTime));
                   String filesName="";
                   String filesUrl="";
                    String ztCode="";
                    String ztName="";
                    String filesKey="";
                    Long idCount=Db.queryLong(queryOrder.toString(),orderCode);
                    if(idCount>0){
                        continue;
                    }
                    List<Map> lis = JSONObject.parseArray(String.valueOf(m.get("attachments")), Map.class);
                    if(CollectionUtil.isNotEmpty(lis)){
                        for(int k=0;k<lis.size();k++){
                            try {
                                Map mlis=lis.get(k);
                                filesName+=mlis.get("name");
                                String key=OpenapiTemplate.getAttachmentUrl(String.valueOf(mlis.get("key")));
                                byte[] bytes = IOUtil.urlAsBytes(key, 30 * 1000);
                                filesUrl+= AliyunOSSClientUtil.uploadImage(bytes, filesName.substring(filesName.lastIndexOf("."),filesName.length()), filesName);
                                filesKey+=String.valueOf(mlis.get("key"));
                                if(k != lis.size()-1){
                                    filesName+=",";
                                    filesUrl+=",";
                                    filesKey+=",";
                                }
                            }catch (IOException  e){
                                e.printStackTrace();
                            }


                        }
                    }
                    Map gyMap=(Map) JSONObject.parseObject(String.valueOf(m.get("vendor")));//获取供应商信息
                    if(gyMap != null){
                        if(gyMap.get("name") != null){
                            gysName=String.valueOf(gyMap.get("name"));
                        }
                    }
                    Map ckMap=(Map) JSONObject.parseObject(String.valueOf(m.get("warehouse")));//获取仓库信息
                    if(ckMap != null){
                        if(ckMap.get("name") != null){
                            ckName=String.valueOf(ckMap.get("code"));
                            ckId=querywarehouseId(ckName);
                        }
                    }
                    List<Map>  orderList=JSONObject.parseArray(String.valueOf(m.get("purReceiptItems")), Map.class);
                    if(CollectionUtil.isEmpty(orderList)){
                        continue;
                    }
                    Map ztMap=(Map) JSONObject.parseObject(String.valueOf(m.get("csZhuTiGongSiCcjmskk0cft01")));//获取主体公司信息
                    if(ztMap != null){
                        if(ztMap.get("name") != null && ztMap.get("code") != null){
                            ztCode=String.valueOf(ztMap.get("code"));
                            ztName=String.valueOf(ztMap.get("name"));
                            insertMainBody(ztCode,ztName,uuid,longTime);
                        }
                    }
                    int insertResult=Db.update(insertSql.toString(),uuid,orderCode,DateUtil.date(),"",ckId,time,time,filesName,filesUrl,filesKey,gysName,now);
                    logger.info("插入订单数据结果---->>>>>"+insertResult);
                    int i=1;
                    for(Map orderMap:orderList){
                        Map produc=(Map) JSONObject.parseObject(String.valueOf(orderMap.get("product")));
                        String productId =String.valueOf(produc.get("code")); //物品外部编码
                        String baseQty =String.valueOf(orderMap.get("baseQty")); //主数量
                        String amountWithoutTax=String.valueOf(orderMap.get("amount")); //价格
                        String originPrice=String.valueOf(orderMap.get("originPrice")); //价格
                        String originTransBasePrice=String.valueOf(orderMap.get("originTransBasePrice")); //价格
                        logger.info("查询详情---->>>",productId,baseQty);
                        if(StringUtils.isNotBlank(productId)){
                            List<Record> records = Db.find(queryMater.toString(), productId);
                            logger.info("查询物品得到的结果-----",records);
                            if(CollectionUtil.isNotEmpty(records)){
                                for(Record rd:records){
                                    String materTypeName=rd.getStr("name");//物品类型名称
                                    String materialSpecs=rd.getStr("materialSpecs");//物品规格
                                    String materId=rd.getStr("id");//物品id
                                    int insertDetailResult=Db.update(insertDetail.toString(),IdGen.uuid(),uuid,materTypeName,materialSpecs,materId,baseQty,baseQty,baseQty,i,originTransBasePrice,originPrice,contractCode,productId,projectId);
                                    logger.info("插入订单详情结果--->>>>>>"+insertDetailResult);
                                }
                            }
                        }
                        i++;
                        int re= Db.update(sync.toString(),longTime,code,filesName,filesKey,gysName,ckName,ztCode,ztName,DateUtil.now(),productId,baseQty);
                        logger.info("企企数据同步到中间库------>>>>"+re);
                    }
                    int re= Db.update(insertLogSql.toString(),IdGen.uuid(),uuid,DateUtil.now());
                    System.out.println("re---->"+re);


                }
            }
        }
    }





    /**
     * 时间戳转换成日期
     * @param time
     * @return
     */
    private String longTimeToStringTime(Long time){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String date = df.format(time);
        return date;
    }

    /**
     * 数据库插入主体公司信息
     * @param qid
     * @param qname
     * @param uuid
     */
    public void insertMainBody(String qid,String qname,String uuid,String longTime){
        String s=formatTimeYMD(Long.valueOf(longTime));
        logger.info("插入主体公司与订单关系 qid,qname,orderId--->>>>",qid,qname,uuid);
        String sql="INSERT INTO crm_qq_main_body(id,qid,qname,main_id,status,create_time,rk_time) VALUES (?,?,?,?,'0',?,?)";
        int result=Db.update(sql,IdGen.uuid(),qid,qname,uuid,DateUtil.date(),s);
        logger.info("数据插入主体公司与订单表---->>",result);

    }


    /**
     * 转换为年月日
     * @param time
     * @return
     */
    public static String formatTimeYMD(long time) {
        return new SimpleDateFormat("yyyy-MM-dd").format(time);
    }


    /**
     * 根据供应商名称获取供应商id
     * @param name
     * @return
     */
    private String queryCrmSupplyMaterialDeliverOrderId(String name){
        logger.info("根据供应商名称查询供应商id name-->>",name);
        SqlBuilder sqlBuilder=new SqlBuilder();
        sqlBuilder.line(" select id from crm_supply_supplier  where status ='0' and name =? ",name);
        List<Record> list= Db.query(sqlBuilder.build(),sqlBuilder.params());
        logger.info("根据供应商名称查询供应商id result----->>",list);
        if(CollectionUtil.isNotEmpty(list)){
            return String.valueOf(list.get(0));
        }
        return "";
    }


    /**
     * 根据仓库名称获取仓库id
     * @param name
     * @return
     */
    private String querywarehouseId(String name){
        logger.info("根据仓库名称获取仓库id name---->",name);
        SqlBuilder sqlBuilder=new SqlBuilder();
        sqlBuilder.line(" select id from crm_supply_warehouse where status='0' and qq_code =? ",name);
        List<Record> list= Db.query(sqlBuilder.build(),sqlBuilder.params());
        logger.info("根据仓库名称获取仓库id   resule---->",list);
        if(CollectionUtil.isNotEmpty(list)){
            return String.valueOf(list.get(0));
        }
        return "";
    }

    /**
     * 获取企企的采购订单
     * @return
     */
    public String queryQqOrder() {
        String yesz=DateUtil.today();
        //取 BillStatus.effective 已生效
        PostListRequest request = new PostListRequest();
        ApiParams apiParams = new ApiParams();
        apiParams.setJson("{\n" +
                "  \"objectType\":\"PurReceipt\",\n" +
                "  \"criteriaStr\": \"approvedTime >= '"+yesz+"'\",\n" +
                "  \"fields\": [\n" +
                "    \"id\",\n" + //主键id
                "    \"code\",\n" + //订单编码
                "    \"billFullStatus\"," + //	单据完全状态
                "    \"businessDate\"," +   //	业务日期
                "    \"approvedTime\"," +   //	采购订单生效时间
                "    \"purObjectType\"," +   //
                "    {\n" +
                "      \"fieldName\": \"billType\"," +
                "      \"fields\": [\n" +
                "        \"name\"" +    //供应商名称
                "      ]\n" +
                "    },\n" +

                "    {\n" +
                "      \"fieldName\": \"project\"," +
                "      \"fields\": [\n" +
                "        \"code\"" +    //供应商名称
                "      ]\n" +
                "    },\n" +
                "    {\n" +
                "      \"fieldName\": \"purObject\"," +
                "      \"fields\": [\n" +
                "        \"code\"" +    //供应商名称
                "      ]\n" +
                "    },\n" +

                //供应商
                "    {\n" +
                "      \"fieldName\": \"vendor\"," +
                "      \"fields\": [\n" +
                "        \"name\"" +    //供应商名称
                "      ]\n" +
                "    },\n" +
                //单据类型
                "    {\n" +
                "      \"fieldName\": \"billType\"," +
                "      \"fields\": [\n" +
                "        \"name\"" +    //单据类型名称
                "      ]\n" +
                "    },\n" +
                //主体公司
                "    {\n" +
                "      \"fieldName\": \"csZhuTiGongSiCcjmskk0cft01\"," +
                "      \"fields\": [\n" +
                "        \"code\"," +     //主体公司code
                "        \"name\"" +    //主体公司名称
                "      ]\n" +
                "    },\n" +
                //入库的仓库
                "    {\n" +
                "      \"fieldName\": \"warehouse\"," +
                "      \"fields\": [\n" +
                "        \"name\"," +    //仓库名称
                "        \"code\"" +    //仓库编码
                "      ]\n" +
                "    },\n" +
                       // activeAppoveUsers
                //采购入库明细列表
                "    {\n" +
                "      \"fieldName\": \"purReceiptItems\"," +
                "      \"fields\": [\n" +
                "        \"baseQty\"," +    //主数量
                "        \"amount\"," +    //价格
                "        \"originPrice\"," +    //原币含税单价
                "        \"originTransBasePrice\"," +    //销售单价
                "    {\n" +
                "      \"fieldName\": \"product\"," +
                "      \"fields\": [\n" +
                "        \"code\"" +    //存货编码
                "      ]\n" +
                "    }\n" +
                "      ]\n" +
                "    },\n" +
                "    {\n" +
                "      \"fieldName\": \"attachments\"," +
                "      \"fields\": [\n" +
                "        \"name\"," +    //附件名称
                "        \"url\"," +    //附件url
                "        \"folderId\"," +    //文件夹
                "        \"key\"," +    //附件KEY
                "        \"ext\"" +    //附件ext
                "      ]\n" +
                "    }\n" +
                "  ]\n" +
                "}");
        request.sdkRequestConfig(getSdkRequestConfig(request));
        request.setApiParams(apiParams);
        PostListResult postListResult = openapi().postList(request);
        ApiResponse apiResponse = postListResult.getApiResponse();
        logger.info("查询订单---->>>>>",apiResponse.getJson());
        return apiResponse.getJson();
    }
}
