<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.jobGroupName"
          clearable
          size="small"
          placeholder="输入任务组名称搜索"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-input
          v-model="query.jobName"
          clearable
          size="small"
          placeholder="输入任务名称搜索"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-input
          v-model="query.tableName"
          clearable
          size="small"
          placeholder="输入数据表名称搜索"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-select
          v-model="query.status"
          clearable
          size="small"
          placeholder="选择状态"
          style="width: 160px"
          class="filter-item"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in 2"
            :key="item"
            :label="item == 1 ? '启用' : '禁用'"
            :value="item == 1 ? 1 : 0"
          />
        </el-select>
        <!-- <date-range-picker v-model="query.baseCreateTime" class="date-item" /> -->
        <rrOperation />
      </div>
      <crudOperation :permission="permission">
        <!-- 任务日志 -->
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="info"
          icon="el-icon-tickets"
          @click="doLog"
          >日志</el-button
        >
      </crudOperation>
      <report-log ref="log" />
    </div>
    <!--Form表单-->
    <el-dialog
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crudCU"
      :title="crud.status.title"
      append-to-body
      width="1000px"
    >
      <el-form
        ref="form"
        :inline="true"
        :model="form"
        :rules="rules"
        size="small"
        label-width="120px"
      >
        <el-form-item label="任务组名称" prop="jobGroupName">
          <el-input v-model="form.jobGroupName" style="width: 220px" />
        </el-form-item>
        <el-form-item label="任务名称" prop="jobName">
          <el-input v-model="form.jobName" style="width: 220px" />
        </el-form-item>
        <el-form-item label="数据表名称" prop="tableName">
          <el-input v-model="form.tableName" style="width: 220px" />
        </el-form-item>
        <br />
        <el-form-item label="运行开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择运行开始时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="运行结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="选择运行结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="Cron表达式" prop="cronExpression">
          <el-input v-model="form.cronExpression" style="width: 220px" />
        </el-form-item>
        <el-form-item label="任务状态">
          <el-radio-group v-model="form.status" style="width: 220px">
            <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" autosize style="width: 570px" />
        </el-form-item>
        <el-table :data="form.fields" style="width: 100%" :default-sort="{ prop: 'sort' }">
          <el-table-column prop="name" label="字段名" align="center">
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="`fields[${scope.$index}].name`"
                :rules="{ required: true, trigger: 'blur', validator: validatorFieldName }"
                style="margin-bottom: 0px"
              >
                <el-input
                  v-model="scope.row.name"
                  size="small"
                  class="filter-item"
                  style="width: 100%"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="值" align="center">
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="`fields[${scope.$index}].value`"
                :rules="{ required: true, trigger: 'blur' }"
                style="margin-bottom: 0px"
              >
                <tag-select-simple
                  v-if="scope.row.type == 1"
                  v-model="scope.row.value"
                  size="small"
                  class="filter-item"
                  style="width: 100%"
                  @change="handleTagChange($event, scope.row)"
                />
                <el-input
                  v-else
                  v-model="scope.row.value"
                  size="small"
                  class="filter-item"
                  style="width: 100%"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="字段类型" align="center" width="130px">
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="`fields[${scope.$index}].type`"
                :rules="{ required: true, trigger: 'blur' }"
                style="margin-bottom: 0px"
              >
                <el-select
                  v-model="scope.row.type"
                  size="small"
                  style="width: 100%"
                  @change="handleChangeType(scope.row)"
                >
                  <el-option
                    v-for="item in optionsObj.ReportFieldType"
                    :key="item.value"
                    :label="item.label"
                    :value="+item.value"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="dataType" label="数据类型" align="center" width="130px">
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="`fields[${scope.$index}].dataType`"
                :rules="{ required: true, trigger: 'blur' }"
                style="margin-bottom: 0px"
              >
                <el-select
                  v-model="scope.row.dataType"
                  :disabled="scope.row.type == 1"
                  size="small"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in optionsObj.DataType"
                    :key="item.value"
                    :label="item.label"
                    :value="+item.value"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" align="center" width="120px">
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="`fields[${scope.$index}].sort`"
                style="margin-bottom: 0px"
              >
                <el-input-number
                  v-model.number="scope.row.sort"
                  :min="0"
                  :max="999"
                  controls-position="right"
                  style="width: 100%"
                  @change="handleSortFields"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center" width="130px">
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="`fields[${scope.$index}].remark`"
                style="margin-bottom: 0px"
              >
                <el-input
                  v-model="scope.row.remark"
                  type="textarea"
                  autosize
                  size="small"
                  style="width: 100%"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="operation" label="删除" align="center" width="60px">
            <template slot-scope="scope">
              <el-popconfirm title="确定删除此数据吗？" @confirm="handleDelFields(scope)">
                <el-button size="mini" type="danger" icon="el-icon-delete" slot="reference" />
              </el-popconfirm>
            </template>
          </el-table-column>
          <template slot="append">
            <el-button
              size="small"
              type="primary"
              icon="el-icon-circle-plus-outline"
              @click="handleAddFields()"
              style="width: 100%"
            />
          </template>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU"
          >确认</el-button
        >
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      style="width: 100%"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column :selectable="checkboxT" type="selection" width="55" align="center" />
      <el-table-column
        v-for="item in jobTableOptions"
        :key="item.prop"
        :label="item.label"
        :prop="item.prop"
        :width="item.width"
        :align="item.align"
        :fixed="item.fixed"
        :sortable="item.sortable"
      >
        <template slot-scope="scope">
          <span v-if="item.prop == 'status'">
            <el-tag :type="scope.row.status ? 'success' : 'danger'">
              {{ scope.row.status ? '启用' : '禁用' }}
            </el-tag>
          </span>
          <span v-else-if="item.prop.includes('Time')">
            {{ scope.row[item.prop] | formatDate }}
          </span>
          <span v-else>{{ scope.row[item.prop] }}</span>
        </template>
      </el-table-column>
      <!--   编辑与删除   -->
      <el-table-column
        v-if="checkPer(['admin', 'report:job:edit', 'report:job:del'])"
        label="操作"
        width="280px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <div style="display: flex; justify-content: center">
            <el-button
              v-permission="['admin', 'report:job:edit']"
              :loading="crud.status.cu === 2"
              size="mini"
              type="success"
              @click="executeJob(scope.row.id)"
              >执行</el-button
            >
            <el-button
              v-permission="['admin', 'report:job:edit']"
              :loading="crud.status.cu === 2"
              size="mini"
              :type="scope.row.status ? 'info' : 'warning'"
              style="margin-left: 5px; margin-right: 5px"
              @click="changeStatus(scope.row)"
            >
              {{ scope.row.status ? '禁用' : '启用' }}
            </el-button>
            <udOperation :data="scope.row" :permission="permission" />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
  </div>
</template>

<script>
import permission from '@/directive/permission'
import crudJob from '@/api/report/job'
import { getOptions } from '@/api/report/public'
import ReportLog from './log'

import CRUD, { presenter, header, form, crud } from '@crud/crud'
// import { crudOperation, rrOperation, udOperation, pagination } from '@crud'
import crudComps from '@crud'
import DateRangePicker from '@/components/DateRangePicker'
import { jobTableOptions } from '../tableConfig'
import TagSelectSimple from '@/components/TagSelectSimple'
import validate from '@/utils/validate'

const defaultForm = {
  id: '',
  jobGroupName: '',
  jobName: '',
  tableName: '',
  cronExpression: '',
  status: 1,
  remark: '',
  startTime: null,
  endTime: null,
  fields: [],
}
export default {
  name: 'ReportJob',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: {
    ...crudComps,
    DateRangePicker,
    ReportLog,
    TagSelectSimple,
  },
  cruds() {
    return CRUD({
      title: '报表任务',
      url: 'report/job/getList',
      listOrder: [],
      crudMethod: { ...crudJob },
    })
  },
  data() {
    var validateTableName = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入数据表名'));
        } else {
          if (!validate.isTableName(value)) {
            callback(new Error('数据表名只支持小写字母和下划线'));
          }
        }
        callback();
      };
    return {
      jobTableOptions,
      delLoading: false,
      permission: {
        add: ['admin', 'report:job:add'],
        edit: ['admin', 'report:job:edit'],
        del: ['admin', 'report:job:del'],
      },
      rules: {
        jobGroupName: [{ required: true, message: '请输入任务组名称', trigger: 'blur' }],
        jobName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        tableName: [{ required: true, validator: validateTableName, trigger: 'blur' }],
        //remark: [{ required: true, message: '请输入任务描述', trigger: 'blur' }],
        //startTime: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
        //endTime: [{ required: true, message: '请选择结束时间', trigger: 'blur' }],
        cronExpression: [{ required: true, message: '请输入Cron表达式', trigger: 'blur' }],
        //personInCharge: [{ required: true, message: '请输入负责人名称', trigger: 'blur' }]
      },
      optionsObj: {
        ReportFieldType: [],
        DataType: [],
      },
    }
  },
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
  },
  created() {
    this.getOptions()
  },
  methods: {
    // 执行
    execute(id) {
      crudJob
        .execution(id)
        .then((res) => {
          this.crud.notify('执行成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        })
        .catch((err) => {
          console.err(err)
        })
    },
    // 改变状态
    changeStatus(row) {
      crudJob
        .changeStatus({ id: row.id, status: row.status ? 0 : 1 })
        .then((res) => {
          this.crud.toQuery()
          this.crud.notify('操作成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        })
        .catch((err) => {
          console.err(err)
        })
    },
    executeJob(id) {
      crudJob
        .executeJob({ id })
        .then((res) => {
          this.crud.toQuery()
          this.crud.notify('执行成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        })
        .catch((err) => {
          console.err(err)
        })
    },
    delMethod(id) {
      this.delLoading = true
      crudJob
        .del([id])
        .then(() => {
          this.delLoading = false
          this.$refs[id].doClose()
          this.crud.dleChangePage(1)
          this.crud.delSuccessNotify()
          this.crud.toQuery()
        })
        .catch(() => {
          this.delLoading = false
          this.$refs[id].doClose()
        })
    },
    // 显示日志
    doLog() {
      this.$refs.log.dialog = true
      //this.$refs.log.doInit()
    },
    getOptions() {
      Object.keys(this.optionsObj).forEach(async (key) => {
        try {
          let res = await getOptions(key)
          if (res.code === 20000) this.optionsObj[key] = res.data.content
        } catch (error) {
          console.log(error)
        }
      })
    },
    handleDelFields(scope) {
      this.form.fields.splice(scope.$index, 1)
    },
    handleAddFields() {
      this.form.fields.push({
        name: '',
        value: '',
        type: 1,
        dataType: 8,
        sort: 999,
        remark: '',
      })
    },
    handleSortFields(currentValue, oldValue) {
      this.form.fields.sort((a, b) => a.sort - b.sort)
    },
    handleChangeType(row) {
      row.value = ''
    },
    handleTagChange(value, row) {
      row.dataType = Number(value.aux1)
    },
    checkboxT(row, rowIndex) {
      // return row.id !== 1
      return true
    },
    validatorFieldName(rule, value, callback) {
      if (!value) {
          callback(new Error('请输字段名'));
        } else {
          if (!validate.isFieldName(value)) {
            callback(new Error('字段名只支持字母、数字和下划线'));
          }
        }
        callback();
    }
  },
}
</script>

<style></style>
