package com.hzya.frame.seeyon.service.impl;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.seeyon.dao.ICapFormDefinitionDao;
import com.hzya.frame.seeyon.entity.CapFormDefinitionEntity;
import com.hzya.frame.seeyon.service.INoProcessService;
import com.hzya.frame.web.entity.JsonResultEntity;
import org.apache.commons.collections.CollectionUtils;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 *
 * @content 无流程表单公用service
 * @className: Administrator
 * @author laborer
 * @date 2024-09-09 14:53
 *
 */

@Service(value = "NoProcessServiceImpl")
public class NoProcessServiceImpl implements INoProcessService {
    private static final Logger logger = LoggerFactory.getLogger(NoProcessServiceImpl.class);
    @Autowired
    private ICapFormDefinitionDao capFormDefinitionDao;
    @Override
    public JsonResultEntity DeleteProcessField(JSONObject requestData) {
        List<String>count  =new ArrayList<>();
        JSONObject jsonStrObj = requestData.getJSONObject("jsonStr");
        String formCode = jsonStrObj.getString("formCode");
        String fieldName = jsonStrObj.getString("fieldName");
        String fieldValue = jsonStrObj.getString("fieldValue");
        if(StrUtil.isEmpty(formCode)){
            return new JsonResultEntity("表单编码不能为空：formCode",false);
        }
        if(StrUtil.isEmpty(fieldName)){
            return new JsonResultEntity("字段名称不能为空：fieldName",false);
        }
        if(StrUtil.isEmpty(fieldValue)){
            return new JsonResultEntity("字段值不能为空：fieldValue",false);
        }

        //通过表单编号获取表单字段信息
        CapFormDefinitionEntity fieldInfo = new CapFormDefinitionEntity();
        fieldInfo.setAppbindInfo(formCode);
        fieldInfo.setDataSourceCode("djoatest");
        List<CapFormDefinitionEntity>capFormDefinitionEntityList = capFormDefinitionDao.getFormFiled(fieldInfo);
        if(CollectionUtils.isEmpty(capFormDefinitionEntityList)){
            return new JsonResultEntity("通过表单编号查询表单有误，请检查表单编号："+formCode,false);
        }

        try {
            capFormDefinitionEntityList.forEach(item->{
                String appbindInfo = item.getAppbindInfo();
                //格式化字段信息
                JSONObject jsonObject = JSONObject.parseObject(appbindInfo);
                boolean queryFlag = false;
                //如果模版编号相同则继续删除，反正跳过
                if(formCode.equals(jsonObject.getString("formCode"))){
                    JSONObject field = JSONObject.parseObject(item.getFieldInfo());
                    JSONObject frontFormmain = field.getJSONObject("front_formmain");
                    JSONArray formsons = field.getJSONArray("formsons");
                    JSONArray fieldInfoTable =  frontFormmain.getJSONArray("fieldInfo");
                    //验证需要删除的条件字段在表单属性中是否存在
                    for (int i = 0; i < fieldInfoTable.size(); i++) {
                        JSONObject fieldInfoTableObj = fieldInfoTable.getJSONObject(i);
                        String name = fieldInfoTableObj.getString("name");
                        //如果表单属性中存在该字段则验证通过，如果不存在直接返回错误
                       if(name.equals(fieldName)){
                           queryFlag = true;

                       }
                    }
                    //验证通过获取数据库表名称进行数据删除
                    if(queryFlag){
                        String tableName = frontFormmain.getString("tableName");
                        //如果主表名称获取主表的主键进行数据删除
                        fieldInfo.setTableName(tableName);
                        fieldInfo.setFieldName(fieldName);
                        fieldInfo.setFieldValue(fieldValue);
                        List<CapFormDefinitionEntity>dataFormList = capFormDefinitionDao.getFormFiledByFileValue(fieldInfo);
                        if(CollectionUtils.isNotEmpty(dataFormList)){
                            dataFormList.forEach(item1->{
                                String id = item1.getId();
                                count.add(id);
                                fieldInfo.setFieldName("id");
                                fieldInfo.setId(id);
                                capFormDefinitionDao.deleteByKey(fieldInfo);
                                //循环该表单下面的所有子表信息进行子表删除
                                if(CollectionUtils.isNotEmpty(formsons)){
                                    formsons.forEach(formsonsItem->{
                                        JSONObject jsonObjectBoddy = JSONObject.parseObject(formsonsItem.toString());
                                        String bodyTableName = jsonObjectBoddy.getString("tableName");
                                        fieldInfo.setTableName(bodyTableName);
                                        fieldInfo.setFieldName("formmain_id");
                                        fieldInfo.setId(id);
                                        capFormDefinitionDao.deleteByKey(fieldInfo);
                                    });
                                }
                            });
                        }
                    }
                }
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return new JsonResultEntity("删除成功,删除的数据ID"+ JSON.toJSONString(count),true);
    }
}
