<template>
  <div class="app-container pageTopForm">
    <el-form :model="queryParams" ref="queryRef" size="small" v-show="showSearch" label-width="auto">
      <el-col :span="8">
        <el-form-item label="策略名称" prop="policyName">
          <el-input
            v-model="queryParams.policyName"
            placeholder="请输入策略名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="策略状态" prop="policyStatus">
          <el-select
            v-model="queryParams.policyStatus"
            placeholder="请选择策略状态"
            clearable>
            <el-option
              v-for="dict in dict.type.policy_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item class="lastBtnSty">
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-col>
    </el-form>
    <TableList :columns="columns" :config="config" :modelIdent="this.$options.name" :queryParams="queryParams" :tableList="tableList" @fnClick="callback" @fnRenderList="getList" @value-change="handleValueChange">
      <template #tempMethod="{ row, column }">
        <dict-tag :options="dict.type.policy_method" :value="row.executionMethod"/>
      </template>
      <template #tempResGroup="{ row, column }">
        {{resourceGroupIdList[row.resourceGroupId]}}
      </template>
      <template #tempType="{ row, column }">
        <dict-tag :options="dict.type.policy_status" :value="row.policyStatus"/>
      </template>
    </TableList>
  </div>
</template>

<script setup>
  import TableList from "@/components/table/index.vue"
  import {listPolicy, delPolicy, getResMonitorGroup, getPolicyList} from "@/api/disRevenue/resource"
  export default {
    name: 'ServerScript',
    components: {TableList},
    dicts: ['policy_status', 'policy_method'],
    data() {
      return {
        loading: true,
        showSearch: true,
        tableList: [],
        queryParams: {
          total: 0,
          pageNum: 1,
          pageSize: 10,
          policyName: '',
          policyStatus: ''
        },
        // 列显隐信息
        columns: {
          id: { label: `ID`,width: '50'},
          policyName: { label: `策略名称`, minWidth: '250', visible: true },
          executionMethod: { label: `执行方式`,minWidth: '80',  slotName: 'tempMethod', visible: true},
          resourceGroupId: { label: `关联资源组`,minWidth: '150', slotName: 'tempResGroup', visible: true },
          includedDevicesName: { label: `包含设备`,minWidth: '200', visible: true},
          policyStatus: { label: `策略状态`, minWidth: '80', slotName: 'tempType', visible: true },
          sourceFilePath: { label: `源文件路径`,minWidth: '150'},
          targetDirectory: { label: `目标目录`,minWidth: '200'},
          commandContent: { label: `命令内容`,minWidth: '200'},
          scheduledTime: { label: `定时时间`,minWidth: '200'},
          deployTime: { label: `下发策略时间`,minWidth: '160'},
          description: { label: `描述`,minWidth: '200'},
          createTime: { label: `创建时间`,minWidth: '160'},
          updateTime:{ label: `修改时间`,minWidth: '160'}
        },
        config: {
          searcherForm: [
            {label: '模版名称', prop: 'roleName', type: 'selset', options: []}
          ],
          tableButton: {
            top: [
              {content: '新增', fnCode: 'add', type: 'primary', icon: 'el-icon-plus', hasPermi: 'resource:monitorStategy:add'},
              {content: '删除', fnCode: 'delete', type: 'danger', icon: 'el-icon-delete', hasPermi: 'resource:monitorStategy:detele'},
              {content: '导出', fnCode: 'export', type: 'warning', icon: 'el-icon-download', hasPermi: 'resource:monitorStategy:export'},
            ],
            line: [
              {content: '修改', fnCode: 'edit', type: 'text', icon: 'el-icon-edit', hasPermi: 'resource:monitorStategy:edit'},
              {content: '详情', fnCode: 'details', type: 'text', icon: 'el-icon-view', hasPermi: 'resource:monitorStategy:details'},
              // {content: '复制', fnCode: 'copy', type: 'text', icon: 'el-icon-document-copy', hasPermi: 'disRevenue:resource:monitorStategy:copy'},
              {content: '下发策略', fnCode: 'strategy', type: 'text', showName: 'policyStatus', showVal: '0', icon: 'el-icon-sort-down', hasPermi: 'resource:monitorStategy:strategy'},
              {content: '删除', fnCode: 'delete', type: 'text', icon: 'el-icon-delete', hasPermi: 'resource:monitorStategy:detele'},
            ]
          }
        },
        resourceGroupIdList: {},
      }
    },
    created() {
      this.fnResMonitorGroup();
      this.getList();
    },
    activated() {
      this.$nextTick(() => {
        this.fnResMonitorGroup();
        this.getList();
      });
    },
    methods: {
      /** 查询列表 */
      getList() {
        this.loading = true;
        listPolicy(this.queryParams).then(response => {
          this.tableList = response.rows;
          this.queryParams.total = response.total;
          this.loading = false;
        })
      },
      // 资源组
      fnResMonitorGroup(){
        getResMonitorGroup().then(res => {
          if (res && res.data) {
            res && res.data.forEach(item => {
              this.resourceGroupIdList[item.id] = item.groupName;
            });
          }
        });
      },
      // 处理子组件传递的新值
      handleValueChange(newValue) {
        // 父组件更新自身数据，实现同步
        this.showSearch = newValue;
        // console.log('父组件拿到新值:', newValue);
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },

      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryRef");
        this.handleQuery();
      },

      callback(result, rowData, selectChange) {
        if (result && result.fnCode) {
          switch (result.fnCode) {
            case 'add':
              this.$router.push({
                path:'/resource/serverScript/details'});
              break;
            case 'edit':
              this.$router.push({
                path:'/resource/serverScript/details',
                query:{
                  id: rowData.id
                }
              });
              break;
            case 'details':
              this.$router.push({
                path:'/resource/serverScript/details',
                query:{
                  id: rowData.id,
                  readonly: true
                }
              });
              break;
            case 'delete':
              let delList = [];
              if (rowData && rowData.id) {
                delList.push(rowData.id);
              } else {
                delList = selectChange;
              }
              this.$modal.confirm('是否确认删除该数据？').then(function() {
                return delPolicy(delList)
              }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功")
              }).catch(() => {});
              break;
            case 'strategy':
              this.$modal.confirm('是否确认下发策略？').then(() => {
                this.$modal.loading();
                getPolicyList(rowData.id).then(res => {
                  this.getList();
                  this.$modal.msgSuccess(res.msg);
                  this.$modal.closeLoading();
                }).catch(error => {
                  this.$modal.closeLoading();
                });
              }).catch(() => {});
              break;
            case 'export':
              // let dataList = [];
              // Object.keys(this.columns).forEach(item => {
              //   if (item.visible) {
              //     dataList.push(item.prop);
              //   }
              // });
              // this.download("/system/monitorStategy/export", {properties: dataList,}, `拓扑管理_${new Date().getTime()}.xlsx`);
              let paramsList = Object.assign({}, this.queryParams,rowData);
              this.download("rocketmq/policy/export", paramsList, `服务器脚本策略_${new Date().getTime()}.xlsx`, null, 'json');
              break;
            default:
          }
        }
      }
    }
  }
</script>
<style scoped>
  ::v-deep .lastBtnSty .el-form-item__content{
    margin-left: 10px!important;
  }
</style>
