package com.teemlink.kujiale.controller;

import cn.myapps.common.util.StringUtil;
import cn.myapps.runtime.dynaform.document.ejb.Document;
import cn.myapps.runtime.dynaform.document.ejb.DocumentProcess;
import cn.myapps.runtime.dynaform.document.ejb.Item;
import cn.myapps.util.ProcessFactory;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.teemlink.kujiale.util.KujialeUtil;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;

@RestController
@RequestMapping(path = "/api/runtime/kujiale", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class KujialeController {

    @GetMapping("/users/{id}/designs")
    public ResultData getUserDesignList(@PathVariable String id, @RequestParam String email, @RequestParam String name, @RequestParam(required = false) String orderreadableid) throws Exception{
        KujialeUtil kujialeUtil = new KujialeUtil();
        JSONObject json = kujialeUtil.getUserDesignList(name, email, id);
        //需要列出已关联方案
        if(!StringUtil.isBlank(orderreadableid)){
            JSONArray result = json.getJSONArray("result");
            JSONObject associateJson = kujialeUtil.getUserOrderAndDesignAssociateList(name, email, id);
            JSONArray associateList = associateJson.getJSONArray("result");
            //获取所有已关联的方案
            String designIds = "";
            for(Iterator iterator = associateList.iterator(); iterator.hasNext();){
                JSONObject associate = (JSONObject)iterator.next();
                boolean orderAssociated = associate.getBoolean("orderAssociated");
                if(orderAssociated) {
                    String designId = associate.getString("designId");
                    if(designIds.equals("")){
                        designIds = designId;
                    } else {
                        designIds = designIds + "," + designId;
                    }
                }
            }

            for (Iterator iterator = result.iterator(); iterator.hasNext();){
                JSONObject design = (JSONObject)iterator.next();
                String designId = design.getString("designId");
                if(designIds.contains(designId)){
                    design.put("orderAssociated", true);
                }
            }
        }
        return new ResultData(0, "ok", json);
    }

    @GetMapping("/users/{id}/designs/{designid}/url")
    public ResultData getDesignUrl(@PathVariable String id, @PathVariable String designid, @RequestParam String email, @RequestParam String name) throws Exception{
        String result = new KujialeUtil().getDesignUrl(name, designid, email, id);
        return new ResultData(0, "ok", result);
    }

    @GetMapping("/users/designs/{designid}/renderpic")
    public ResultData getUserDesignRenderpicList(@PathVariable String designid) throws Exception{
        JSONObject json = new KujialeUtil().getUserDesignRenderpicList(designid);
        return new ResultData(0, "ok", json);
    }

    @PutMapping("/users/{id}/orders/{orderreadableid}/associate")
    public ResultData associateOrderAndDesign(@PathVariable String id, @PathVariable String orderreadableid, String designIds, @RequestParam(required = false) String applicationId, @RequestParam(required = false) String docId, @RequestParam(required = false) String fieldName,  @RequestParam String email,  @RequestParam String name) {
        try{
            boolean result = new KujialeUtil().associateCusOrderAndDesign(name, orderreadableid, designIds, email, id);
            if(result && !StringUtil.isBlank(docId)){
                DocumentProcess documentProcess = (DocumentProcess) ProcessFactory.createRuntimeProcess(DocumentProcess.class, applicationId);
                Document doc = (Document)documentProcess.doView(docId);
                Item item = doc.findItem(fieldName);
                if(item.getValue() != null && !StringUtil.isBlank(item.getVarcharvalue())){
                    item.setValue(item.getValue()+","+designIds);
                } else {
                    item.setValue(designIds);
                }
                documentProcess.doUpdate(doc);
            }
            return new ResultData(0, "ok", result);
        } catch (Exception e){
            e.printStackTrace();
            return new ResultData(500, e.getMessage());
        }
    }

    @PutMapping("/users/{id}/orders/{orderreadableid}/cancelAssociate")
    public ResultData cancelAssociateOrderAndDesign(@PathVariable String id, @PathVariable String orderreadableid, String designId, @RequestParam(required = false) String applicationId, @RequestParam(required = false) String docId, @RequestParam(required = false) String fieldName,  @RequestParam String email,  @RequestParam String name) {
        try{
            boolean result = new KujialeUtil().cancelAssociateCusOrderAndDesign(name, orderreadableid, designId, email, id);
            String value = "";
            if(result && !StringUtil.isBlank(docId)){
                DocumentProcess documentProcess = (DocumentProcess) ProcessFactory.createRuntimeProcess(DocumentProcess.class, applicationId);
                Document doc = (Document)documentProcess.doView(docId);
                Item item = doc.findItem(fieldName);
                String[] values = item.getVarcharvalue().split(",");
                for(int i=0; i<values.length; i++){
                    String val = values[i];
                    if(!designId.equals(val)){
                        if("".equals(value)){
                            value = val;
                        } else {
                            value = value + "," + val;
                        }
                    }
                }
                item.setValue(value);
                documentProcess.doUpdate(doc);
            }
            return new ResultData(0, "ok", value);
        } catch (Exception e){
            e.printStackTrace();
            return new ResultData(500, e.getMessage());
        }
    }
}
