<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      :class="showSearch ? '' : ' hide'"
      label-width="68px"
    >
      <el-form-item label="服务名称" prop="serviceName">
        <el-input
          v-model="queryParams.serviceName"
          placeholder="请输入服务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据源" prop="databaseName">
        <el-input
          v-model="queryParams.databaseName"
          placeholder="请输入数据源名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表名" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          placeholder="请输入表名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="同步方式" prop="mode">
        <el-select v-model="queryParams.mode" placeholder="同步方式">
          <el-option label="增量" value="add"></el-option>
          <el-option label="全量" value="full"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system/share:serviceCache:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="serviceCacheList">
      <el-table-column label="编号" align="center" prop="id" width="80" />
      <el-table-column label="服务名称" prop="serviceName" />
      <el-table-column label="缓存数据源名称" prop="databaseName" />
      <el-table-column label="缓存表名" align="center" prop="tableName" />
      <el-table-column label="同步方式" align="center" prop="mode">
        <template slot-scope="scope">
          <span v-if="scope.row.mode === 'add'">增量</span>
          <span v-if="scope.row.mode === 'full'">全量</span>
        </template>
      </el-table-column>
      <el-table-column label="同步周期" align="center" prop="cacheCycleUnit">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_task_cycle"
            :value="scope.row.cacheCycleUnit"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status === '1'">启用</el-tag>
          <el-tag type="danger" v-if="scope.row.status === '0'">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system/share:serviceCache:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system/share:serviceCache:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改服务缓存对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="共享服务" prop="serviceId">
          <el-select
            v-model="form.serviceId"
            placeholder="请选择"
            @change="changeService"
          >
            <el-option
              :label="srv.serviceName"
              :value="srv.id"
              v-for="(srv, i) in serviceList"
              :key="i"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务地址" v-if="form.serviceId">
          {{ serviceList.find((p) => p.id === form.serviceId).serviceUrl }}
        </el-form-item>
        <el-form-item label="请求参数" prop="requestParam">
          <el-input
            v-model="form.requestParam"
            placeholder="调用接口必要参数，JSON格式"
            type="textarea"
            rows="5"
          ></el-input>
        </el-form-item>
        <el-form-item label="数据源" prop="databaseId">
          <el-select
            v-model="form.databaseId"
            placeholder="请选择数据源"
            filterable
            :disabled="form.id > 0"
          >
            <el-option
              :label="`${db.databaseName}（${db.aliasName}）`"
              :value="db.id"
              v-for="(db, i) in databaseList"
              :key="i"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="表名" prop="tableName">
          <el-input
            v-model="form.tableName"
            placeholder="请输入表名"
            :disabled="form.id > 0"
          />
        </el-form-item>
        <el-form-item label="同步方式" prop="mode">
          <el-select v-model="form.mode" placeholder="同步方式">
            <el-option label="增量" value="add"></el-option>
            <el-option label="全量" value="full"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="增量字段" prop="addField">
          <el-input v-model="form.addField" placeholder="请输入增量字段" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="cacheCycleValue" label="同步周期">
              <el-input
                v-model="form.cacheCycleValue"
                placeholder="请输入周期值"
              >
                <template slot="prepend" v-if="form.cacheCycleUnit !== 'w'"
                  >每</template
                >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-row>
              <el-col :span="12">
                <el-form-item prop="cacheCycleUnit" class="complex-select">
                  <el-select
                    v-model="form.cacheCycleUnit"
                    placeholder="请选择周期单位"
                    style="display: flex; justify-content: flex-start"
                  >
                    <el-option
                      v-for="dict in dict.type.sys_task_cycle"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" style="line-height: 36px; padding-left: 10px"
                >执行一次</el-col
              >
            </el-row>
          </el-col>
        </el-row>
        <el-form-item label="页字段名" prop="pageField">
          <el-input
            v-model="form.pageField"
            placeholder="请输入页字段名，如：page"
          />
        </el-form-item>
        <el-form-item label="页大小字段" prop="pageSizeField">
          <el-input
            v-model="form.pageSizeField"
            placeholder="请输入页大小字段名，如：size"
          />
        </el-form-item>
        <el-form-item label="搜索字段名" prop="searchField">
          <el-input
            v-model="form.searchField"
            placeholder="请输入搜索字段，如：search"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            placeholder="请输入备注"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="submitting"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listServiceCache,
  getServiceCache,
  delServiceCache,
  addServiceCache,
  updateServiceCache,
} from "@/api/system/share/serviceCache";

import { listDatabase } from "@/api/system/base/database";

import { listService } from "@/api/system/share/service";

export default {
  name: "ServiceCache",
  dicts: ["sys_task_cycle"],
  data() {
    const validateCycleValue = (rule, value, callback) => {
      if (value) {
        // if (!isMobile(value)) {
        //   callback("请输入正确手机");
        // }
        if (isNaN(value)) {
          callback("必须为数字");
        }

        if (this.form.cacheCycleUnit === "mi") {
          if (value < 0 || value > 60) {
            callback("每分钟第几秒必须在0-60之间");
          }
        } else if (this.form.cacheCycleUnit === "h") {
          if (value < 0 || value > 60) {
            callback("每小时第几分钟必须在0-60之间");
          }
        } else if (this.form.cacheCycleUnit === "d") {
          if (value < 0 || value > 23) {
            callback("每天第几小时必须在0-23之间");
          }
        } else if (this.form.cacheCycleUnit === "w") {
          if (value < 1 || value > 7) {
            callback("每周几必须在1-7之间");
          }
        } else if (this.form.cacheCycleUnit === "m") {
          if (value < 1 || value > 31) {
            callback("每月第几日必须在0-31之间");
          }
        } else if (this.form.cacheCycleUnit === "y") {
          if (value < 0 || value > 12) {
            callback("每年第几月必须在1-12之间");
          }
        }

        callback();
      }
      callback();
    };
    return {
      // 遮罩层
      loading: true,
      submitting: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 服务缓存表格数据
      serviceCacheList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serviceId: null,
        serviceName: null,
        databaseId: null,
        databaseName: null,
        tableId: null,
        tableName: null,
        mode: null,
        addField: null,
        cacheCycleUnit: null,
        cacheCycleValue: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        serviceId: [
          { required: true, message: "共享服务不能为空", trigger: "change" },
        ],
        databaseId: [
          { required: true, message: "数据源不能为空", trigger: "change" },
        ],
        tableName: [
          { required: true, message: "表名不能为空", trigger: "change" },
        ],
        mode: [
          {
            required: true,
            message: "同步方式不能为空",
            trigger: "change",
          },
        ],
        addField: [
          { required: true, message: "增量字段不能为空", trigger: "change" },
        ],
        pageField: [
          { required: true, message: "页字段不能为空", trigger: "change" },
        ],
        pageSizeField: [
          { required: true, message: "页大小字段不能为空", trigger: "change" },
        ],
        searchField: [
          { required: true, message: "搜索字段不能为空", trigger: "change" },
        ],
        cacheCycleUnit: [
          { required: true, message: "同步周期不能为空", trigger: "change" },
        ],
        cacheCycleValue: [
          { required: true, message: "同步周期值不能为空", trigger: "change" },
          { validator: validateCycleValue, trigger: "change" },
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" },
        ],
        delFlag: [
          { required: true, message: "删除标志不能为空", trigger: "change" },
        ],
      },
      serviceList: [],
      databaseList: [],
    };
  },
  created() {
    this.getServiceList();
    this.getDatabaseList();
    this.getList();
  },
  methods: {
    changeService(e) {
      // const service = this.serviceList.find((p) => p.id === e);
      // const form = JSON.parse(JSON.stringify(this.form));
      // form.addField = service.addField;
      // form.pageField = service.pageField;
      // form.pageSizeField = service.pageSizeField;
      // form.searchField = service.searchField;
      // this.form = form;
    },
    getCycleRemark() {
      if (this.form.cacheCycleUnit === "mi") {
        return "每分钟第几秒";
      } else if (this.form.cacheCycleUnit === "h") {
        return "每小时第几分钟";
      } else if (this.form.cacheCycleUnit === "d") {
        return "每天几点";
      } else if (this.form.cacheCycleUnit === "w") {
        return "每周几";
      } else if (this.form.cacheCycleUnit === "m") {
        return "每月第几周";
      } else if (this.form.cacheCycleUnit === "y") {
        return "每年第几月";
      } else {
        return "请选择周期";
      }
    },
    getCycleUnit() {
      if (this.form.cacheCycleUnit === "mi") {
        return "秒";
      } else if (this.form.cacheCycleUnit === "h") {
        return "分钟";
      } else if (this.form.cacheCycleUnit === "d") {
        return "点";
      } else if (this.form.cacheCycleUnit === "w") {
        return "";
      } else if (this.form.cacheCycleUnit === "m") {
        return "周";
      } else if (this.form.cacheCycleUnit === "y") {
        return "月";
      } else {
        return "";
      }
    },
    getDatabaseList() {
      listDatabase({ status: 1 }).then((response) => {
        this.databaseList = response.rows;
      });
    },
    getServiceList() {
      listService({ responseForm: "standard", status: "1" }).then(
        (response) => {
          this.serviceList = response.rows;
        }
      );
    },
    /** 查询服务缓存列表 */
    getList() {
      this.loading = true;
      listServiceCache(this.queryParams).then((response) => {
        this.serviceCacheList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        serviceId: null,
        serviceName: null,
        databaseId: null,
        databaseName: null,
        tableId: null,
        tableName: null,
        mode: null,
        addField: null,
        cacheCycleUnit: null,
        cacheCycleValue: null,
        remark: null,
        status: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加服务缓存";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getServiceCache(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改服务缓存";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 检查周期值
          this.submitting = true;
          if (this.form.id != null) {
            updateServiceCache(this.form).then((response) => {
              this.submitting = false;
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(() => {
              this.submitting = false;
            });
          } else {
            addServiceCache(this.form).then((response) => {
              this.submitting = false;
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(() => {
              this.submitting = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除服务缓存编号为"' + ids + '"的数据项？')
        .then(function () {
          return delServiceCache(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/share/serviceCache/export",
        {
          ...this.queryParams,
        },
        `serviceCache_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
