<template>
  <div :class="open && open.length > 0 ? '' : 'app-container'">
    <Form ref="formRef" :formList="formList" :ruleFormData="ruleForm" :config="config" @fnClick="callback"></Form>
  </div>
</template>

<script setup name="Handle">
  import Form from '@/components/form/index.vue';
  import {addMtrAgent, getMtrAgent, allMtrClientIdData} from "@/api/disRevenue/resource"
  export default {
    name: 'mtrAgent_view',
    components: {Form},
    dicts: ['policy_method', 'rm_register_online_state', 'agent_update_result', 'rm_register_status'],
    props: {
      open: {
        type: String,
        default: ''
      },
      dialogRowData: {
        type: Object,
        default: () => {}
      }
    },
    watch: {
      open: {
        handler(val) {
          if (val === 'type_true') {
            this.paramsData = {};
            this.$set(this.ruleForm, 'mtrClientIds', this.dialogRowData && this.dialogRowData.mtrClientId || '');
          } else if (val === 'type_false') {
            // 清空form
            this.$refs['formRef'].$refs.ruleForm.resetFields();
          }
        },
        deep: true,
        immediate: true
      },
    },
    data() {
      return {
        ruleForm: {},
        formList: [],
        paramsData: {},
        config: {},
        includeList: {},
        clientIdList: {},
      }
    },
    created() {
      this.paramsData = this.$route && this.$route.query;
      if (this.open) {
        this.paramsData = {};
        if (this.dialogRowData && this.dialogRowData.mtrClientId) {
          this.$set(this.ruleForm, 'mtrClientIds', this.dialogRowData && this.dialogRowData.mtrClientId || '');
        }
      }
      if (this.paramsData && this.paramsData.id) {
        this.getFormDataList(this.paramsData.id);
      } else {
        this.fnFormList();
        // this.getResNameList();
      }
      this.getMtrClientList();
      if (this.paramsData && this.paramsData.readonly) {
        this.config = {
          buttonGroup: [{title: '返回', fnCode: 'goBack'}]
        };
      }
    },
    methods: {
      // formList集合
      fnFormList(objVal) {
        let colSpan = 18;
        if (this.paramsData && this.paramsData.readonly) {
          colSpan = 12;
        }
        this.formList = [{
          config: {title: ' ', colSpan: '', readonly: this.paramsData && this.paramsData.readonly},
          controls: {
            id: {label: 'ID',hidden: true},
            mtrClientId: {label: 'MTRClientID', span: colSpan, type: 'input', hidden: this.paramsData && this.paramsData.readonly ? false : true},
            version: {label: '版本', span: colSpan, type: 'input', hidden: this.paramsData && this.paramsData.readonly ? false : true},
            logicalNode: {label: '标识', span: colSpan, type: 'input', hidden: this.paramsData && this.paramsData.readonly ? false : true},
            registerTime: {label: '注册时间', span: colSpan, type: 'datetime', hidden: this.paramsData && this.paramsData.readonly ? false : true},
            registerStatus: {label: '注册状态', span: colSpan, type: 'select', options: this.dict.type.rm_register_status, hidden: this.paramsData && this.paramsData.readonly ? false : true},
            onlineStatus: {label: '在线状态', span: colSpan, type: 'select', options: this.dict.type.rm_register_online_state, hidden: this.paramsData && this.paramsData.readonly ? false : true},
            heartbeatInterval: {label: '心跳时间间隔(s)', span: colSpan, type: 'input', hidden: this.paramsData && this.paramsData.readonly ? false : true},
            heartbeatCount: {label: '心跳次数', span: colSpan, type: 'input', hidden: this.paramsData && this.paramsData.readonly ? false : true},
            method: {label: '更新方式', span: colSpan, type: 'select', options: this.dict.type.policy_method, eventName: 'change', required: true},
            scheduledUpdateTime: {label: '更新时间', span: colSpan, type: 'datetime', required: true, hidden: objVal && objVal.method === '1' ? false: true},
            filePath: {label: '文件地址', span: colSpan, type: 'input', required: true, placeholder: '请输入外网地址', warningTitle: '如：http://www.tr.com/server-1.1.1.jar'},
            fileMd5: {label: '文件MD5', span: colSpan, type: 'input', required: true},
            mtrClientIds: {label: '部署设备', span: colSpan, type: 'textarea', rows:15, placeholder: '请粘贴/输入MTRClientID列表，如\nMTRClientID1\nMTRClientID2\n...', required: true, hidden: this.paramsData && this.paramsData.readonly ? true : false},
            clientAllId: {label: '加载全部MTRClientID', span: 3, type: 'button', style: 'vertical-align: top', hidden: this.paramsData && this.paramsData.readonly ? true : this.paramsData && this.paramsData.id ? true : false},
            lastUpdateResult: {label: '最后一次更新结果', span: colSpan, type: 'select', options: this.dict.type.agent_update_result, hidden: this.paramsData && this.paramsData.readonly ? false : true},
            lastUpdateTime: {label: '最后一次更新时间', span: colSpan, type: 'datetime', hidden: this.paramsData && this.paramsData.readonly ? false : true},
            networkInfo: {label: '网卡信息', span: colSpan, type: 'input', hidden: this.paramsData && this.paramsData.readonly ? false : true},
            description: {label: '描述', span: colSpan, type: 'input', disabled: true, hidden: this.paramsData && this.paramsData.readonly ? false : true},
            cpucores: {label: 'cpu核数', span: colSpan, type: 'input', disabled: true, hidden: this.paramsData && this.paramsData.readonly ? false : true},
          }
        }];
      },
      // 获取详情
      getFormDataList(id) {
        getMtrAgent(id).then(val => {
          if (val && val.data) {
            val.data['method'] = val.data && val.data['method'] || val.data['method'] === 0 ? val.data['method'].toString() : val.data['method'];
            this.fnFormList(val.data);
            this.ruleForm = val.data;
          }
        }).catch(() => {
          // this.$modal.msgError("操作失败")
        });
      },
      getMtrClientList() {
        allMtrClientIdData({}).then(res => {
          if (res && res.data) {
            res && res.data.map(item => {
              this.clientIdList[item.mtrClientId] = item.mtrClientId;
            });
          }
        });
      },
      // 监听事件
      callback(result, dataVal, formVal) {
        if (result && result.fnCode) {
          switch (result.fnCode) {
            case 'method':
              if (dataVal === '1') {
                this.formList[0].controls.scheduledUpdateTime['hidden'] = false;
              } else {
                this.formList[0].controls.scheduledUpdateTime['hidden'] = true;
              }
              break;
            case 'clientAllId':
              this.$set(this.ruleForm, 'mtrClientIds', '');
              allMtrClientIdData({}).then(res => {
                let str = '';
                if (res && res.data) {
                  res && res.data.map(item => {
                    str+= item.mtrClientId + '\n';
                  });
                }
                this.$set(this.ruleForm, 'mtrClientIds', str);
              });
              break;
            case 'submit':
              let unknownData = [];
              if (dataVal && dataVal.mtrClientIds) {
                let deployList = JSON.parse(JSON.stringify(dataVal.mtrClientIds.trim())).split('\n');
                deployList.forEach(item => {
                  if (!this.clientIdList[item]) {
                    unknownData.push(item);
                  }
                });
              }
              if (unknownData && unknownData.length > 0) {
                this.$modal.msgWarning(`存在未知的MTRClientID: ${unknownData.join('; ')}`);
                return;
              }
              addMtrAgent(dataVal).then(response => {
                this.$modal.msgSuccess(response.msg);
                if (this.open) {
                  this.$emit("dialogResult", {open: true});
                } else {
                  this.$router.push("/resource/mtrAgent")
                }
              }).catch(() => {
                this.$modal.msgError("操作失败")
              });
              break;
            case 'cancel':
              if (this.open) {
                this.$emit("dialogResult", {open: false});
              } else {
                this.$router.push("/resource/mtrAgent")
              }
              break;
            default:
          }
        }
      }
    }
  }
</script>
<style>
</style>
