<template>
  <div class="app-container">
    <el-card>
      <div>
      <el-input
              v-model="listQuery.search"
              placeholder="名称"
              style="width: 300px"
              class="filter-item"
              @keyup.enter.native="handleFilter"
            />
            <el-button
              class="filter-item"
              type="primary"
              icon="el-icon-search"
              @click="handleFilter"
              >搜索</el-button
            >
            <el-button
              class="filter-item"
              type="primary"
              icon="el-icon-refresh-left"
              @click="resetFilter"
              >重置</el-button
            >
    </div>
    <div style="margin-top: 10px">
      <el-button type="primary" icon="el-icon-plus" @click="handleCreate"
        >新增</el-button
      >
    </div>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-table
        v-loading="listLoading"
        :data="workflowList.results"
        border
        fit
        stripe
        highlight-current-row
        max-height="600"
      >
        <el-table-column type="index" width="50" />
        <el-table-column label="名称">
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column label="描述">
          <template slot-scope="scope">{{ scope.row.description }}</template>
        </el-table-column>
         <el-table-column label="工单查看权限校验">
           <template slot-scope="scope">
              {{ !!(scope.row.view_permission_check)?'是':'否' }}
          </template>
        </el-table-column>
         <el-table-column  width="180" label="创建时间">
          <template slot-scope="scope">{{ scope.row.create_time }}</template>
        </el-table-column>

        <el-table-column
          align="center"
          label="操作"
          width="220px"
        >
          <template slot-scope="scope">
            <el-link
              v-if="checkPermission(['workflow_update'])"
              @click="handlecfgt(scope)"
              >配置</el-link
            >
            <el-link
              v-if="checkPermission(['workflow_update'])"
              @click="handleEdit(scope)"
              >编辑</el-link
            >
            <el-link
              v-if="checkPermission(['workflow_delete'])"
              type="danger"
              @click="handleDelete(scope)"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="workflowList.count > 0"
        :total="workflowList.count"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getList"
      />
    </el-card>
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? '编辑设备' : '新增设备'"
    >
      <el-form
        ref="Form"
        :model="workflow"
        label-width="80px"
        label-position="right"
        :rules="rule1"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="workflow.name" placeholder="名称" />
        </el-form-item>
       
         
        <el-form-item label="描述" prop="description">
          <el-input
            type="textarea"
            :rows="4"
            v-model="workflow.description"
            placeholder="描述"
          />
        </el-form-item>
         <el-form-item
          label="查看权限校验"
          prop="view_permission_check"
          label-width="120px"
        >
          <el-switch v-model="workflow.view_permission_check"></el-switch>
        </el-form-item>
 <el-form-item
          label="限制表达式"
          prop="limit_expression"
          label-width="120px"
        >
         <vue-json-editor
      v-model="workflow.limit_expression"
      :showBtns="false"
      :mode="'code'"
      lang="zh"
      @json-change="onJsonChange"
      @json-save="onJsonSave"
      @has-error="onError"
    />
    <br>
       </el-form-item>
    <el-form-item
          label="展现表单字段"
          prop="display_form_str"
          label-width="120px"
        >
         <vue-json-editor
      v-model="workflow.display_form_str"
      :showBtns="false"
      :mode="'code'"
      lang="zh"
      @json-change="onJsonChange1"
      @json-save="onJsonSave1"
      @has-error="onError1"
    />
    <br>
    
     </el-form-item>

         <el-form-item label="标题模板" prop="title_template">
          <el-input v-model="workflow.title_template" placeholder="你有一个待办工单:{title}" />
        </el-form-item>
         <el-form-item label="内容模板" prop="content_template">
          <el-input v-model="workflow.content_template" placeholder="标题:{title}, 创建时间:{create_time}" />
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirm('Form')">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getWorkflowList, createWorkflow,updateWorkflow,deleteWorkflow } from "@/api/workflow";
import checkPermission from "@/utils/permission";
 import vueJsonEditor from 'vue-json-editor'
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
const defaultworkflow = {
  name: "",
  number: "",
};
export default {
  components: { Pagination,vueJsonEditor  },
  data() {
    return {
      workflow: defaultworkflow,
      view_permission_check:false,
       hasJsonFlag:true,  // json是否验证通过
         hasJsonFlag1:true,  // json是否验证通过
      workflowList: {
        count: 0,
      },
     
      listQuery: {
        page: 1,
        page_size: 20,
      },
      display_form_str:[],
      limit_expression:[],
      listLoading: true,
      dialogVisible: false,
      dialogType: "new",
      rule1: {
        name: [{ required: true, message: "请输入", trigger: "blur" }],
        description: [{ required: true, message: "请输入", trigger: "blur" }]
      },
    };
  },
  computed: {},
  watch: {},
  created() {
    this.getList();
  },
  methods: {
    checkPermission,
   
    getList() {
      this.listLoading = true;
      getWorkflowList(this.listQuery).then((response) => {
        if (response.data) {
          this.workflowList = response.data;
        }
        this.listLoading = false;
      });
    },
    
    
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    resetFilter() {
      this.listQuery = {
        page: 1,
        page_size: 20,
      }
      this.getList();
    },
    handleCreate() {
      this.workflow = Object.assign({}, defaultworkflow);
      this.dialogType = "new";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["Form"].clearValidate();
      });
    },
   
    handleEdit(scope) {
      this.workflow = Object.assign({}, scope.row); // copy obj
      this.dialogType = "edit";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["Form"].clearValidate();
      });
    },
    handlecfgt(scope)
    {
      this.$router.push({name:"configuration",params:{workflow:scope.row.id}})
    }
    ,
    handleDelete(scope) {
      this.$confirm("确认删除?", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(async () => {
          await deleteWorkflow(scope.row.id);
          this.getList();
          this.$message.success("成功");
        })
        .catch((err) => {
          console.error(err);
        });
    },
   
    async confirm(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const isEdit = this.dialogType === "edit";
          if (isEdit) {
             this.checkJson();
             this.checkJson2();
            updateWorkflow(this.workflow.id, this.workflow).then((res) => {
              if (res.code >= 200) {
                this.getList();
                this.dialogVisible = false;
                this.$message.success("成功");
              }
            });
          } else {
            this.checkJson();
             this.checkJson2();
            
            createWorkflow(this.workflow).then((res) => {
              if (res.code >= 200) {
                this.getList();
                 this.dialogVisible = false;
                this.$message.success("成功");
              }
            });
          }
        } else {
          return false;
        }
      });
    },


   onJsonChange (value) {
        // console.log('更改value:', value);
        // 实时保存
        this.onJsonSave(value)
      },
      onJsonSave (value) {
        // console.log('保存value:', value);
        this.limit_expression = value
        this.hasJsonFlag = true
      },
      onError(value) {
        // console.log("json错误了value:", value);
        this.hasJsonFlag = false
      },
       onJsonChange1 (value) {
        // console.log('更改value:', value);
        // 实时保存
        this.onJsonSave1(value)
      },
      onJsonSave1 (value) {
        // console.log('保存value:', value);
        this.display_form_str = value
        this.hasJsonFlag1 = true
      },
      onError1(value) {
        // console.log("json错误了value:", value);
        this.hasJsonFlag1 = false
      },
      // 检查json
      checkJson(){
        if (this.hasJsonFlag == false){
          // console.log("json验证失败")
          // this.$message.error("json验证失败")
          alert("限制表达式json验证失败")
          return false
        } else {
          // console.log("json验证成功")
          // this.$message.success("json验证成功")
          alert("限制表达式json验证成功")
          return true
        }
      },
       // 检查json
      checkJson2(){
        if (this.hasJsonFlag1 == false){
          // console.log("json验证失败")
          // this.$message.error("json验证失败")
          alert("展现表单字段json验证失败")
          return false
        } else {
          // console.log("json验证成功")
          // this.$message.success("json验证成功")
          alert("展现表单字段json1验证成功")
          return true
        }
      },


  },
};
</script>
