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.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.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.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.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 【请填写功能名称】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);
        return AjaxResult.success(resultMap);
    }
   /* @ApiOperation("修改表名")
    @PostMapping("/altTableName/{oldtableName}")
    public AjaxResult alterTableName(@PathVariable("oldtableName") String oldtableName,String newtableName){
        int s = tbFormService.alterTableName(oldtableName,newtableName);
        if(s == 0){
            s=1;
            return toAjax(s);
        }
        return toAjax(s);
    }*/

    /**
     * 动态根据表名创建表
     */
    @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);
        System.err.println(tbForm.getFormTitle());
        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;
        System.err.println("-------------------------------------------------------------------------------------------------------------------");
        int s = tbFormService.selecltTable(tableName);
        System.err.println(s);
        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();
        System.err.println(action);
        String form = action.replace("form_", "");
        System.err.println(form);
        tbForm.setAction(form);
        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) {
        System.err.println("aaaaaaa        " + tbForm.getAction());
        String s1 = "form_" + tbForm.getAction();
        System.err.println("s1:         " + s1);
        tbForm.setAction(s1);
        newtableName = s1;
        System.err.println("asdasd" + tbForm);
        System.err.println("旧值:                    " + oldtableName);
        System.err.println("新值:                    " + newtableName);
        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);
        System.err.println(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;
    }

}
