<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :search.sync="query"
               :permission="permissionList"
               v-model="form"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="onLoad(page, query)"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="mini"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.wf_design_form_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot="menu"
                slot-scope="{row}">
        <el-button v-if="permission.wf_design_form_design"
                   type="text"
                   size="mini"
                   icon="el-icon-edit"
                   @click="handleDesign(row)">设计</el-button>
        <el-button v-if="permission.wf_design_form_copy"
                   type="text"
                   size="mini"
                   icon="el-icon-document-copy"
                   @click="handleCopy(row)">拷贝</el-button>
        <!-- <el-button v-if="permission.wf_design_form_history && row.version > 1"
                   type="text"
                   size="mini"
                   icon="el-icon-time"
                   @click="handleHistory(row)">历史</el-button> -->
      </template>
    </avue-crud>

    <el-dialog :visible.sync="formVisible"
               append-to-body
               title="表单设计"
               fullscreen>
      <avue-form-design style="height: 88vh"
                        ref="formDesign"
                        :toolbar="['clear', 'preview', 'import']"
                        :includeFields="['group', 'dynamic', 'input', 'textarea', 'number', 'map', 'radio','checkbox','select','tree','cascader', 'upload', 'date','time','datetime','daterange','datetimerange','timerange','ueditor','switch','rate','color','icon','slider']"
                        :customFields="customFields"
                        :options="options">
        <template #toolbar>
          <el-button type="text"
                     size="medium"
                     icon="el-icon-download"
                     @click="handleSubmit">保存</el-button>
        </template>
      </avue-form-design>
    </el-dialog>

    <el-dialog :visible.sync="copyVisible"
               append-to-body
               title="拷贝表单">
      <avue-form :option="copyOption"
                 v-model="form"
                 ref="copyForm"
                 @submit="handleCopySubmit">
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, add, update, remove } from "@/api/plugin/workflow/form";
import { mapGetters } from "vuex";

export default {
  data() {
    return {
      formVisible: false,
      options: {},
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        size: 'mini',
        height: 'auto',
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        selection: true,
        delBtn: false,
        dialogType: 'drawer',
        align: 'center',
        searchMenuSpan: 6,
        column: [
          {
            label: "表单key",
            prop: "key",
            rules: [{
              required: true,
              message: "请输入表单key",
              trigger: "blur"
            }],
            search: true
          },
          {
            label: "表单名称",
            prop: "name",
            rules: [{
              required: true,
              message: "请输入表单名称",
              trigger: "blur"
            }],
            search: true
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            span: 24
          },
          {
            label: '版本',
            prop: 'version',
            display: false
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            dicData: [{
              label: '可用',
              value: 1
            }, {
              label: '禁用',
              value: 2
            }],
            rules: [{
              required: true,
              message: "请选择状态",
              trigger: "change"
            }],
            search: true
          },
        ]
      },
      data: [],
      customFields: [{
        label: '批复意见',
        prop: 'comment',
        type: 'textarea',
        span: 24,
        display: true
      }],
      copyOption: {
        column: [{
          label: "表单key",
          prop: "key",
          rules: [{
            required: true,
            message: "请输入表单key",
            trigger: "blur"
          }],
        },
        {
          label: "表单名称",
          prop: "name",
          rules: [{
            required: true,
            message: "请输入表单名称",
            trigger: "blur"
          }],
        },
        {
          label: '备注',
          prop: 'remark',
          type: 'textarea',
          span: 24
        },
        {
          label: '状态',
          prop: 'status',
          type: 'select',
          dicData: [{
            label: '可用',
            value: 1
          }, {
            label: '禁用',
            value: 2
          }],
          rules: [{
            required: true,
            message: "请选择状态",
            trigger: "change"
          }],
        },]
      },
      isCopy: false,
      copyVisible: false
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.wf_design_form_add, false),
        viewBtn: this.vaildData(this.permission.wf_design_form_view, false),
        delBtn: this.vaildData(this.permission.wf_design_form_delete, false),
        editBtn: this.vaildData(this.permission.wf_design_form_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    handleSubmit() {
      this.$refs.formDesign.getData('string').then(data => {
        if (this.isCopy) {
          this.copyVisible = true
          this.form.content = data
        } else {
          this.row.content = data
          this.$confirm('是否将此表单保存为新版本？这意味着可以返回到以前的版本。', '提示', {
            confirmButtonText: '否',
            cancelButtonText: '是',
            type: 'warning'
          }).then(() => {
            this.row.newVersion = false

            update(this.row).then(() => {
              this.$message.success("保存成功")
              this.onLoad(this.page, this.query)
              this.formVisible = false
            })
          }).catch(() => {
            this.row.newVersion = true

            update(this.row).then(() => {
              this.$message.success("保存成功")
              this.onLoad(this.page, this.query)
              this.formVisible = false
            })
          })
        }
      })
    },
    handleDesign(row) {
      this.formVisible = true
      this.options = this.deepClone(row.content || '')
      this.row = row
      this.isCopy = false
    },
    handleCopy(row) {
      this.formVisible = true
      this.options = this.deepClone(row.content || '')
      this.isCopy = true
    },
    handleCopySubmit(form, done) {
      const param = {
        ...form,
        content: this.form.content
      }
      add(param).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.$refs.copyForm.resetFields()
        done()
        this.copyVisible = false
        this.formVisible = false
      }).catch(() => {
        done()
      })
    },
    rowSave(row, loading, done) {
      add(row).then(() => {
        loading();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        done();
        console.log(error);
      });
    },
    rowUpdate(row, index, loading, done) {
      update(row).then(() => {
        loading();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        done();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.onLoad(this.page, params);
      done()
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
    }
  }
};
</script>

<style>
</style>
