package com.cnd3b.restcontroller.enterprise.salerclient.mainpage.agentwork.standardwork;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cnd3b.common.Controller;
import com.cnd3b.common.D3bException;
import com.cnd3b.common.actionscore.ActionScore;
import com.cnd3b.common.data.Row;
import com.cnd3b.common.data.Rows;
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.HashMap;

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

    /**
     * 标准工作列表查询
     *
     * @return
     */
    public String query_standardworkList() {
        /**
         *排序条件设置
         */
        String[] sortfield = {"t1.changedate"};
        String sort = getSort(sortfield, "t1.changedate desc");

        /**
         * 过滤条件设置
         */
        StringBuffer where = new StringBuffer(" 1=1 ");
        if (content.containsKey("where")) {
            JSONObject whereObject = content.getJSONObject("where");
            if (whereObject.containsKey("condition") && !"".equals(whereObject.getString("condition"))) {
                where.append(" and(");
                where.append("t2.fname like'%").append(whereObject.getString("condition")).append("%' ");
                where.append(" or t3.fstorename like'%").append(whereObject.getString("condition")).append("%' ");
                where.append(")");
            }
            if (whereObject.containsKey("createdate") && !"".equals(whereObject.getString("createdate"))) {
                where.append(" and(");
                where.append("convert(varchar(10),t1.createdate,120) ='").append(whereObject.getString("createdate")).append("' ");
                where.append(")");
            }
        }
        SQLFactory costhead = new SQLFactory(this, "标准工作列表", pageSize, pageNumber, sort);
        costhead.addParameter("siteid", siteid);
        costhead.addParameter_in("tenterprise_userid", getSubUsers());
        costhead.addParameter_SQL("where", where);
        Rows rows = dbConnect.runSqlQuery(costhead.getSQL());
        return getSucReturnObject().setDataByPaging(rows, sortfield).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 标准工作主界面查询
     *
     * @return
     */
    public String query_standardworkMain() {
        SQLFactory headsql = new SQLFactory(this, "标准工作主界面查询");
        headsql.addParameter("siteid", siteid);
        headsql.addParameter("tworkid", content.getString("tworkid"));
        Rows rows = dbConnect.runSqlQuery(headsql.getSQL());
        for (Row row : rows) {
            SQLFactory bzworkmx = new SQLFactory(this, "标准工作明细查询");
            bzworkmx.addParameter("siteid", siteid);
            bzworkmx.addParameter("tworkid", content.getString("tworkid"));
            Rows bzworkrows = dbConnect.runSqlQuery(bzworkmx.getSQL());

            row.put("workmxlist", bzworkrows.toJsonArray());
            row.put("datalog", getDataLog("tbusinesstripid", row.getString("tbusinesstripid")));
        }
        return getSucReturnObject().setData(rows).toString();
    }

    /**
     * 标准工作新增、修改
     *
     * @return
     */
    public String standardworkInsertOrModify() throws D3bException, P2Exception {
        long tworkid = content.getLongValue("tworkid");//标准工作ID，新增时默认为0
        long tbusinesstripid = content.getLongValue("tbusinesstripid");//出差行程ID
        int fdays = content.getIntValue("fdays");//工作时间
        long tagentsid = content.getLongValue("tagentsid");//经销商id
        long tstoreid = content.getLongValue("tstoreid");//门店ID
        String fdate = content.getString("fdate");

        JSONArray workmx = content.getJSONArray("workmx");
        for (Object object : workmx) {
            JSONObject workmxobject = (JSONObject) object;
            workmxobject.getString("fnotes", "tworkmx.fnotes", "工作备注");
        }

        PaoSetRemote tworkSet = getP2ServerSystemPaoSet("twork", "siteid='" + siteid + "' and tworkid='" + tworkid + "'");
        PaoRemote twork = null;
        if (tbusinesstripid <= 0 || tworkSet.isEmpty()) {
            twork = tworkSet.addAtEnd();
            twork.setValue("siteid", siteid, 11L);//企业ID
            twork.setValue("fworktype", "标准", 11L);//工作类型
            twork.setValue("tagentsid", tagentsid, 11L);//经销商ID
            twork.setValue("tbusinesstripid", tbusinesstripid, 11L);
            twork.setValue("createby", username, 11L);//录入人
            twork.setValue("createdate", sysdate, 11L);//录入时间

            addActionScore(ActionScore.fsourcetype.标准工作录入, twork.getUniqueIDValue(), "标准工作录入");
        } else {
            twork = tworkSet.getPao(0);
        }
        twork.setValue("tstoreid", tstoreid, 11L);//门店id
        twork.setValue("fdate", fdate, 11L);
        twork.setValue("fdays", fdays, 11L);//工作时间
        twork.setValue("changeby", username, 11L);//修改人
        twork.setValue("changedate", sysdate, 11L);//修改时间
        PaoSetRemote tworkmxSet = twork.getPaoSet("$tworkmx", "tworkmx", "siteid='" + siteid + "' and tbusinesstripid=" + tbusinesstripid + " and tworkid=" + tworkid);
        HashMap<String, PaoRemote> paomap = getPaoMap(tworkmxSet, "fworkname");
        for (Object o : workmx) {
            JSONObject workmxobject = (JSONObject) o;
            long tworkmxid = workmxobject.getLongValue("tworkmxid");
            String ftype = workmxobject.getString("ftype");
            String fworkname = workmxobject.getString("fworkname");
            String fnotes = workmxobject.getString("fnotes");
            int fdocqty = workmxobject.getIntValue("fdocqty");
            boolean fisimage = workmxobject.getBooleanValue("fisimage");
            boolean fiseditnote = workmxobject.getBooleanValue("fiseditnote");

            PaoRemote tworkmx = null;
            if (tworkmxid <= 0 || !paomap.containsKey(fworkname)) {
                tworkmx = tworkmxSet.addAtEnd();
                tworkmx.setValue("siteid", siteid, 11L);//企业ID
                tworkmx.setValue("tbusinesstripid", tbusinesstripid, 11L);
                tworkmx.setValue("tworkid", twork.getUniqueIDValue(), 11L);//工作类型
                tworkmx.setValue("ftype", ftype, 11L);//门店、经销商
                tworkmx.setValue("fworkname", fworkname, 11L);//工作名称
                tworkmx.setValue("fdocqty", fdocqty, 11L);//附件数量
                tworkmx.setValue("fisimage", fisimage, 11L);//是否图片附件
                tworkmx.setValue("fiseditnote", fiseditnote, 11L);//是否需要备注
            } else {
                tworkmx = paomap.get(fworkname);
            }
            tworkmx.setValue("fnotes", fnotes, 11L);//工作备注
        }
        content.put("tworkid", twork.getUniqueIDValue());
        saveDataLog(twork);
        tworkSet.save();

        return query_standardworkMain();
    }

    /**
     * 标准工作删除
     *
     * @return
     */
    public String standardworkDelete() {
        SQLFactory sqlFactory = new SQLFactory(this, "标准工作删除");
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("tworkid", content.getString("tworkid"));

        String result = dbConnect.runSqlUpdate(sqlFactory.getSQL());
        if ("true".equals(result)) {
            return getSucReturnObject().toString();
        } else {
            return getErrReturnObject().setErrMsg(result).toString();
        }
    }
    /**
     * 出差行程直接从出差行程列表中查询
     */
    /**
     * 经销商门店选择列表查询
     *
     * @return
     */
    public String query_agentstoreList() {
        SQLFactory sqlFactory = new SQLFactory(this, "经销商门店列表查询");
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("tagentsid", content.getString("tagentsid"));
        Rows rows = dbConnect.runSqlQuery(sqlFactory.getSQL());
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }

    /**
     * 标准工作模板列表查询
     *
     * @return
     */
    public String query_standardworkTemplateList() {
        SQLFactory sql = new SQLFactory(this, "标准工作模板查询");
        sql.addParameter("siteid", siteid);
        Rows rows = dbConnect.runSqlQuery(sql.getSQL());
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }

}
