package com.zfire.jiasm.syncdata.upload.order;


import com.alibaba.fastjson.JSON;
import com.zfire.jiasm.syncdata.common.AddJdueServiceImpl;
import com.zfire.jiasm.syncdata.constant.TaskConfigEnum;
import com.zfire.jiasm.syncdata.data.Token;
import com.zfire.jiasm.syncdata.service.PublicService;
import com.zfire.jiasm.syncdata.utils.HttpUtil;
import com.zfire.jiasm.syncdata.utils.JSONResult;
import com.zfire.jiasm.syncdata.utils.TokenCenter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/** 格力商城的工单数据下载走正常工单流程
 *
 * 格力商城工单数据回传到格力总部  itf_tbl_new_ds_fkmx_req
 * 格力商城 ---- 服务人员接单、服务人员报完工、服务人员预约、作废，非广佛作废、工单关闭 回传请求
 * 下派/改派网点,下派改派师傅，用户预约/改约，完工，作废 操作  区分渠道(京东,格力,天猫) 操作记录到不同的表中
 */
@Slf4j
@Component
public class GREEMallUpload {
    @Value("${baseurl}")
    private String baseurl;
    @Value("${glscc}")
    private String glscc = "";
    @Autowired
    private TokenCenter tokenCenter;
    @Autowired
    private AddJdueServiceImpl service;
    @Resource
    private PublicService publicService;

    @Scheduled(fixedDelayString = "${glsc}")
    private void process() {
        if (glscc.equals(TaskConfigEnum.FALSE.getCode())){
            return;
        }

        try {
            Token token = tokenCenter.getCurrentToken();
            // 提取待回传的数据
            List<Map<String, Object>> result = service.getTaskData("itf_tbl_new_ds_fkmx_req", false);
            String serviceName = "tblNewDsFkmx";
            String isNewDataUrl = baseurl + serviceName + "/isNewData";
            String addDataUrl = baseurl + serviceName + "/add";
            String updateUrl = baseurl + serviceName + "/update";

            for (Map<String, Object> row : result) {
                Long synReqId = (Long) row.get("syn_req_id");
                try {
                    Map<String, Object> paramMap = new HashMap<String, Object>();
                    paramMap.put("pkguid", row.get("PKGUID"));

                    // 查看该网点数据是否需要回传，不需要回传时直接修改同步状态将不再回传
                    // 工单号，名表，记录ID
                    if (publicService.checkWebsitSyncFlag((String) row.get("worker_order_no"),"itf_tbl_new_ds_fkmx_req",synReqId)){
                        continue;
                    }

                    // 检查 pkguid 是否存在 有返回数据为修改，无返回数据为新增
                    JSONResult jsonResult = HttpUtil.httpRequestWithToken(isNewDataUrl, "POST",
                            JSON.toJSONStringWithDateFormat(paramMap, "yyyy-MM-dd HH:mm:ss"), token);
                    if (jsonResult.isOK()) {
                        // 已存在调修改同步接口
                        if (!jsonResult.getData().equals("")) {
                            JSONResult updateResult = HttpUtil.httpRequestWithToken(updateUrl, "POST",
                                    JSON.toJSONStringWithDateFormat(genDataMap(row), "yyyy-MM-dd HH:mm:ss"),
                                    token);
                            if (updateResult.isOK()) {
                                service.updateSuccess(synReqId, "itf_tbl_new_ds_fkmx_req");
                            } else {
                                throw new Exception("格力商城更新数据失败[" + synReqId + "],[" + updateResult.getMsg() + "]");
                            }
                        } else {
                            // 不存在为广费建单，调新增接口
                            JSONResult addResult = HttpUtil.httpRequestWithToken(addDataUrl, "POST",
                                    JSON.toJSONStringWithDateFormat(genDataMap(row), "yyyy-MM-dd HH:mm:ss"),
                                    token);
                            if (addResult.isOK()) {
                                service.updateSuccess(synReqId, "itf_tbl_new_ds_fkmx_req");
                            } else {
                                throw new Exception("格力商城新增数据失败[" + synReqId + "],[" + addResult.getMsg() + "]");
                            }
                        }
                    } else {
                        throw new Exception("格力商城检查是否新增失败[" + synReqId + "],[" + jsonResult.getMsg() + "]");
                    }
                } catch (Exception ex) {
                    log.error("执行格力商城任务[" + synReqId + "]发生错误:" + ex.getMessage());
                    service.updateError("itf_tbl_new_ds_fkmx_req", synReqId, ex.getMessage());
                }
            }
        } catch (Exception ex) {
            log.error("ִ执行格力商城取任务发生错误", ex);
        }
    }

    private Map<String, Object> genDataMap(Map<String, Object> sourceData) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("pkguid", sourceData.get("PKGUID"));
        paramMap.put("parentbizorderid", sourceData.get("PARENTBIZORDERID"));
        paramMap.put("bizorderid", sourceData.get("BIZORDERID"));
        paramMap.put("orderitemid", sourceData.get("ORDERITEMID"));
        paramMap.put("status", sourceData.get("STATUS"));
        paramMap.put("servicewdname", sourceData.get("SERVICEWDNAME"));
        paramMap.put("servicewdno", sourceData.get("SERVICEWDNO"));
        paramMap.put("workerno", sourceData.get("WORKERNO"));
        paramMap.put("workername", sourceData.get("WORKERNAME"));
        paramMap.put("workermobile", sourceData.get("WORKERMOBILE"));
        paramMap.put("stat", sourceData.get("STAT"));
        paramMap.put("blackcardno", sourceData.get("BLACKCARDNO"));
        paramMap.put("retailsign", sourceData.get("RETAILSIGN"));
        paramMap.put("carnumber", sourceData.get("CARNUMBER"));
        paramMap.put("idnumber", sourceData.get("IDNUMBER"));
        paramMap.put("appointmentstart", sourceData.get("APPOINTMENTSTART"));
        paramMap.put("appointmentend", sourceData.get("APPOINTMENTEND"));
        paramMap.put("servicephone", sourceData.get("SERVICEPHONE"));
        paramMap.put("serviceaddress", sourceData.get("SERVICEADDRESS"));
        paramMap.put("agreement", sourceData.get("agreement"));
        paramMap.put("payment", sourceData.get("payment"));
        paramMap.put("created_by", sourceData.get("created_by"));
        paramMap.put("created_date", sourceData.get("created_date"));
        paramMap.put("last_modified_by", sourceData.get("last_modified_by"));
        paramMap.put("last_modified_date", sourceData.get("last_modified_date"));
        paramMap.put("qqlyxh", sourceData.get("qqlyxh"));
        return paramMap;
    }


}
