package com.cnd3b.restcontroller.enterprise.agentwebclient.mainpage.action.costinput;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cnd3b.common.Controller;
import com.cnd3b.common.actionscore.ActionScore;
import com.cnd3b.common.data.Row;
import com.cnd3b.common.data.Rows;
import com.cnd3b.common.data.RowsMap;
import com.cnd3b.common.data.SQLFactory;
import com.cnd3b.common.data.db.DataPool;
import p2.pao.PaoRemote;
import p2.pao.PaoSetRemote;
import p2.util.P2Exception;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

public class costinput extends Controller {
    public costinput(JSONObject content) {
        super(content);
    }

    /**
     * 经销商费用列表查询
     *
     * @return
     */
    public String query_costList() {
        /**
         *排序条件设置
         */
        String[] sortfield = {"t1.fdate"};
        String sort = getSort(sortfield, "t1.fdate desc");
        /**
         * 过滤条件设置
         */
        StringBuffer where = new StringBuffer(" 1=1 ");
        if (content.containsKey("where")) {
            JSONObject whereObject = content.getJSONObject("where");
            if (whereObject.containsKey("begdate") && !"".equals(whereObject.getString("begdate"))) {
                where.append(" and convert(varchar(10),t1.fdate,120)>=").append("'").append(whereObject.getString("begdate")).append("'");
            }
            if (whereObject.containsKey("enddate") && !"".equals(whereObject.getString("enddate"))) {
                where.append(" and convert(varchar(10),t1.fdate,120)<=").append("'").append(whereObject.getString("enddate")).append("'");
            }
        }
        SQLFactory costhead = new SQLFactory(this, "经销商费用列表查询", pageSize, pageNumber, sort);
        costhead.addParameter("siteid", siteid);
        costhead.addParameter("tagentsid", tagentsid);
        costhead.addParameter_SQL("where", where);
        Rows rows = dbConnect.runSqlQuery(costhead.getSQL());
        return getSucReturnObject().setDataByPaging(rows, sortfield).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 经销商费用主界面查询
     *
     * @return
     */
    public String query_costMain() {
        String tagents_costid = content.getString("tagents_costid");

        SQLFactory costhead = new SQLFactory(this, "经销商费用主界面查询_表头");
        costhead.addParameter("siteid", siteid);
        costhead.addParameter("tagentsid", tagentsid);
        costhead.addParameter("tagents_costid", tagents_costid);

        Rows rows = dbConnect.runSqlQuery(costhead.getSQL());

        SQLFactory costmx = new SQLFactory(this, "经销商费用主界面查询_明细");
        costmx.addParameter("siteid", siteid);
        costmx.addParameter("tagentsid", tagentsid);
        costmx.addParameter("tagents_costid", tagents_costid);
        Rows mxrows = dbConnect.runSqlQuery(costmx.getSQL());
        for (Row row : rows) {
            row.put("costlist", mxrows);
            row.put("datalog", getDataLog("tagents_cost", tagents_costid));
        }
        return getSucReturnObject().setData(rows).toString();
    }

    /**
     * 经销商费用新增、修改
     *
     * @return
     */
    public String costInsertOrModify() throws P2Exception {
        JSONArray costlist = content.getJSONArray("costlist");
        if (costlist.isEmpty()) {
            return getErrReturnObject().setErrMsg("费用明细不可为空").toString();
        }
        long tagents_costid = content.getLong("tagents_costid");//费用ID，新增时默认传0
        Date fdate = content.getDate("fdate");//费用日期

        PaoSetRemote tagents_costSet = getP2ServerSystemPaoSet("tagents_cost", "siteid='" + siteid + "' and tagentsid='" + tagentsid + "' and tagents_costid='" + tagents_costid + "'");
        PaoRemote tagents_cost = null;
        if (tagents_costid <= 0 || tagents_costSet.isEmpty()) {
            tagents_cost = tagents_costSet.addAtEnd();
            tagents_cost.setValue("siteid", siteid, 11L);//企业ID
            tagents_cost.setValue("tagentsid", tagentsid, 11L);//经销商ID
            tagents_cost.setValue("createby", username, 11L);//录入人
            tagents_cost.setValue("createdate", sysdate, 11L);//录入时间

            addActionScore(ActionScore.fsourcetype.费用录入, tagents_cost.getUniqueIDValue(), "费用录入");
        } else {
            tagents_cost = tagents_costSet.getPao(0);
        }
        tagents_cost.setValue("fdate", fdate, 11L);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(fdate);
        tagents_cost.setValue("fyear", calendar.get(Calendar.YEAR), 11L);
        tagents_cost.setValue("fmonth", calendar.get(Calendar.MONTH), 11L);
        tagents_cost.setValue("changeby", username, 11L);//修改人
        tagents_cost.setValue("changedate", sysdate, 11L);//修改时间

        PaoSetRemote tagents_costmxSet = tagents_cost.getPaoSet("$tagents_costmx", "tagents_costmx", "siteid=:siteid and tagentsid=:tagentsid and tagents_costid=:tagents_costid");

        HashMap<String, PaoRemote> tagents_costmxmap = getPaoMap(tagents_costmxSet, "fcostname");

        for (Object o : costlist) {
            JSONObject tagents_costmxobject = (JSONObject) o;
            String fcostname = tagents_costmxobject.getString("fcostname");
            String ftype = tagents_costmxobject.getString("ftype");
            double famount = tagents_costmxobject.getDoubleValue("famount");

            PaoRemote tagents_costmx = null;
            if (tagents_costmxmap.containsKey(fcostname)) {
                tagents_costmx = tagents_costmxmap.get(fcostname);
            } else {
                tagents_costmx = tagents_costmxSet.addAtEnd();
                tagents_costmx.setValue("siteid", siteid, 11L);//企业ID
                tagents_costmx.setValue("tagentsid", tagentsid, 11L);//经销商ID
                tagents_costmx.setValue("tagents_costid", tagents_cost.getUniqueIDValue(), 11L);//经销商ID
                tagents_costmx.setValue("fcostname", fcostname, 11L);
                tagents_costmx.setValue("ftype", ftype, 11L);
            }
            tagents_costmx.setValue("famount", famount, 11L);
        }
        content.put("tagents_costid", tagents_cost.getString("tagents_costid"));
        /**
         * 保存修改日志
         */
        saveDataLog(tagents_cost);
        tagents_costSet.save();

        return query_costMain();
    }


    /**
     * 经销商费用删除
     *
     * @return
     */
    public String costDelete() {
        SQLFactory sqlFactory = new SQLFactory(this, "经销商费用删除");
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("tagentsid", tagentsid);
        sqlFactory.addParameter("tagents_costid", content.getString("tagents_costid"));

        String result = dbConnect.runSqlUpdate(sqlFactory.getSQL());
        if ("true".equals(result)) {
            return getSucReturnObject().toString();
        } else {
            return getErrReturnObject().setErrMsg(result).toString();
        }
    }

    /**
     * 经销商费用类型查询
     *
     * @return
     */
    public String query_costType() {
        SQLFactory sqlFactory = new SQLFactory(this, "经销商费用类型查询");
        RowsMap rowsmap = dbConnect.runSqlQuery(sqlFactory.getSQL()).toRowsMap("ftypemx");
        JSONArray array = new JSONArray();
        for (String ftypemx : rowsmap.keySet()) {
            JSONObject object = new JSONObject();
            object.put("ftype", ftypemx);
            object.put("fcostname", rowsmap.get(ftypemx).toArray("fvalue"));
            array.add(object);
        }
        return getSucReturnObject().setData(array).saveToDataPool().toString();
    }
}
