<template>
  <div class="page-main"
       v-loading="pageLoad">
    <div class="left-nav">
      <el-menu @select="selectMenu"
               :default-active="defaultActive">
        <label v-for="item in menuData"
               :key="item.serviceCode">
          <el-submenu v-if="item.tenantServiceItems.length>0"
                      :index="item.serviceCode">
            <template slot="title">{{ item.serviceName }}</template>
            <el-menu-item v-for="item2 in item.tenantServiceItems"
                          :key="item2.serviceItemCode"
                          :index="item2.serviceItemCode">
              <template slot="title">{{ item2.serviceItemName }}</template>
            </el-menu-item>
          </el-submenu>
          <el-menu-item v-else
                        :index="item.serviceCode"
                        :title="item.serviceName">
            <template slot="title">{{ item.serviceName }}</template>
          </el-menu-item>
        </label>
      </el-menu>
    </div>
    <div class="context"
         v-loading="mainLoading"
         v-if="menuData.length>0">
      <div class="top-text">
        <div>
          <p> 可自由配置的表单字段控制</p>
          <span>(请从下方字段中勾选企业所需要记录的字段信息)</span>
        </div>
        <div>
          <template v-if="tabsData.length>0">
            <el-button size="mini"
                       type="primary"
                       @click="handleSave">保存</el-button>
            <!-- <el-button size="mini" @click="handlePreview">预览</el-button>  -->
          </template>
        </div>
      </div>
      <div class="main"
           v-if="isShow">
        <el-tabs v-model="activeName"
                 type="card"
                 @tab-click="handleClick">
          <el-tab-pane v-for="item in tabsData "
                       :key="item.tableCode"
                       :ref="item.tableCode"
                       :label="item.tableName"
                       :name="item.tableCode">
            <!-- <el-input size="small" placeholder="请输入折叠面板的标题" v-model="item.tableName" @focus="temTitle=item.tableName" @blur="item.tableName=item.tableName?item.tableName:temTitle">
              <template slot="prepend">表单标题</template>
            </el-input> -->
            <el-tag>{{ item.parentCode+'-'+item.tableCode }}</el-tag>
            <ws-form-tpl v-if="item.tableType === 'form'"
                         :ref="item.tableCode+'-form'"
                         :init-form-item="item.files"></ws-form-tpl>
            <span v-else>table模板还在开发中。。。</span>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <el-dialog append-to-body
               title="表单一览"
               :visible.sync="dialogRanVisible"
               :close-on-click-modal="false">
      <el-switch v-model="isReadonly"
                 active-text="编辑状态"
                 inactive-text="反显状态">
      </el-switch>
      <ws-form style="margin-top:10px;"
               v-if="dialogRanVisible"
               ref="form"
               label-width="100px"
               :model="previewForm">
        <ws-info-table>
          <ws-form-tpl-item v-for="(item,index) in formJsonArray"
                            :key="index"
                            :model="item"
                            :data="previewForm"
                            :readonly="isReadonly">
            <template slot="select">
              <el-option label="区域一"
                         value="shanghai"></el-option>
              <el-option label="区域二"
                         value="beijing"></el-option>
            </template>
            <template slot="checkbox">
              <el-checkbox label="线下主题活动"
                           name="type"></el-checkbox>
              <el-checkbox label="单纯品牌曝光"
                           name="type"></el-checkbox>
            </template>
            <template slot="radio">
              <el-radio label="线上品牌商赞助"></el-radio>
              <el-radio label="线下场地免费"></el-radio>
            </template>
          </ws-form-tpl-item>
        </ws-info-table>
      </ws-form>
    </el-dialog>
  </div>
</template>

<script>
import TplFormApi from "@/api/templateForm";

// 默认DOM结构
const defaultDOM = {
  /**
   * 可选类型
   * input
   * time
   * select
   * radio
   * checkbox
   */
  domType: "input",
  // input标题
  label: "标题",
  // DOM的v-model
  key: "key",
  // 是否为空
  notNull: false,
  // 是否禁用
  disabled: false,
  // 是否显示
  showable: true,
  // 别名,如果传入会覆盖label属性
  alias: null,
  // 检验规则
  rule: 255,
  // 栅格列数
  span: 4,
  // 显隐控制函数,类型字符串 ['true'|'false'|函数名]
  showFunName: "true",
  // 是否反显组件
  readonly: false,
  // ------  备用字段 --------
  // ID
  id: "snap",
  // 绑定字段
  bindingField: "snap",
  // 是否是默认必选项
  defaultRequired: false,
  // 是否参与输出
  exportable: true,
  // 表单ID
  formId: "snap"
};

export default {
  data () {
    return {
      // 表单标题备份
      temTitle: "",
      tenantId: "1",
      pageLoad: false,
      // 默认选中的tabs
      activeName: "",
      // 默认激活的菜单
      defaultActive: "",
      tabsData: [],
      menuData: [],
      // 预览对象
      formJsonArray: [],
      // 表单一览
      dialogRanVisible: false,
      // 编辑状态
      isReadonly: false,
      // 渲染form
      previewForm: {},
      // 页面遮罩
      mainLoading: false,
      // 显示tabs编辑区
      isShow: false
    };
  },
  mounted () {
    this.doInit();
  },
  methods: {
    // 初始化数据
    async doInit () {
      try {
        this.pageLoad = true;
        const resp = await TplFormApi.tenantServiceForm({
          tenantId: this.tenantId
        });
        this.menuData = resp.data;
        if (this.menuData.length > 0) {
          const _serviceCode =
            this.menuData[0].tenantServiceItems.length > 0
              ? this.menuData[0].tenantServiceItems[0].serviceItemCode
              : this.menuData[0].serviceCode;
          this.defaultActive = _serviceCode;
          this.selectMenu(_serviceCode);
        }
      } catch (error) {
        if (error.code && error.code !== "200") {
          this.$message(error.message);
        }
      } finally {
        this.pageLoad = false;
      }
    },
    // 选择菜单
    async selectMenu (index) {
      try {
        this.mainLoading = true;
        this.isShow = false;
        const resp = await TplFormApi.findCode({ code: index });
        const _tabsData = resp.data;
        for (const item of _tabsData) {
          if (item.tableType === "form") {
            await this.initFormTpl(item);
          } else if (item.tableType === "table") {
            await this.initTableTpl(item);
          }
        }
        this.tabsData = _tabsData;
        if (this.tabsData.length > 0) {
          this.activeName = this.tabsData[0].tableCode;
        }
        this.defaultActive = index;
        this.isShow = true;
      } catch (error) {
        if (error.code && error.code !== "200") {
          this.$message(error.message);
        }
        // console.log(error);
      } finally {
        this.mainLoading = false;
      }
    },
    // 初始化form模板
    async initFormTpl (item) {
      let doms = [];
      const resp = await TplFormApi.getTplForm({
        tenantId: this.tenantId,
        businessCode: item.parentCode + "-" + item.tableCode
      });
      if (resp.data) {
        doms = resp.data.fields;
        item.formId = resp.data.id;
      } else {
        const _resp = await TplFormApi.findTableCode({
          tableCode: item.tableCode
        });
        // 解析dom格式
        _resp.data.forEach(value => {
          doms.push(
            Object.assign({}, defaultDOM, {
              label: value.fieldName,
              notNull: value.mustFillFlag === "1",
              key: value.dbFiled
            })
          );
        });
      }
      item.files = doms;
    },
    // 初始化table模板
    async initTableTpl (item) { },
    // 预览
    handlePreview () {
      this.formJsonArray = this.$refs[
        this.activeName + "-form"
      ][0].getFormItem();
      this.dialogRanVisible = true;
    },
    // tabs 点击
    handleClick () { },
    // 保存
    async handleSave () {
      try {
        // 备份当前选择的tabs
        const _activeName = this.activeName;
        this.mainLoading = true;
        // 获取当前的form结构
        const formItems = this.$refs[
          this.activeName + "-form"
        ][0].getFormItem();
        // 判断是否是修改
        let _formId = null;
        this.tabsData.forEach(v => {
          if (v.tableCode === this.activeName) _formId = v.formId;
        });
        // 组织请求结构
        const data = {
          id: _formId,
          tenantId: this.tenantId,
          businessCode: this.defaultActive + "-" + this.activeName,
          fields: formItems
        };
        await TplFormApi.saveTplForm(data);
        await this.selectMenu(this.defaultActive);
        this.activeName = _activeName;
        this.$message.success("保存成功! ");
      } catch (error) {
        if (error.code && error.code !== "200") {
          this.$message.error(error.message);
        }
      } finally {
        this.mainLoading = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.page-main {
  display: flex;
  width: 100%;
  height: 100%;
  flex-direction: row;
  flex-wrap: nowrap;
  & .left-nav {
    width: 20%;
    display: flex;
    flex-shrink: 0;
    & .el-menu {
      width: 100%;
    }
  }
  & .context {
    width: 80%;
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    & .top-text {
      height: 50px;
      background-color: #f6f6f6;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0px 10px;
      & p {
        margin: 0px;
        display: inline-block;
        padding: 0px;
      }
      & span {
        font-size: 14px;
        color: #666666;
        margin-left: 5px;
      }
    }
    & .main {
      display: flex;
      flex-grow: 1;
      padding: 20px 0 0 20px;
      flex-shrink: 0;
      & .el-tabs {
        width: 100%;
      }
    }
  }
}
</style>
