<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="模板名称" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入模板名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模板类型" prop="templateType">
        <el-input
          v-model="queryParams.templateType"
          placeholder="请输入模板类型"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          plain
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          plain
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="200" show-overflow-tooltip />
      <el-table-column label="模板名称" align="center" prop="templateName" />
      <el-table-column label="模板类型" align="center" prop="templateType" width="120" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="210">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-copy"
            @click="handleCopy(scope.row)"
          >复制</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 添加或修改模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板类型" prop="templateType">
          <el-select v-model="form.templateType" placeholder="请选择模板类型" style="width: 100%" @change="handleTemplateTypeChange" :disabled="form.id != undefined">
            <el-option label="免费表单类" value="免费表单类" />
            <el-option label="小程序表单类" value="小程序表单类" />
            <el-option label="一站式小程序表单类" value="一站式小程序表单类" />
            <el-option label="免费加粉类" value="免费加粉类" />
            <el-option label="小程序加粉类" value="小程序加粉类" />
          </el-select>
        </el-form-item>
        <el-form-item label="编辑页面">
          <el-button type="primary" @click="openH5(form.templateData)" :disabled="!form.templateType">
            编辑页面
          </el-button>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- H5编辑对话框 -->
    <el-dialog title="编辑页面" :visible.sync="h5Open" append-to-body fullscreen class="h5-editor-dialog">
      <div class="h5-editor-wrapper">
        <H5Editor ref="h5Editor" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="h5Ok">确 定</el-button>
        <el-button @click="h5Cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageTemplate, getTemplate, addTemplate, updateTemplate, batchDelTemplate, updateTemplateStatus, copyTemplate } from "@/api/adv/landingPageTemplate";
import H5Editor from "@/components/H5Editor/index.vue";

export default {
  name: "LandingPageTemplate",
  components: {
    H5Editor
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模板表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // H5编辑器对话框
      h5Open: false,
      queryParams: {
        page: 1,
        size: 10,
        templateName: undefined,
        templateType: undefined,
        domainId: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        templateName: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询模板列表 */
    getList() {
      this.loading = true;
      pageTemplate(this.queryParams).then(response => {
        this.templateList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 模板状态修改
    handleStatusChange(row) {
      let text = row.status === 1 ? "启用" : "禁用";
      this.$confirm('确认要"' + text + '""' + row.templateName + '"模板吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return updateTemplateStatus(row.id, row.status);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(() => {
        row.status = row.status === 0 ? 1 : 0;
      });
    },
    // 处理模板类型改变
    handleTemplateTypeChange(val) {
      let id = null;
      switch (val) {
        case '免费表单类':
          id = 1;
          break;
        case '小程序表单类':
          id = 2;
          break;
        case '一站式小程序表单类':
          id = 3;
          break;
        case '免费加粉类':
          id = 4;
          break;
        case '小程序加粉类':
          id = 5;
          break;
      }
      
      if (id) {
        getTemplate(id).then(response => {
          if (response.data && response.data.templateData) {
            this.form.templateData = response.data.templateData;
            // 如果是在新增模式下且没有填写标题，可以考虑是否要同步其他信息，暂时只同步内容
          }
        });
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        templateName: undefined,
        templateData: undefined,
        templateType: undefined,
        domainId: undefined,
        status: 0,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 清空H5编辑器的缓存数据
      if (this.$refs.h5Editor) {
        this.$refs.h5Editor.initData('{"pageTitle":"","configList":[]}')
      }
      this.open = true;
      this.title = "添加模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getTemplate(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改模板";
      });
    },
    /** 复制按钮操作 */
    /** 复制按钮操作 */
    handleCopy(row) {
      this.reset();
      const id = row.id;
      getTemplate(id).then(response => {
        this.form = response.data;
        this.form.id = undefined;
        this.form.templateName = this.form.templateName + "_副本";
        this.open = true;
        this.title = "复制并添加模板";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 验证JSON格式
          if (this.form.templateData) {
            try {
              JSON.parse(this.form.templateData);
            } catch (e) {
              this.msgError("模板数据格式不正确，必须是有效的JSON");
              return;
            }
          }
          
          if (this.form.id != undefined) {
            updateTemplate(this.form.id, this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addTemplate(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id ? [row.id] : this.ids;
      this.$confirm('是否确认删除选中的模板?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return batchDelTemplate(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function() {});
    },
    /** 打开H5编辑器 */
    openH5(templateData) {
      this.h5Open = true
      this.$nextTick(() => {
        // 支持新旧数据格式
        this.$refs.h5Editor.initData(templateData || '{"pageTitle":"","configList":[]}', this.form.templateType)
      })
    },
    /** H5编辑器确定 */
    h5Ok() {
      // 通过ref获取子组件的完整数据（新格式JSON）
      const pageData = this.$refs.h5Editor.getPageData()
      this.form.templateData = JSON.stringify(pageData)
      this.h5Open = false // 关闭对话框
    },
    /** H5编辑器取消 */
    h5Cancel() {
      this.h5Open = false;
    }
  }
};
</script>

<style scoped>
.h5-editor-dialog /deep/ .el-dialog {
  display: flex;
  flex-direction: column;
}

.h5-editor-dialog /deep/ .el-dialog__body {
  flex: 1;
  overflow: hidden;
  padding: 0;
}

.h5-editor-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.h5-editor-wrapper /deep/ .h5-editor-container {
  width: 100%;
  height: 100%;
}
</style>

