<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="应用类型" prop="cfgType">
        <el-select v-model="queryParams.cfgType" placeholder="请选择应用类型" clearable>
          <el-option
            v-for="dict in dict.type.sys_apply_cfg_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="应用主键" prop="appId">
        <el-input
          v-model="queryParams.appId"
          placeholder="请输入应用主键"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目主键"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单位名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入单位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否有效" prop="isDel">
        <el-select v-model="queryParams.isDel" placeholder="请选择是否删除" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </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:applyConfig:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:applyConfig:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:applyConfig:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:applyConfig:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="applyConfigList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="应用类型" align="center" prop="cfgType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_apply_cfg_type" :value="scope.row.cfgType"/>
        </template>
      </el-table-column>
      <el-table-column label="项目信息" align="center" prop="projectName" />
      <el-table-column label="部门信息" align="center" prop="deptName" />
      <el-table-column label="AppId" align="center" prop="appId" />
      <el-table-column label="AppSecret" align="center" prop="publicKey" width="500"/>
      <el-table-column label="是否有效" align="center" prop="isDel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.isDel"/>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" width="100"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </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:applyConfig:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:applyConfig: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="680px" append-to-body :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div class="page-warning">
          <p><strong style="color: #E6A23C;">“应用公钥”</strong> 在注册应用后由系统生成，请在保存后查看。</p>
        </div>
        <el-form-item label="应用类型" prop="cfgType">
          <el-select v-model="form.cfgType" placeholder="请选择应用类型" style="width: 100%" :disabled="getDisabled()">
            <el-option
              v-for="dict in dict.type.sys_apply_cfg_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应用主键" prop="appId">
          <el-input v-model="form.appId" placeholder="请输入应用主键" :disabled="true"/>
        </el-form-item>
        <el-form-item label="应用公钥" prop="publicKey" v-if="form.publicKey">
          <el-input type="textarea" :rows="6" v-model="form.publicKey" placeholder="请输入应用公钥" :disabled="true"/>
        </el-form-item>
        <el-form-item label="项目信息" prop="projectId">
          <el-select
            v-model="form.projectId"
            :disabled="getDisabled()"
            filterable
            clearable
            placeholder="请选择所属项目"
            style="width: 100%"
            @change="projectChange"
          >
            <el-option
              v-for="item in projectOptions"
              :key="item.id"
              :label="item.projectName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <div class="page-warning">
          <p><strong style="color: #E6A23C;">“单位信息”</strong> 只能选择<strong style="color: #E6A23C;">“总包单位”</strong>。</p>
        </div>
        <el-form-item label="单位信息" prop="deptId">
          <el-select
            v-model="form.deptId"
            :disabled="getDisabled()"
            clearable
            placeholder="请选择所属单位"
            style="width: 100%"
          >
            <el-option
              v-for="item in deptOptions"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应用状态" prop="isDel">
          <el-select v-model="form.isDel" placeholder="请选择应用状态" style="width: 100%">
            <el-option
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="注册说明" prop="remark">
          <el-input type="textarea" :rows="3" v-model="form.remark" placeholder="请输入注册说明" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listApplyConfig, getApplyConfig, delApplyConfig, addApplyConfig, updateApplyConfig, getApplyId } from "@/api/system/applyConfig";

export default {
  name: "ApplyConfig",
  dicts: ['sys_normal_disable','sys_apply_cfg_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 系统应用注册表格数据
      applyConfigList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        appId: null,
        projectId: null,
        projectName: null,
        deptId: null,
        deptName: null,
        isDel: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        cfgType: [
          { required: true, message: "请选择注册应用类型", trigger: "blur" },
        ],
        projectId: [
          { required: true, message: "请选择所属项目信息", trigger: "blur" },
        ],
        deptId: [
          { required: true, message: "请选择所属单位信息", trigger: "blur" },
        ],
        appId: [
          { required: true, message: "请输入应用主键信息", trigger: "blur" },
        ],
        isDel: [
          { required: true, message: "请选择应用状态", trigger: "blur" },
        ],
        remark: [
          { required: false, message: "请输入申请说明", trigger: "blur" },
          { maxlength: 200, message: "申请说明最多200字符", trigger: "blur" },
        ],
      },
      projectOptions: [],
      deptOptions :[],
    };
  },
  created() {
    this.getList();
    this.getProjectList();
  },
  methods: {
    projectChange(val){
      this.form.deptId=null;
      // 根据项目查询总包单位
      this.initDept(val);
    },
    initDept(val){
      this.$api.publics
        .queryUnitList({
          projectId: val,
          unitType: 2
        })
        .then((d) => {
          this.deptOptions = d.rows;
          if (d.rows.length > 0) {
            // 有总包单位
          } else {
            this.$message.error("当前项目未分配总包单位，不能注册应用！");
          }
        });
    },
    /** 查询系统应用注册列表 */
    getList() {
      this.loading = true;
      listApplyConfig(this.queryParams).then(response => {
        this.applyConfigList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取项目列表
    getProjectList() {
      let param = {
        data: {},
      };
      //获取项目列表的接口
      this.$api.publics.getProjectList(param).then((response) => {
        this.projectOptions = response.rows;
      });
    },
    getDisabled(){
      if(this.form && this.form.id){
        return true;
      }else{
        return false;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        appId: null,
        publicKey: null,
        privateKey: null,
        projectId: null,
        deptId: null,
        isDel: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: 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();
      getApplyId().then(response => {
        this.form.appId = response.msg;
        this.open = true;
        this.title = "系统应用注册";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      
      getApplyConfig(id).then(response => {
        this.$api.publics
        .queryUnitList({
          projectId: response.data.projectId,
          unitType: 2
        })
        .then((d) => {
          this.deptOptions = d.rows;
          this.form = response.data;
          this.open = true;
          this.title = "系统应用修改";
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id) {
            updateApplyConfig(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addApplyConfig(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除系统应用编号为"' + ids + '"的数据项？').then(function() {
        return delApplyConfig(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/applyConfig/export', {
        ...this.queryParams
      }, `applyConfig_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss">
.page-warning {
    padding: 8px 16px;
    background-color: #f0f9eb;
    border-radius: 4px;
    border-left: 5px solid #67C23A;
    margin: 20px 0;
    font-size: 13px;
    margin-top: 10px;
} 
</style>
