package com.ruoyi.project.system.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.TbForm;
import com.ruoyi.project.system.domain.TbFormModule;
import com.ruoyi.project.system.service.ITbFormModuleService;
import com.ruoyi.project.system.service.ITbFormService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2020-06-16
 */
@Api("用户信息管理")
@RestController
@RequestMapping("/system/form")
public class TbFormController extends BaseController {
    @Autowired
    private ITbFormService tbFormService;
    @Autowired
    private ITbFormModuleService tbFormModuleService;

    String oldtableName = null;
    String newtableName = null;


    /**
     * 根据id查询表信息
     * @param tableName 表名
     * @param id 信息id
     * @return 查询数据
     */
    @GetMapping(value = "/selAutoTableById/{tableName}/{id}")
    public AjaxResult selAutoTableById(@PathVariable("tableName") String tableName,@PathVariable("id") Long id) {
        Map resultMap = tbFormService.selAutoTableById("form_"+tableName, id);
        List<Object> objects = JSONArray.parseArray((String) resultMap.get("vueJson"));
        List<Object> obj=new ArrayList<>();
        for(Object o :objects){
            Map maps=(Map)JSON.parse(o.toString());
            String s = (String) maps.get("vModel");
            String v = (String) resultMap.get(s);
            String defaultValue="defaultValue" ;
            maps.put(defaultValue, v);
            obj.add(maps);
        }
        resultMap.put("vueJson",obj);
        System.err.println(obj);
        System.err.println("resultMap:"+resultMap);
//        StringBuilder stringBuilder = new StringBuilder(o);
//        //int i2 = StringUtils.ordinalIndexOf(o, "\"vModel\":\"" + vModel + "\"", 1);
//      //  StringBuilder insert2 = stringBuilder.insert(i2, "\"defaultValue\":\"" + o2 + "\",");
//        System.err.println(o);
//        List<Object> objects = JSONArray.parseArray(o);
//        for (int i = 0; i <objects.size() ; i++) {
//            Object o1 = objects.get(i);
//            JSONObject jsonObject = (JSONObject) JSON.toJSON(o1);
//            String vModel = jsonObject.getString("vModel");
//            System.err.println("vModel:"+vModel);
//            Object o2 = resultMap.get(vModel);
//            boolean status = o.contains("\"defaultValue\":\"" + o2 + "\",");
//            if (!status){
//                int i1 = StringUtils.ordinalIndexOf(o, "\"vModel\":\"" + vModel + "\"", 1);
//                StringBuilder insert = stringBuilder.insert(i1, "\"defaultValue\":\"" + o2 + "\",");
//                System.err.println("insert"+insert);
//                System.err.println("i1:"+i1);
//                resultMap.put("vueJson",insert);
//                System.err.println();
//            }
//            System.err.println("o2:"+o2);
//        }
        return AjaxResult.success(resultMap);
    }


    /**
     * 动态根据表名创建表
     */
    @PreAuthorize("@ss.hasPermi('system:form:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @GetMapping(value = "/createTable/{action}/{ms}")
    @ResponseBody
    public AjaxResult createTable(@PathVariable("action") String tableName, @PathVariable("ms") String ms) {
        tableName = "form_" + tableName;
        System.err.println(tableName);
        int result = tbFormService.createTable(tableName);
        //System.err.println(result);
        TbForm tbForm = new TbForm();
        tbForm.setFormId(UUID.randomUUID().toString().replaceAll("-", ""));
        tbForm.setAction(tableName);
        tbForm.setFormTitle(ms);
        int s = tbFormService.insertTbForm(tbForm);
        if (s != 0) {
            System.err.println("插入数据成功");
        }
        return toAjax(s);
    }


    /**
     * 查询是否表名已存在
     */
    @ApiOperation("查询是否表名已存在")
    @PreAuthorize("@ss.hasPermi('system:form:selTable')")
    @GetMapping(value = "/selTable/{tableName}")
    public AjaxResult selTable(@PathVariable("tableName") String tableName) {

        tableName = "form_" + tableName;
        int s = tbFormService.selecltTable(tableName);

        return AjaxResult.success(s);
    }

    /**
     * 新增自定义表
     */
    @PostMapping(value = "/addAutoForm")
    @ResponseBody
    public AjaxResult addAutoForm(@RequestBody List<TbForm> typeList) {
        return null;
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:form:list')")
    @GetMapping("/list")
    public TableDataInfo list(TbForm tbForm) {
        startPage();
        List<TbForm> list = tbFormService.selectTbFormList(tbForm);
        for (int i = 0; i < list.size(); i++) {
            String aa = list.get(i).getAction();
            String form = aa.replace("form_", "");
            list.get(i).setAction(form);
        }
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:form:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TbForm tbForm) {
        List<TbForm> list = tbFormService.selectTbFormList(tbForm);
        ExcelUtil<TbForm> util = new ExcelUtil<TbForm>(TbForm.class);
        return util.exportExcel(list, "form");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:form:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        TbForm tbForm = tbFormService.selectTbFormById(id);
        String action = tbForm.getAction();
        oldtableName = tbForm.getAction();
        String form = action.replace("form_", "");
        tbForm.setAction(form);
        return AjaxResult.success(tbForm);
    }


    @PreAuthorize("@ss.hasPermi('system:form:query')")
    @GetMapping(value = "action/{action}")
    //@Test
    public AjaxResult getInfo1(@PathVariable("action") String action) {
        System.err.println("form_"+action);
        TbForm tbForm = tbFormService.selectTbFormByAction("form_"+action);
        return AjaxResult.success(tbForm);
    }


    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:form:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TbForm tbForm) {
        return toAjax(tbFormService.insertTbForm(tbForm));
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:form:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TbForm tbForm) {
        String s1 = "form_" + tbForm.getAction();
        tbForm.setAction(s1);
        newtableName = s1;
        int s = tbFormService.alterTableName(oldtableName, newtableName);
        int i = tbFormService.updateTbForm(tbForm);
        if (s == 0) {
            s = 1;
            return toAjax(s);
        }
        return toAjax(i);
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:form:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{action}")
    public AjaxResult remove(@PathVariable("action") String[] action) {
        String filePath=null;
        for (int i = 0; i < action.length; i++) {
            action[i] = "form_" + action[i];
            System.err.println();
            filePath  =System.getProperty("user.dir")+"/ruoyi-ui/src/views/system/autoform/config/"+action[i]+".vue";
        }
        int i2= tbFormModuleService.deleteTbFormModuleByIds(action);
        int i = tbFormService.deleteTbFormByIds(action);
        int i1 = tbFormService.deleteTable1(action);
        // deleteFile(filePath);
        return toAjax(i + i1+i2);
    }
    /**
     * 删除单个文件
     * @param
     * @return 单个文件删除成功返回true，否则返回false
     */
    public boolean deleteFile(String filePath) {
        System.err.println(filePath);
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }



    /**
     * 根据表名修改表结构
     *
     * @param tableName 表名
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:form:altTable')")
    @PostMapping(value = "/altTable/{tableName}")
    public AjaxResult altTalbe(@PathVariable("tableName") String tableName, @RequestParam("filde") String fildes, @RequestParam("vueJson") String vueJson) throws IOException {
        tableName = "form_" + tableName;
        int i = tbFormService.altTalbe(tableName, fildes, vueJson);
        String path = System.getProperty("user.dir")+"/ruoyi-ui/src/views/system/autoform/config/"+tableName+".vue";
        // ceateFileVue(vueJson,path);
        return toAjax(i);
    }

    @PostMapping(value = "/findfield/{tableName}")
    public AjaxResult findfield(@PathVariable("tableName") String tableName) {
        String i = tbFormService.selecltTableBytabName("form_" + tableName);

        return AjaxResult.success("ok", i);
    }



    /**
     * 新建vue文件
     * @param vueTest
     * @param filePath
     * @throws IOException
     */
    public void ceateFileVue(String vueTest, String filePath) throws IOException {
        System.err.println(filePath);
        createFile(filePath);
        FileWriter fileWriter = new FileWriter(filePath);
        try {
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(vueTest);
            bufferedWriter.close();
        } catch (Exception e) {

            e.printStackTrace();

        }
    }
    /**
     * 此方法的作用主要是判断创建文件是否成功，成功则返回true，否则则返回false
     * @param destFileName is 目标文件
     * @return true or false
     */
    public boolean createFile(String destFileName) {

        File file = new File(destFileName);//根据指定的文件名创建File对象

        //要创建的单个文件已存在
        if (file.exists()) {
            System.out.println("文件" + destFileName + "已存在，创建失败！");
            return false;
        }


        //如果输入的文件是以分隔符结尾的，则说明File对象是目录而不是文件
        if (destFileName.endsWith(File.separator)) {
            System.out.println("文件" + destFileName + "是目录，目标文件不能是目录，创建失败！");
            return false;
        }

        //判断目标文件所在目录是否存在
        if (!file.getParentFile().exists()) {//如果目标文件所在文件夹不存在，则创建父文件夹
            System.out.println("创建" + file.getName() + "所在目录不存在，正在创建！");

            //判断父文件夹是否存在，如果存在则表示创建成功，否则失败
            if (!file.getParentFile().mkdirs()) {
                System.out.println("创建目标文件所在目录失败！");
                return false;
            }
        }
        return true;
    }

}
