<template>
  <div class="content-view" v-if="meta">
    <div class="table-head-tool">
      <div class="table-head-row">
        <div class="table-head-actions">
          <Button type="primary" @click="showAdd">新增</Button>
          <Button type="default" @click="query(1)" class="ml10">刷新</Button>
          <Button type="default" @click="exportCsv" class="ml10">导出</Button>
        </div>
      </div>
      <Form ref="searchForm" :model="gridOption.param.seachOption" inline :label-width="80" class="search-form">
        <FormItem :label-width="20" class="search-input-group">
          <Select v-model="gridOption.param.seachOption.key" style="width: 180px" :placeholder="seachTypePlaceholder">
            <Option v-for="item in meta.seachTypes" :value="item.key" :key="item.key">{{ item.value }}</Option>
          </Select>
          <Input class="ml10" v-model="gridOption.param.seachOption.value" style="width: 280px" search
            placeholder="请输入关键字" @on-search="query(1)" />
        </FormItem>
        <FormItem class="search-action-group">
          <Button type="primary" @click="query(1)">查询</Button>
          <Button type="default" @click="resetQuery" class="ml10">重置</Button>
        </FormItem>
      </Form>
    </div>
    <div class="table-body">
      <tables :columns="listColumns" :value="gridOption.data" :pageOption="gridOption.param.pageOption"
        @changePage="query"></tables>
    </div>
    <editModal ref="editModal" :columns="editColumns" :rules="gridOption.rules" width="640" />
  </div>
</template>

<script>
import tplDemoServer from "@/api/demo/tplDemoServer.js";

export default {
  name: "TplDemoPage",

  data() {
    return {
      select_sources: {},
      gridOption: {
        param: { seachOption: { key: "", value: "" }, pageOption: { page: 1, pageSize: 20, total: 0 } },
        data: [],
        rules: {},
      },
    };
  },
  computed: {
    modelName() {
      return "tpl_demo";
    },
    meta() {
      return {
        title: "演示数据",
        seachTypes: [
          { key: "title", value: "标题" },
          { key: "remark", value: "备注" },
        ],
        fields: [
          { key: "id", title: "ID", type: "number", list: true, form: false, minWidth: 80 },
          { key: "title", title: "标题", type: "input", list: true, form: true, required: true, minWidth: 200 },
          { key: "remark", title: "备注", type: "input", list: true, form: true, required: false, minWidth: 220 },
        ],
      };
    },
    seachTypePlaceholder() {
      const st = this.meta && this.meta.seachTypes;
      if (!st || !st.length) {
        return "请选择";
      }
      const k = this.gridOption.param.seachOption.key;
      const f = st.find((x) => x.key === k);
      return f ? f.value : "请选择搜索字段";
    },
    editColumns() {
      if (!this.meta || !Array.isArray(this.meta.fields)) {
        return [];
      }
      return this.generateEditColumns(this.meta.fields.filter((f) => f.form !== false), this.select_sources);
    },
    listColumns() {
      if (!this.meta || !Array.isArray(this.meta.fields)) {
        return [];
      }
      const listFields = this.meta.fields.filter((f) => f.list !== false);
      const cols = this.generateListColumns(listFields, this.meta.fields, this.select_sources);
      cols.push({
        title: "操作",
        key: "action",
        width: 180,
        type: "template",
        render: (h, params) => {
          return this.renderRowActionBtns(h, [
            { title: "编辑", type: "info", click: () => this.showEdit(params.row) },
            { title: "删除", type: "error", click: () => this.delConfirm(params.row) },
          ]);
        },
      });
      return cols;
    },
  },
  async mounted() {
    await this.load_select_sources();
    this.resetSearchFromMeta();
    this.syncEditRules();
    this.query(1);
  },
  methods: {
    id_field_to_model() {
      return "";
    },
    async load_select_sources() {
      this.select_sources = await this.loadSelectSources(
        this.meta.fields,
        this.id_field_to_model.bind(this),
        this.getRowLabel.bind(this)
      );
    },
    syncEditRules() {
      this.gridOption.rules = this.generateEditRules(this.meta.fields.filter((f) => f.form !== false));
    },
    resetSearchFromMeta() {
      if (!this.meta) {
        return;
      }
      const firstKey = (this.meta.seachTypes[0] && this.meta.seachTypes[0].key) || "title";
      this.gridOption.param.seachOption = { key: firstKey, value: "" };
      this.gridOption.param.pageOption = { page: 1, pageSize: 20, total: 0 };
    },
    buildEmptyForm() {
      return this.generateEmptyForm(this.meta.fields.filter((f) => f.form !== false));
    },
    normalizePayload(raw) {
      return this.generatePayload(raw, this.meta.fields.filter((f) => f.form !== false));
    },
    async query(page) {
      if (!this.modelName || !this.meta) {
        return;
      }
      if (page) {
        this.gridOption.param.pageOption.page = page;
      }
      try {
        const res = await tplDemoServer.page(this.gridOption.param);
        if (res && res.code === 0) {
          this.gridOption.data = res.data.rows || [];
          this.gridOption.param.pageOption.total = res.data.count || 0;
        } else {
          this.$Message.error((res && (res.message || res.Msg)) || "查询失败");
        }
      } catch (e) {
        this.$Message.error("查询失败: " + (e && e.message ? e.message : String(e)));
      }
    },
    resetQuery() {
      this.resetSearchFromMeta();
      this.query(1);
    },
    showAdd() {
      this.$refs.editModal.addShow(this.buildEmptyForm(), async (data) => {
        await this.persist(data, false);
      });
    },
    showEdit(row) {
      this.$refs.editModal.editShow(this.normalizeRowForEditModal({ ...row }), async (data) => {
        await this.persist(data, true);
      });
    },
    async persist(data, isEdit) {
      const payload = this.normalizePayload(data);
      const req = isEdit ? tplDemoServer.edit(payload) : tplDemoServer.add(payload);
      const res = await req;
      if (res && res.code === 0) {
        this.$Message.success(isEdit ? "保存成功" : "新增成功");
        this.query(1);
      } else {
        this.$Message.error((res && (res.message || res.Msg)) || "保存失败");
        throw new Error("save failed");
      }
    },
    delConfirm(row) {
      this.$Modal.confirm({
        title: "确认删除",
        content: "确定删除该条记录？",
        onOk: async () => {
          const res = await tplDemoServer.del({ id: row.id });
          if (res && res.code === 0) {
            this.$Message.success("已删除");
            this.query(1);
          } else {
            this.$Message.error((res && (res.message || res.Msg)) || "删除失败");
          }
        },
      });
    },
    exportCsv() {
      if (!this.modelName || !this.meta) {
        return;
      }
      try {
        tplDemoServer.exportCsv({ param: this.gridOption.param });
      } catch (e) {
        this.$Message.error("导出失败: " + (e && e.message ? e.message : String(e)));
      }
    },
  },
};
</script>
