package com.izouma.awesomeadmin.web;

import java.io.File;
import java.util.*;

import com.google.gson.Gson;
import com.izouma.awesomeadmin.model.DataSourceInfo;
import com.izouma.awesomeadmin.model.GenCode;
import com.izouma.awesomeadmin.model.TableField;
import com.izouma.awesomeadmin.service.DataSourceInfoService;
import com.izouma.awesomeadmin.util.DatabaseUtil;
import com.izouma.awesomeadmin.util.PinYinUtil;
import com.izouma.codegenerator.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.text.CaseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.izouma.awesomeadmin.constant.AppConstant;
import com.izouma.awesomeadmin.dto.Page;
import com.izouma.awesomeadmin.dto.Result;
import com.izouma.awesomeadmin.service.GenCodeService;
import org.springframework.web.context.ContextLoader;

/**
 * gen_code_model controller类
 * Fri May 04 15:57:06 CST 2018  Suo Chen Cheng
 */
@Controller
@RequestMapping("/genCode")
public class GenCodeController {

    @Autowired
    private GenCodeService genCodeService;

    @Autowired
    private DataSourceInfoService dataSourceInfoService;

    /**
     * <p>获取全部记录。</p>
     */
    @RequestMapping(value = "/all", method = RequestMethod.GET)
    @ResponseBody
    public Result all(GenCode record) {

        List<GenCode> pp = genCodeService.getGenCodeList(record);
        return new Result(true, pp);
    }

    /**
     * <p>根据Id。</p>
     */
    @RequestMapping(value = "/getGenCode", method = RequestMethod.GET)
    @ResponseBody
    public Result getGenCode(@RequestParam(required = false, value = "id") String id) {

        GenCode data = genCodeService.getGenCodeById(id);
        return new Result(true, data);
    }

    /**
     * <p>根据条件获取。</p>
     */
    @RequestMapping(value = "/getOne", method = RequestMethod.GET)
    @ResponseBody
    public Result getOne(GenCode record) {

        GenCode data = genCodeService.getGenCode(record);
        return new Result(true, data);
    }

    /**
     * <p>分页查询。</p>
     */
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    @ResponseBody
    public Result page(Page page, GenCode record) {

        Map<String, Object> result = new HashMap<>();

        List<GenCode> pp = genCodeService.getGenCodeByPage(page, record);

        result.put(AppConstant.PAGE, page);
        result.put("pp", pp);
        return new Result(true, result);
    }

    /**
     * <p>保存。</p>
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public Result save(@RequestBody GenCode record) {
        try {
            Gson gson = new Gson();
            record.setGenJson(gson.toJson(record));
            genCode(record);

            genCodeService.createGenCode(record);
            return new Result(true, record.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, "保存异常");
    }


    /**
     * <p>更新信息。</p>
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Result updateGenCode(@RequestBody GenCode record) {
        try {
            Gson gson = new Gson();
            record.setGenJson(gson.toJson(record));
            genCode(record);

            boolean num = genCodeService.updateGenCode(record);
            if (num) {
                return new Result(true, "保存成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new Result(false, "保存异常");
    }

    /**
     * 生成代码
     *
     * @param record
     * @throws Exception
     */
    private void genCode(@RequestBody GenCode record) throws Exception {
        String tableName = record.getTableName();

        if (PinYinUtil.isContainChinese(tableName)) {
            tableName = PinYinUtil.getStringPinYin(tableName);
        }

        if (StringUtils.isNotEmpty(record.getClassName())) {
            //手动填写
            record.setClassName(CaseUtils.toCamelCase(record.getClassName(), true, '_'));
        } else {
            //根据表名生成类名
            record.setClassName(CaseUtils.toCamelCase(tableName, true, '_'));
        }

//        if (record.getReadTable()) {
//            ReadTableGenerator.ReadTable(record);
//        }


        GeneratorTool.getImports(record);

        if (record.getGenTable() && !record.getReadTable()) {
            TableGenerator.GenTable(record);
        }

        if (record.getGenClass()) {
            ModelGenerator.GenModel(record);
            ControllerGenerator.GenController(record);
            ServiceGenerator.GenService(record);
            ServiceImplGenerator.GemServicelImpl(record);
            MapperGenerator.GenMapper(record);
            MapperXmlGenerator.GenXml(record);
        }
        if (record.getGenList()) {
            ListViewGenerator.GenListView(record);
        }
        if (record.getGenForm()) {
            EditViewGenerator.GenEditView(record);
        }
        if (record.getGenRouter()) {
            RouterGenerator.GenRouter(record);
        }
    }

    /**
     * <p>删除。</p>
     */
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    @ResponseBody
    public Result deleteGenCode(@RequestParam(required = true, value = "id") String id) {

        boolean num = genCodeService.deleteGenCode(id);
        if (num) {
            return new Result(true, "删除成功");
        }
        return new Result(false, "删除异常");
    }

    /**
     * 获取生成代码文件路径
     *
     * @return
     */
    @RequestMapping(value = "/getSrcPath", method = RequestMethod.GET)
    @ResponseBody
    public Result getSrcPath() {
        Map<String, Object> map = new HashMap<>();

        String path = this.getClass().getPackage().getName();
        path = path.substring(0, path.lastIndexOf(".")).replace(".", File.separator);
        String[] arr = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/").split("target");
        //String root = StringUtils.join(Arrays.copyOfRange(arr, 0, arr.length - 2), File.separator);
        String root = arr[0];
        if ("linux".equalsIgnoreCase(System.getProperties().getProperty("os.name"))) {
            map.put("root", "/var/lib/jenkins/workspace/信牧基础平台");
        } else {
            map.put("root", root);
        }

        map.put("javaPath", "/src/main/java/" + path);
        map.put("viewPath", "/src/main/vue/src/pages");
        map.put("routerPath", "/src/main/vue/src/router");
        return new Result(true, map);
    }

    /**
     * 根据数据源获取所有表
     *
     * @param dataSourceInfo
     * @return
     */
    @RequestMapping(value = "/tables", method = RequestMethod.GET)
    @ResponseBody
    public Result tables(DataSourceInfo dataSourceInfo) {

        if (StringUtils.isNotEmpty(dataSourceInfo.getCode()) && !"dataSource".equals(dataSourceInfo.getCode())) {
            dataSourceInfo = dataSourceInfoService.getDataSourceInfo(dataSourceInfo);
            if (dataSourceInfo != null) {

                List<String> pp = DatabaseUtil.loadDatabaseTables(dataSourceInfo);
                return new Result(true, pp);
            }
        } else {
            List<String> pp = DatabaseUtil.loadDatabaseTables(dataSourceInfo);
            return new Result(true, pp);
        }


        return new Result(false, "获取失败");
    }

    /**
     * 根据表获取字段
     *
     * @param dataSourceInfo
     * @return
     */
    @RequestMapping(value = "/tableFields", method = RequestMethod.GET)
    @ResponseBody
    public Result tableFields(DataSourceInfo dataSourceInfo) {

        String tableName = dataSourceInfo.getTableName();

        if (StringUtils.isNotEmpty(dataSourceInfo.getCode())) {

            if (!"dataSource".equals(dataSourceInfo.getCode())) {

                dataSourceInfo = dataSourceInfoService.getDataSourceInfo(dataSourceInfo);
            }
            if (dataSourceInfo != null) {
                dataSourceInfo.setTableName(tableName);
                List<TableField> pp = DatabaseUtil.loadTableFields(dataSourceInfo);
                return new Result(true, pp);
            }
        } else {
            List<TableField> pp = DatabaseUtil.loadTableFields(dataSourceInfo);
            return new Result(true, pp);
        }


        return new Result(false, "获取失败");
    }


    @RequestMapping(value = "/check", method = RequestMethod.GET)
    @ResponseBody
    public Result check(GenCode record) {

        GenCode genCode = new GenCode();
        if (StringUtils.isNotEmpty(record.getClassName())) {
            //手动填写
            genCode.setClassName(CaseUtils.toCamelCase(record.getClassName(), true, '_'));
        } else {
            //根据表名生成类名
            genCode.setClassName(CaseUtils.toCamelCase(record.getTableName(), true, '_'));
        }
        GenCode data = genCodeService.getGenCode(genCode);
        if (data != null) {
            if (record.getId() != null) {
                if (!record.getId().equals(data.getId())) {
                    return new Result(false, "类名冲突");
                }
            } else {
                return new Result(false, "类名冲突");
            }
        }

        if (record.getGenTable()) {
            GenCode genCode2 = new GenCode();
            genCode2.setTableName(record.getTableName());
            genCode2 = genCodeService.getGenCode(genCode2);

            if (genCode2 != null) {
                return new Result(true, "-1");
            }

        }


        return new Result(true, "1");
    }

}

