<template>
  <div class="table-container">
    <vab-query-form>
      <vab-query-form-left-panel>
        <el-form
          ref="searchForm"
          :model="searchForm"
          :inline="true"
          @submit.native.prevent
        >
          <el-form-item>
            <el-input v-model="searchForm.name" placeholder="定时任务名称" />
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              type="primary"
              native-type="submit"
              @click="handleQuery"
            >
              查询
            </el-button>
            <el-button icon="el-icon-plus" type="primary" @click="handleAdd">
              添加
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-left-panel>
    </vab-query-form>

    <el-table
      ref="tableSort"
      v-loading="listLoading"
      :data="tableData"
      :element-loading-text="elementLoadingText"
      :height="height"
      :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }"
    >
      >

      <el-table-column show-overflow-tooltip label="序号" width="95">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="name" label="名称" />
      <el-table-column
        show-overflow-tooltip
        prop="executeClass"
        label="执行类"
      />

      <el-table-column show-overflow-tooltip prop="code" label="编码" />
      <el-table-column show-overflow-tooltip prop="sor" label="排序" />

      <el-table-column
        show-overflow-tooltip
        prop="type"
        label="类型"
        :formatter="formatType"
      />
      <el-table-column show-overflow-tooltip prop="description" label="描述" />
      <el-table-column
        show-overflow-tooltip
        prop="inCode"
        label="所属公司"
        :formatter="formatCompany"
      />

      <el-table-column show-overflow-tooltip label="操作" width="180px">
        <template #default="{ row }">
          <el-button type="text" @click="handleEdit(row)">
            <el-tag type="success">编辑</el-tag>
          </el-button>
          <el-button type="text" @click="handleDelete(row)">
            <el-tag type="danger">删除</el-tag>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :background="background"
      :current-page="page.currentPage"
      :layout="layout"
      :page-size="page.pageSize"
      :total="page.total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    ></el-pagination>

    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      width="500px"
      @close="close"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model.trim="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="执行类"  prop="executeClass">
          <el-input
            :disabled="typeEdit"
            v-model.trim="form.executeClass"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="编码" prop="code">
          <el-input v-model.trim="form.code" :disabled="typeEdit" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="排序" prop="sor">
          <el-input
            v-model.trim="form.sor"
            type="string"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-select
            v-model.trim="form.type"
            clearable
            placeholder="请选择"

            @change="typeChange"
          >
            <el-option
              v-for="item in types"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所属公司" prop="inCode">
          <el-select
            v-model.trim="form.inCode"
            clearable
            placeholder="请选择"
            :disabled="companyEdit"
          >
            <el-option
              v-for="item in companys"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model.trim="form.description"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdate()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    fetchList,
    addObj,
    putObj,
    delObj,
    getExecuteClass,
    getCode,
  } from '@/api/quartzBase'
  import { getCompanyAll } from '@/api/integrationCompany'
  export default {
    name: 'QuartzBase',

    data() {
      const validateExecuteClass = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请输入执行类'))
        }
        getExecuteClass(value).then((response) => {
          if (this.dialogType === 'edit') callback()
          let result = response.data
          if (result !== null) {
            callback(new Error('执行类已存在'))
          } else {
            callback()
          }
        })
      }

      const validateCode = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请输入编码'))
        }
        getCode( value).then((response) => {
          if (this.dialogType === 'edit') callback()
          let result = response.data
          if (result !== null) {
            callback(new Error('编码已存在'))
          } else {
            callback()
          }
        })
      }

      const validateSor = (rule, value, callback) => {

        if (!value) {
          return callback(new Error('请输入排序'))
        }
        let isTel =/^([0-9]+\.?[0-9]*|-[0-9]+\.?[0-9]*)$/.test(value);
        if (!isTel) {
          return callback(new Error('请输入整数'))
        } else {
          return callback()
        }
      }

      return {
        typeEdit: false,
        companyEdit: false,
        dialogFormVisible: false,
        dialogType: '',
        title: '',
        tableData: [],
        companys: [],
        searchForm: {
          code: null,
          name: null,
        },
        form: {},
        types: [
          { label: '公共', value: 'PUBLIC' },
          { label: '私有', value: 'PRIVATE' },
        ],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        background: true,
        elementLoadingText: '正在加载...',
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20, // 每页显示多少条
        },
        rules: {
          name: [
            { required: true, trigger: 'blur', message: '请输入公司名称' },
          ],

          executeClass: [
            {
              required: true,
              trigger: 'blur',
              validator: validateExecuteClass,
            },
          ],

          code: [
            {
              required: true,
              trigger: 'blur',
              validator: validateCode,
            },
          ],

          type: [
            {
              required: true,
              trigger: 'blur',
              message: '请输入类型'
            },
          ],
          sor: [
            {
              required: true,
              trigger: 'blur',
              validator: validateSor,
            },
          ],
        },
      }
    },
    computed: {
      height() {
        return this.$baseTableHeight()
      },
    },
    created() {
      this.getCompany()
    },
    methods: {
      handleChange(value) {
        this.form.sor = value
      },
      getCompany() {
        getCompanyAll()
          .then((response) => {
            this.companys = response.data
            this.fetchData()
            this.listLoading = false
          })
          .catch(() => {
            this.listLoading = false
          })
      },
      async fetchData() {
        this.listLoading = true
        fetchList(
          Object.assign(
            {
              current: this.page.currentPage,
              size: this.page.pageSize,
            },
            this.searchForm
          )
        )
          .then((response) => {
            this.tableData = response.data.records
            this.page.total = response.data.total
            this.listLoading = false
          })
          .catch(() => {
            this.listLoading = false
          })
      },

      handleSizeChange(val) {
        this.page.pageSize = val
        this.page.currentPage = 1
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.page.currentPage = val
        this.fetchData()
      },
      handleQuery() {
        for (var v in this.searchForm) {
          if (this.searchForm[v] == '') {
            delete this.searchForm[v]
          }
        }

        this.page.currentPage = 1
        this.fetchData()
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
        this.$emit('fetch-data')
      },
      handleAdd() {
        this.typeEdit = false
        this.form = {}
        this.title = '新增'
        this.dialogType = 'add'
        this.dialogFormVisible = true
      },
      handleEdit(row) {
        this.typeEdit = true
        var newObj = JSON.parse(JSON.stringify(row))
        this.form = newObj
        this.title = '修改'
        this.dialogType = 'edit'
        this.dialogFormVisible = true
      },
      handleDelete(row) {
        this.$baseConfirm('你确定要删除当前项吗', null, async () => {
          const { msg } = await delObj(row.id)
          this.$baseMessage(msg, 'success')
          this.fetchData()
        })
      },
      saveOrUpdate() {
        if (this.dialogType == 'add') {
          this.save()
        } else {
          this.update()
        }
      },
      save() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.listLoading = true
            addObj(this.form)
              .then((response) => {
                this.dialogFormVisible = false
                this.fetchData()
                this.listLoading = false
              })
              .catch(() => {
                this.listLoading = false
              })
          } else {
            return false
          }
        })
      },
      update() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.listLoading = true
            console.log(this.form)
            putObj(this.form)
              .then((response) => {
                this.$message({
                  message: '修改成功',
                  type: 'success',
                })
                this.dialogFormVisible = false
                this.fetchData()
                this.listLoading = false
              })
              .catch(() => {
                this.$message({
                  message: '修改失败',
                  type: 'warning',
                })
                this.listLoading = false
              })
          } else {
            return false
          }
        })
      },

      formatCompany(row, column) {
        for (let i = 0; i < this.companys.length; i++) {
          if (row.inCode == this.companys[i].code) {
            return this.companys[i].name
          }
        }
      },
      formatType(row, column) {
        for (let i = 0; i < this.types.length; i++) {
          if (row.type == this.types[i].value) {
            return this.types[i].label
          }
        }
      },

      typeChange(value) {
        if (value == 'PUBLIC') {
          this.$set(this.form, 'inCode', null)
          this.companyEdit = true
        } else {
          this.companyEdit = false
        }
      },
    },
  }
</script>

<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
