<template>
  <div class="form-container" v-loading="!done">
    <fc-designer v-if="done" ref="designer" :tableList="tableList" :menu="menu" @updateTableCol="updateTableCol">
      <template slot="handle">
        <el-button icon="el-icon-download" type="primary" size="small" round @click="handleDownloadRule()">保存表单JSON</el-button>
        <el-button icon="el-icon-upload2" type="success" size="small" round @click="handleUploadRule()">导入表单JSON</el-button>
        <el-button icon="el-icon-download" type="primary" size="small" round @click="handleDownloadOption()">生成表单配置</el-button>
        <el-button icon="el-icon-upload2" type="success" size="small" round @click="handleUploadOption()">导入表单配置</el-button>
      </template>
    </fc-designer>

    <!--代码预览-->
    <el-dialog :title="dialogTitle" :visible.sync="dialogState" :close-on-click-modal="false" append-to-body>
      <codemirror v-model="codemirrorContent" :options="codemirrorOptions" style="height: 90%;text-align: left;border: 1px solid #ccc;" />
      <el-row v-if="dialogMenu">
        <el-button @click="dialogState = false">取 消</el-button>
        <el-button type="primary" @click="handleImport">导 入</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable */
import { setToken } from "../utils/auth";
import { getFormInfo, setFormRenderJson, getTableList, getTableCol, getDictTypeList, getDepList } from  '../api/index.js'
import jsonlint from 'jsonlint-mod'
import 'codemirror/addon/lint/lint'
import 'codemirror/addon/lint/json-lint'
import 'codemirror/lib/codemirror.css'
import 'codemirror/addon/lint/lint.css'
import 'codemirror/addon/edit/matchbrackets.js'
import 'codemirror/mode/javascript/javascript.js'
import departmentSelector from './departmentSelector'
export default {
  data() {
    return {
      id: '',
      token: '',
      tableId: '', // 表id
      tableList: [],
      dialogTitle: '', // 对话框标题
      dialogState: false, // 对话框状态
      dialogMenu: false, // 对话框菜单状态
      // codemirror配置
      codemirrorOptions: {
        mode: 'application/json',
        theme: 'default',
        gutters: ['CodeMirror-lint-markers'],
        tabSize: 2,
        lint: true,
        line: true,
        lineNumbers: true,
        matchBrackets: true,
        lineWrapping: true,
        styleActiveLine: true,
        readOnly: false
      },
      // codemirror内容
      codemirrorContent: null,
      done: false,
      menu: [
        {
          title: "表单组件",
          name: "main",
          list: [
            {
              icon: "icon-input",
              name: "input",
              label: "输入框"
            },
            {
              icon: "icon-number",
              name: "inputNumber",
              label: "计数器"
            },
            {
              icon: "icon-radio",
              name: "radio",
              label: "单选框"
            },
            {
              icon: "icon-checkbox",
              name: "checkbox",
              label: "多选框"
            },
            {
              icon: "icon-select",
              name: "select",
              label: "选择器"
            },
            {
              icon: "icon-switch",
              name: "switch",
              label: "开关"
            },
            {
              icon: "icon-time",
              name: "timePicker",
              label: "时间选择器"
            },
            {
              icon: "icon-date",
              name: "datePicker",
              label: "日期选择器"
            },
            {
              icon: "icon-slider",
              name: "slider",
              label: "滑块"
            },
            {
              icon: "icon-rate",
              name: "rate",
              label: "评分"
            },
            {
              icon: "icon-color",
              name: "colorPicker",
              label: "颜色选择器"
            },
            // {
            //   icon: "icon-cascader",
            //   name: "cascader",
            //   label: "级联选择器"
            // },
            {
              icon: "icon-upload",
              name: "upload",
              label: "上传"
            },
            // {
            //   icon: "icon-tree",
            //   name: "tree",
            //   label: "树形控件"
            // },
            {
              icon: "icon-editor",
              name: "fc-editor",
              label: "富文本框"
            }
          ]
        },
        {
          title: "辅助组件",
          name: "aide",
          list: [
            {
              icon: "icon-alert",
              name: "el-alert",
              label: "提示"
            },
             {
              icon: "icon-button",
              name: "el-button",
              label: "按钮"
            },
             {
              icon: "icon-span",
              name: "span",
              label: "文字"
            },
             {
              icon: "icon-divider",
              name: "el-divider",
              label: "分割线"
            },
          ]
        },
         {
          title: "布局组件",
          name: "layout",
          list: [
            {
              icon: "icon-space",
              name: "div",
              label: "间距"
            },
            {
              icon: "icon-row",
              name: "col",
              label: "栅格"
            },
          ]
        }
      ]
    }
  },
  beforeCreate() {
    // 开启JSON校验
    window.jsonlint = jsonlint
  },
  created(){
    this.id = this.getQueryString('id')
    this.token = this.getQueryString('token')
    setToken(this.token)
    this.getTableList();
  },
  methods: {
    getTableList(){
      getTableList().then(resp=>{
        if (resp && resp.status===200) {
          let temp = [];
          if(resp.data?.length){
            resp.data.forEach(item => {
              temp.push({
                value: item.id,
                label: item.tableName
              })
            })
            this.tableList = temp
            getDictTypeList().then(resp=>{
              if (resp && resp.status===200) {
                let temp = [{
                  value: '',
                  label: '请选择'
                }];
                if(resp.data?.length){
                  resp.data.forEach(item => {
                    temp.push({
                      value: item.id,
                      label: item.name
                    })
                  })
                  localStorage.setItem('dictTypeList', JSON.stringify(temp))
                  this.done = true
                  this.getFormInfo()
                  this.$nextTick(() => {
                    // this.addCustomPanel()
                    // 第一次进来自动根据表ID查询字段
                    this.updateTableCol(this.tableList[0].value)

                    // 组装部门信息
                    let depList = []
                    getDepList({
                      parentId: 'D000000001'
                    }).then(resp => {
                      if (resp && resp.status===200) {
                        depList = resp.data.map(item => {
                          return {
                            value: item.code,
                            label: item.name
                          }
                        })
                        let xunfei = []
                        getDepList({
                          parentId: 'D000000002'
                        }).then(resp2 => {
                          if (resp2 && resp2.status===200) {
                            xunfei = resp2.data.map(item => {
                              return {
                                value: item.code,
                                label: item.name
                              }
                            })
                            depList.forEach(item => {
                              if(item.value === 'D000000002'){
                                item.children = xunfei
                              }
                            })
                            //插入组件规则
                            const departmentSelectorOption = departmentSelector(depList)
                            console.log(departmentSelectorOption)
                            this.$refs.designer.addComponent(departmentSelectorOption);
                            //插入拖拽按钮到`main`分类下
                            this.$refs.designer.appendMenuItem('main', {
                              icon: departmentSelectorOption.icon,
                              name: departmentSelectorOption.name,
                              label: departmentSelectorOption.label
                            })
                          }
                        })
                      }
                    })
                  })
                }
              }
            })
          }
        }
      })
    },
    updateTableCol(tableId){
      getTableCol({
        tableId: tableId
      }).then(resp=>{
        if (resp && resp.status===200) {
          let temp = [];
          if(resp.data?.length){
            resp.data.forEach(item => {
              temp.push({
                value: item.colCode,
                label: item.colName
              })
            })
            this.$refs['designer'].setBaseFormRule(temp);
          }
        }
      })
    },
    // 回显表单
    getFormInfo() {
      getFormInfo({
        id: this.id
      }).then(resp=>{
        if (resp && resp.status===200) {
          if(resp.data.formRenderJson){
            let rule = JSON.parse(resp.data.formRenderJson).rule
            let config = JSON.parse(resp.data.formRenderJson).config
            this.$refs.designer.setRule(rule)
            this.$refs.designer.setOption(config);
          }
        }
      })
    },
    getQueryString(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var r = window.location.search.substr(1).match(reg);
      if(r != null) {
        return decodeURIComponent(r[2]);
      }
      return '';
    },
    // 自定义折叠面板
    addCustomPanel() {
      // 自定义折叠面板 
      const label = '折叠面板';
      const name = 'el-collapse';
      const checkbox = {
        icon: 'icon-checkbox',
        label,
        name,
        drag: true,
        dragBtn: false,
        inside: true,
        rule() {
          return {
            type: name,
            props: {span: 12},
            children: []
          };
        },
        props() {
          return [
            {type: 'input', field: 'mbmc', title: '面板名称', value: ''},
          ];
        }
      };
      
      // 添加自定义
      this.$refs.designer.addComponent(checkbox)
      // 插入拖拽按钮到`main`分类下
      this.$refs.designer.appendMenuItem('layout', {
        icon: checkbox.icon,
        name: checkbox.name,
        label: checkbox.label
      })
    },
    // 保存表单
    handleDownloadRule() {
      this.dialogTitle = '表单规则'
      // this.dialogState = true
      // this.dialogMenu = false
      // this.codemirrorOptions.readOnly = true
      // 表单项
      this.codemirrorContent = this.$refs.designer.getRule()
      // 表单配置
      const formConfig = this.$refs.designer.getOption()
      let formData = {};
      formData.rule = this.codemirrorContent
      formData.config = formConfig
      this.tableId = formConfig.form.formInDatabase
      setFormRenderJson({
        tableId: this.tableId,
        id: this.id,
        formRenderJson: JSON.stringify(formData),
      }).then(resp=>{
        if (resp && resp.status===200) {
          this.$message({
            type: 'success',
            message: '保存成功'
          })
        }
      })
    },
    // 导出表单配置
    handleDownloadOption() {
      this.dialogTitle = '表单配置'
      this.dialogState = true
      this.dialogMenu = false
      this.codemirrorOptions.readOnly = true
      this.codemirrorContent = JSON.stringify(this.$refs.designer.getOption(), null, 2)
      console.log(this.codemirrorContent);
    },
    // 导入表单JSON
    handleUploadRule() {
      this.dialogTitle = '导入表单规则'
      this.dialogState = true
      this.dialogMenu = true
      this.codemirrorOptions.readOnly = false
      this.codemirrorContent = JSON.stringify([], null, 2)
    },
    // 导入表单配置
    handleUploadOption() {
      this.dialogTitle = '导入表单配置'
      this.dialogState = true
      this.dialogMenu = true
      this.codemirrorOptions.readOnly = false
      this.codemirrorContent = JSON.stringify({}, null, 2)
    },
    // 配置导入
    handleImport() {
      try {
        const content = JSON.parse(this.codemirrorContent)
        if (this.dialogTitle === '导入表单规则') {
          this.$refs.designer.setRule(content)
        }
        if (this.dialogTitle === '导入表单配置') {
          this.$refs.designer.setOptions(content)
        }
        this.dialogState = false
      } catch (e) {
        alert('输入内容格式有误')
      }
    }
  }
}
</script>

<style scoped>
.form-container >>> ._fc-designer{
  height: 100vh !important;
}
.form-container >>> aside{
  background: none;
}
.row{
  display: flex;
  justify-content: center;
  padding: 5px 0;
}
</style>
