package com.malk.pake.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson.JSONObject;
import com.malk.pake.entity.PkWbcg;
import com.malk.pake.mapper.PkWbcgMapper;
import com.malk.pake.service.PkWbcgService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.service.aliwork.YDClient;
import com.malk.utils.PublicUtil;
import com.malk.utils.UtilDateTime;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class PkWbcgServiceImpl implements PkWbcgService {

    @Autowired
    private YDClient ydClient;
    @Autowired
    private PkWbcgMapper pkWbcgMapper;

    private static List<configDto> config2;

    {
        config2=new ArrayList<>();
        // 类型   金额  一级部门 二级部门
        config2.add(new configDto("01","第三方采购","textField_40lr8u5","textField_qpi47c5","textField_iqu0lt4"));
        config2.add(new configDto("02","代运营保底赔付","textField_4ja4exh","默认",""));
        config2.add(new configDto("02","代运营保底赔付","textField_9lolz7t","全国营销中心","河北办事处"));
        config2.add(new configDto("02","代运营保底赔付","textField_mchzg5g","全国营销中心","新疆办事处"));
        config2.add(new configDto("02","代运营保底赔付","textField_uh7xzvp","全国营销中心","浙江办事处"));
        config2.add(new configDto("02","代运营保底赔付","textField_u9ezpca","全国营销中心","销售与解决方案事业部"));
        config2.add(new configDto("02","代运营保底赔付","textField_1q1mngd","全国营销中心","驻地运营事业部"));

        config2.add(new configDto("03","内容成本","textField_yskuizk","textField_n6dgais","textField_nywps4o&&textField_cq3wrgw"));
        config2.add(new configDto("04","渠道成本","textField_0p6725u","textField_niydh0v","textField_cq3wrgw"));
        config2.add(new configDto("05","版权赔付","textField_7z9umea","textField_n6dgais","textField_cq3wrgw"));
        config2.add(new configDto("06","项目专线、IDC租赁","textField_o7hrwxq","textField_niydh0v","textField_nywps4o&&textField_cq3wrgw"));
        config2.add(new configDto("07","中标服务费","textField_rl6bu4e","textField_niydh0v","textField_nywps4o"));
        config2.add(new configDto("08","经营性固定资产采购","textField_zkp9rt7","textField_qpi47c5","textField_iqu0lt4"));
        config2.add(new configDto("09","研发设备采购费","textField_f4hxczh","textField_bs5acse","textField_absucq7"));
        config2.add(new configDto("10","研发软件及服务采购","textField_vh8bd91","textField_r391zwq","textField_4kzpuqt"));
        config2.add(new configDto("11","投流成本","textField_6fykj0t","textField_pr7mh62","textField_2hpmihn"));
    }

    private class configDto{
        public String id;
        public String key;
        public String key2;
        public String key3;
        public String key4;
        public configDto(String key,String key2){
            this.key=key;
            this.key2=key2;
        }
        public configDto(String id,String key,String key2,String key3,String key4){
            this.id=id;
            this.key=key;
            this.key2=key2;
            this.key3=key3;
            this.key4=key4;
        }
    }

    @Override
    public List<Map> selectSumDataList(String dept1, String dept2) {
        return pkWbcgMapper.selectSumDataList(dept1,dept2);
    }

    @Override
    public void syncData(String id) {
        Map<String,Object> data =ydClient.queryData(YDParam.builder().formInstId(id).build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
        LocalDateTime localDateTime= UtilDateTime.getLocalDateTimeFromTimestamp(UtilMap.getLong(data,"dateField_cs14yue"));
        int month=localDateTime.getMonthValue();
        for(configDto configDto:config2){
            String amt="";
            if(configDto.key2.contains("&&")){
                String[] keys=configDto.key2.split("&&");
                for (int i = 0; i < keys.length; i++) {
                    amt= NumberUtil.add(UtilMap.getNumberStr(data,keys[i]),amt).toString();
                }
            }else{
                amt=UtilMap.getNumberStr(data,configDto.key2);
            }
            String dept1,dept2;
            if(configDto.key3.contains("textField")){
                if(configDto.key3.contains("&&")){
                    String[] keys=configDto.key3.split("&&");
                    String[] values=new String[keys.length];
                    for (int i = 0; i < keys.length; i++) {
                        values[i]=UtilMap.getString(data,keys[i]);
                    }
                    dept1=String.join(",", values);
                }else{
                    dept1=UtilMap.getString(data,configDto.key3);
                }
            }else{
                dept1=configDto.key3;
            }
            if(configDto.key4.contains("textField")){
                if(configDto.key4.contains("&&")){
                    String[] keys=configDto.key4.split("&&");
                    String[] values=new String[keys.length];
                    for (int i = 0; i < keys.length; i++) {
                        values[i]=UtilMap.getString(data,keys[i]);
                    }
                    dept2=String.join(",", values);
                }else{
                    dept2=UtilMap.getString(data,configDto.key4);
                }
            }else{
                dept2=configDto.key4;
            }
            PkWbcg pkWbcg=new PkWbcg(configDto.id,configDto.key,dept1,dept2);
            save(pkWbcg,"setAmt".concat(String.valueOf(month)),amt,"setTotal");
        }
        System.out.println("处理完成");
    }

    @Override
    public void syncYsData() {
        for(configDto configDto:config2) {
            List<Map> list = (List<Map>) ydClient.queryData(YDParam.builder().formUuid("FORM-2172522109C047D9AC18A872ED2FCD792YMZ")
                    .searchFieldJson(JSONObject.toJSONString(UtilMap.map("selectField_b3run5c, selectField_m7qqwok", "外部采购",configDto.key)))
                    .build(), YDConf.FORM_QUERY.retrieve_list).getData();
            for (int i = 0; i < list.size(); i++) {
                log.info("处理进度：{}/{}", i + 1, list.size());
                Map data = list.get(i);
                String dept1=UtilMap.getString(data,"textField_67lf04e");
                String dept2=UtilMap.getString(data,"textField_vco7vnl");
                String amt=UtilMap.getString(data,"numberField_397v7ux");
                PkWbcg pkWbcg = new PkWbcg(configDto.id, configDto.key, dept1, dept2);
                if(PublicUtil.isNull(data,"dateField_w3yecdm")){
                    // 年度预算
                    save(pkWbcg,amt);
                }else{
                    LocalDateTime localDateTime = UtilDateTime.getLocalDateTimeFromTimestamp(UtilMap.getLong(data, "dateField_w3yecdm"));
                    String amtMethodName= "setYsamt".concat(String.valueOf(localDateTime.getMonthValue()));
                    save(pkWbcg, amtMethodName, amt, "setYstotal");
                }
            }
        }
        System.out.println("处理完成");
    }

    private void save(PkWbcg pkWbcg,String amtMethodName,String amt,String totalMethodName){
        PkWbcg data=pkWbcgMapper.selectById(pkWbcg.getName());
        if(data==null){
            ReflectUtil.invoke(pkWbcg,amtMethodName,amt);
            ReflectUtil.invoke(pkWbcg,totalMethodName,amt);
            pkWbcgMapper.insert(pkWbcg);
        }else{
            String newAmt=NumberUtil.add(ReflectUtil.invoke(data,amtMethodName.replace("set","get")),amt).toString();
            String totalAmt=NumberUtil.add(ReflectUtil.invoke(data,totalMethodName.replace("set","get")),amt).toString();
            ReflectUtil.invoke(data,amtMethodName,newAmt);
            ReflectUtil.invoke(data,totalMethodName,totalAmt);
            pkWbcgMapper.updateById(data);
        }
    }

    private void save(PkWbcg pkWbcg,String ndysAmt){
        PkWbcg data=pkWbcgMapper.selectById(pkWbcg.getName());
        if(data==null){
            ReflectUtil.invoke(pkWbcg,"setNdystotal",ndysAmt);
            pkWbcgMapper.insert(pkWbcg);
        }else{
            String totalAmt=NumberUtil.add(ReflectUtil.invoke(data,"getNdystotal"),ndysAmt).toString();
            ReflectUtil.invoke(data,"setNdystotal",totalAmt);
            pkWbcgMapper.updateById(data);
        }
    }
}
