package com.engine.htsc.common.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ServiceUtil;
import com.engine.htsc.common.service.CommonService;
import com.engine.htsc.common.service.impl.CommonServiceImpl;
import com.engine.htsc.trip.util.AjaxResult;
import weaver.general.BaseBean;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommonAction extends BaseBean {

    private CommonService getServices(){
        return ServiceUtil.getService(CommonServiceImpl.class);
    }

    /**
     * 根据表名、条件名、参数修改表字段值
     *  "table": "uf_dsfgl","conditions":"zt:1&id:3","data":"zt:3"
     * @param params
     * @return
     */
    @POST
    @Path("/updateCommon")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public AjaxResult<List<Map<String, String>>> updateCommon(Map<String, String> params) {
        writeLog("sync fund status starting... params: " + JSON.toJSONString(params));
        try {
            List<Map<String, String>> dataList = new ArrayList<>();
            String tableName = params.get("table");
            String[] conditions = params.get("conditions").split("&");
            String[] datas = params.get("data").split("&");
            Map<String,String> conditionMap = new HashMap<>();
            Map<String,String> dataMap = new HashMap<>();
            for (String condition:conditions){
                conditionMap.put(condition.split(":")[0],condition.split(":")[1]);
            }
            for (String data:datas){
                dataMap.put(data.split(":")[0],data.split(":")[1]);
            }
            String recordchangeParam = params.get("recordchangeParam");
            if (recordchangeParam != null){
                Map<String,String> map = (Map<String,String>) JSONObject.parse(recordchangeParam);
                Map<String, String> responseMsg = this.getServices().recordChange(tableName,conditionMap,dataMap,map);
                if (!"200".equals(String.valueOf(responseMsg.get("code")))){
                    return AjaxResult.error(responseMsg.get("message"));
                }
            }

            Map<String, String> responseMsg = this.getServices().updateData(tableName,conditionMap,dataMap);
            dataList.add(responseMsg);
            if ("200".equals(String.valueOf(responseMsg.get("code")))){
                return AjaxResult.ok(dataList);
            }else {
                return AjaxResult.error(responseMsg.get("message"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            writeLog("sync fund status fail, catch error: ", e);
            return AjaxResult.error(e.getMessage());
        }
    }

}
