package cn.com.capcloud.api.action.myself.system.data;

import cn.com.capcloud.api.action.service.ApiService;
import cn.com.capcloud.ccui.core.common.json.JackJSON;
import cn.com.capcloud.ccui.core.common.json.JackJSONArray;
import cn.com.capcloud.ccui.core.common.json.JackJSONObject;
import cn.com.capcloud.core.cache.KHCRedisCache;
import cn.com.capcloud.core.cache.BaseConfigStaticCache;
import cn.com.capcloud.core.noentitydb.BaseService;
import cn.com.capcloud.core.noentitydb.DefaultAction;
import cn.com.capcloud.core.system.user.UserService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Component
public class DataFormAction extends DefaultAction {
    //表单按钮组件的默认数据(KEY)
    private static final String SYSTEM_SETTINGS_DS_FORM_BUTTON_JSON="system.settings.ds.form.button.json";
    @Resource
    private BaseService baseService;
    @Resource
    private UserService userService;
    @Resource
    private ApiService apiService;
    @Resource
    private KHCRedisCache khcRedisCache;
    private static DataFormAction action;
    @PostConstruct
    public void init(){
        action=this;
        action.baseService=this.baseService;
        action.userService=this.userService;
        action.apiService =this.apiService;
        action.khcRedisCache =this.khcRedisCache;
    }
    public Map<String,Object> copy(String jsonStr, JackJSONObject retJson, HttpServletRequest request){
        JackJSONObject json= JackJSONObject.fromObject(jsonStr);
        Map<String,Object> map=new HashMap<>();
        String pageParentUuid = String.valueOf(json.get("page_parent_uuid"));
        String oldCode = String.valueOf(json.get("oldCode"));
        String newCode = String.valueOf(json.get("newCode"));
        String sql = "SELECT * FROM  tbl_data_form_info WHERE status=0 and page_parent_uuid='"+pageParentUuid+"'";
        List<Map<String, Object>> list = this.getJdbcTemplate().queryForList(sql);
        String formUUIDSql="SELECT uuid FROM `tbl_data_form` WHERE status=0 and form_code= '"+newCode+"'";
        String formUUID=this.getJdbcTemplate().queryForObject(formUUIDSql,String.class);
        for (Map listInfo : list) {
            listInfo.remove("id");
            listInfo.put("page_parent_uuid", formUUID);
            action.baseService.save("tbl_data_form_info", listInfo);
        }
        map.put("message","复制成功");
        return map;
    }

    @Override
    public JackJSONArray saveAfter(String jsonStr, JackJSONObject retJson, HttpServletRequest request, JackJSONArray array) {
        String parentUUID=String.valueOf(array.getJackJSONObject(0).get("uuid"));
        String sql="SELECT count(1) FROM tbl_data_button WHERE status=0 and page_parent_uuid='"+parentUUID+"'";
        List<Map<String,Object>> list= JackJSON.parseObject(String.valueOf(BaseConfigStaticCache.get(SYSTEM_SETTINGS_DS_FORM_BUTTON_JSON)), ArrayList.class);
        for (int i = 0; i < list.size(); i++) {
            Integer count=this.getJdbcTemplate().queryForObject(sql+" and button_method='"+list.get(i).get("button_method")+"'",Integer.class);
            if(count>0){
                continue;
            }
            String uuid= UUID.randomUUID().toString().replaceAll("-","");
            list.get(i).put("uuid",uuid);
            list.get(i).put("page_parent_uuid",parentUUID);
            action.baseService.save("tbl_data_button", list.get(i));
            action.khcRedisCache.deleteAllButton();//清除缓存的按钮信息
        }
        return array;
    }
    //部署新表单
    public Map<String,Object> deploy(String jsonStr, JackJSONObject retJson, HttpServletRequest request){
        int version=1;
        try {
            JackJSONObject json= JackJSONObject.fromObject(jsonStr);
            String dsCode = String.valueOf(json.get("ds_code"));
            String formCode = String.valueOf(json.get("form_code"));
            Map<String,Object> dsMap=action.apiService.findDataSourceByCode(dsCode);
            Map<String,Object> formMap=action.apiService.getForm(String.valueOf(dsMap.get("id")),formCode);
            // 查询历史版本，计算出下一个版本
            String vSql="SELECT * FROM tbl_data_form_info_v WHERE STATUS=0 AND form_id= " +formMap.get("id") +" order by form_version desc limit 1";
            List<Map<String, Object>> vList=this.getJdbcTemplate().queryForList(vSql);
            if(vList.size()>0){
                String versionStr=String.valueOf(vList.get(0).get("form_version"));
                version=Integer.valueOf(versionStr)+1;
            }
            Map<String,Object> formVMap=new HashMap<>();
            formVMap.put("form_version",version);
            formVMap.put("ds_id",dsMap.get("id"));
            formVMap.put("page_parent_uuid",formMap.get("uuid"));
            formVMap.put("form_code",formCode);
            formVMap.put("form_name",formMap.get("form_name"));
            // save新发布的表单信息版本
            action.baseService.save("tbl_data_form_info_v",formVMap);
            // update 更新表单版本version
            String updateVersionSql="UPDATE tbl_data_form SET form_version="+version+" WHERE id="+formMap.get("id");
            this.getJdbcTemplate().execute(updateVersionSql);

            String sql="SELECT * FROM tbl_data_form_info WHERE STATUS=0 AND page_parent_uuid= '" +formMap.get("uuid")+"'";
            List<Map<String, Object>> list=this.getJdbcTemplate().queryForList(sql);
            for (int i = 0; i < list.size(); i++) {
                Map<String,Object> map=list.get(i);
                map.remove("id");
                map.put("form_version",version);
                map.put("form_code",formCode);
                action.baseService.save("tbl_data_form_info_h",map);
            }
        } catch (Exception e) {

        }
        Map<String,Object> map=new HashMap<>();
        map.put("message","部署成功");
        map.put("version",version);
        return map;
    }
    public Map<String,Object> getFormToDict(String jsonStr, JackJSONObject retJson, HttpServletRequest request){
        JackJSONObject json= JackJSONObject.fromObject(jsonStr);
        String bpmFormCode = String.valueOf(json.get("bpmFormCode"));
        String sql="SELECT * FROM tbl_data_form WHERE STATUS=0 and form_code='"+bpmFormCode+"'";
        Map<String,Object> formMap=this.getJdbcTemplate().queryForMap(sql);
        String queryFormInfoSql="SELECT * FROM tbl_data_form_info WHERE STATUS=0 and page_parent_uuid='"+formMap.get("uuid")+"' order by field_sort asc";
        List<Map<String, Object>> formInfoList=this.getJdbcTemplate().queryForList(queryFormInfoSql);
        String queryButtonSql="SELECT * FROM tbl_data_button WHERE STATUS=0 and button_status=0 and page_parent_uuid='"+formMap.get("uuid")+"' order by button_sort asc";
        List<Map<String, Object>> buttonList=this.getJdbcTemplate().queryForList(queryButtonSql);
        List<Map<String,Object>> formInfoDictList=new ArrayList<>();
        List<Map<String,Object>> buttonDictList=new ArrayList<>();
        for (int i = 0; i < formInfoList.size(); i++) {
            Map<String,Object> dictMap=new HashMap<>();
            String key=String.valueOf(formInfoList.get(i).get("name"));
            String labelName=String.valueOf(formInfoList.get(i).get("label_name"));
            String showType=String.valueOf(formInfoList.get(i).get("show_type"));
            String value=labelName+"_"+showType;
            if((labelName.equals("null")||labelName.length()==0)||(showType.equals("hidden"))){
                continue;
            }
            dictMap.put("key",key);
            dictMap.put("value",value);
            formInfoDictList.add(dictMap);
        }
        for (int i = 0; i < buttonList.size(); i++) {
            Map<String,Object> dictMap=new HashMap<>();
            String key=String.valueOf(buttonList.get(i).get("button_name"));
            String buttonTitle=String.valueOf(buttonList.get(i).get("button_title"));
            String value=buttonTitle+"("+key+")";
            dictMap.put("key",key);
            dictMap.put("value",value);
            buttonDictList.add(dictMap);
        }
        Map<String,Object> map=new HashMap<>();
        JackJSONObject dataJson=new JackJSONObject();
        dataJson.put("form",formMap);
        dataJson.put("formInfoDict",formInfoDictList);
        dataJson.put("buttonDict",buttonDictList);
        map.put("message","查询成功");
        map.put("data",dataJson);
        return map;
    }
}
