<template>
  <div class="app-container">
    <div v-if="paramsData && paramsData.readonly">
      <DynamicForm :formData="ruleFormDataTow" :showTactics="true" :readonly="true" :showView="true"></DynamicForm>
      <el-button type="primary" style="float: right;margin-top: 12px;" class="mb10" @click="goBack">返回</el-button>
    </div>
    <div v-else>
      <el-steps :active="active" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="脚本策略"></el-step>
        <el-step title="策略确认"></el-step>
      </el-steps>
      <!--    内容区   -->
      <div style="margin-top: 30px;">
        <!--    active:0    -->
        <div v-if="active === 0">
          <Form ref="formRef" style="text-align: center;" :formList="formList" :ruleFormData="ruleFormData" :config="config" @fnClick="callback"></Form>
        </div>
        <!--    active:2    -->
        <div v-if="active === 1">
          <DynamicForm ref="dyncForm" :formData="ruleFormDataTow"></DynamicForm>
        </div>
        <!--    active:3    -->
        <div v-if="active === 2">
          <DynamicForm :formData="ruleFormDataTow" :showTactics="true" :readonly="true"></DynamicForm>
        </div>
      </div>
      <el-button type="primary" v-show="active > 1" style="float: right;margin-top: 12px;margin-left: 10px;" @click="submit">提交</el-button>
      <el-button type="primary" v-show="active < 2" style="float: right;margin-top: 12px;" @click="next('1')">下一步</el-button>
      <el-button type="primary" v-show="active > 0" style="float: right;margin-top: 12px;" @click="next('-1')">上一步</el-button>
      <el-button type="primary" style="float: right;margin-top: 12px;" @click="goBack">返回</el-button>
    </div>
  </div>
</template>

<script setup>
  import Form from '@/components/form/index.vue';
  import TableList from "@/components/table/index.vue"
  import DynamicForm from './dynamicForm'
  import {getPolicy, addPolicy, updatePolicy, getResMonitorGroup, resNameList, listArrRegisterList} from "@/api/disRevenue/resource"
  export default {
    name: 'ServerScriptDetails',
    components: {Form, TableList, DynamicForm},
    data() {
      return {
        active: 0,
        synthesisList: {},
        // 第一节点
        ruleFormData: {
          resourceGroupId: '',
          includedDevicesDataList: []
        },
        config: {
          buttonGroup: []
        },
        formList: [],
        // 第二节点 1栏
        ruleFormDataTow: {},
        groupFormList: {},
        includedDevicesList: {},
        resourceGroupIdList: {},
      }
    },
    created() {
      this.paramsData = this.$route && this.$route.query;
      // console.log('paramsData===',this.paramsData);
      if (this.paramsData && this.paramsData.id) {
        this.getFormDataList(this.paramsData.id);
      }
      this.formRender();
      this.fnResMonitorGroup();
      this.getResNameList();
    },
    methods: {
      formRender(){
        this.formList = [{
          config: {title: '', colSpan: 'disBlock m0Auto'},
          controls: {
            id: {label: 'ID',hidden: true},
            policyName: {label: '策略名称', span: 12, type: 'input', rules: [{required: true, message: '请输入模版名称', trigger: 'blur'}]},
            description: {label: '描述', span: 12, type: 'textarea'},
            resourceGroupId: {label: '关联资源组', span: 12, eventName: 'change', type: 'select', options:[]},
            includedDevicesDataList: {label: '包含设备', span: 12, type: 'select', eventName: 'change', options:[], multiple: true, collapseTags: true}
          }
        }];
      },
      // 资源组
      fnResMonitorGroup(){
        getResMonitorGroup().then(res => {
          if (res && res.data) {
            this.formList[0].controls['resourceGroupId']['options']= res && res.data.map(item => {
              this.resourceGroupIdList[item.id] = item;
              return Object.assign({label: item.groupName, value: item.id});
            });
          }
        });
      },
      getResNameList() {
        resNameList().then(val => {
          if (val) {
            this.formList[0].controls['includedDevicesDataList']['options']= val && val.map(item => {
              this.includedDevicesList[item.id] = item;
              return Object.assign({label: item.id + '_' + item.resourceName, value: item.id});
            });
          }
        }).catch(() => {
          this.$modal.msgError("操作失败")
        });
      },
      // 获取详情
      getFormDataList(id) {
        getPolicy(id).then(val => {
          if (val && val.data) {
            let firstForm = {};
            Object.keys(this.formList[0].controls).forEach(item => {
              firstForm[item] = val.data[item];
            });
            firstForm.includedDevicesDataList = val.data && val.data.includedDevicesId && val.data.includedDevicesId.split(',').map(id => Number(id));
            firstForm['resourceGroupName'] = firstForm && firstForm.resourceGroupId ? this.resourceGroupIdList[val.data.resourceGroupId].groupName : '';
            val.data['resourceGroupName'] = firstForm && firstForm.resourceGroupId ? this.resourceGroupIdList[val.data.resourceGroupId].groupName : '';
            this.ruleFormData = {...firstForm};
            // 第二节点
            val.data['sources'] = [];
            val.data['commands'] = [];
            val.data.executionMethod = val.data.executionMethod.toString();
            val.data.commandContent = val.data && val.data.commandContent.split(',');
            val.data.sourceFilePath = val.data && val.data.sourceFilePath.split(',');
            if (val.data.commandContent && val.data.commandContent.length > 0) {
              val.data.commandContent.forEach(item => {
                val.data['commands'].push({commandContent: item});
              });
            }
            if (val.data.sourceFilePath && val.data.sourceFilePath.length > 0) {
              val.data.sourceFilePath.forEach(item => {
                val.data['sources'].push({sourceFilePathType: '1', sourceFilePath: item});
              });
            }
            this.ruleFormDataTow = val.data;
          }
        }).catch(() => {
          // this.$modal.msgError("操作失败")
        });
      },
      async next(num) {
        // console.log('num==',num, 'active==',this.active);
        if (num === '-1') {
          this.active--;
        } else {
          if (this.active === 0) {
            if (!await this.fnFormValid()) {
              return;
            }
          }
          if (this.active === 1) {
            this.formDataTow();
          }
          this.active++;
        }
      },
      // form验证
      fnFormValid() {
        return new Promise((resolve) => {
          this.ruleFormData = {};
          const formValid = this.$refs.formRef.$refs.ruleForm;
          // 3. 操作form（如验证）
          formValid.validate((valid) => {
            if (valid) {
              // 资源组
              formValid.model.resourceGroupName = formValid.model && formValid.model.resourceGroupId ? this.resourceGroupIdList[formValid.model.resourceGroupId].groupName: '';
              // 包含设备
              formValid.model['includedDevicesName'] = [];
              if (formValid.model && formValid.model.includedDevicesDataList && formValid.model.includedDevicesDataList.length > 0) {
                formValid.model.includedDevicesDataList.forEach(item => {
                  if (this.includedDevicesList[item]) {
                    formValid.model['includedDevicesName'].push(this.includedDevicesList[item].resourceName);
                  }
                });
              }
              formValid.model['includedDevicesId'] = formValid.model['includedDevicesDataList'].join();
              formValid.model['includedDevicesName'] = formValid.model['includedDevicesName'].join();
              this.ruleFormData = formValid.model;
              resolve(true);
            } else {
              resolve(false);
            }
          });
        });
      },
      // 第二节点下的form值
      formDataTow() {
        let newFormVal = {commandContent: [], sourceFilePath: [], sourceFilePathType: []};
        this.$refs.dyncForm.submitForm().then(formData => {
          this.ruleFormDataTow = Object.assign({}, formData, this.ruleFormData);
          if (formData && formData.commands && formData.commands.length > 0) {
            formData.commands.forEach(item => {
              newFormVal['commandContent'].push(item.commandContent);
            });
          }
          if (formData && formData.sources && formData.sources.length > 0) {
            formData.sources.forEach(item => {
              newFormVal['sourceFilePath'].push(item.sourceFilePath);
              newFormVal['sourceFilePathType'].push(item.sourceFilePathType);
            });
          }
          newFormVal['sourceFilePath'] = newFormVal['sourceFilePath'].join();
          newFormVal['sourceFilePathType'] = newFormVal['sourceFilePathType'].join();
          newFormVal['commandContent'] = newFormVal['commandContent'].join();
          this.groupFormList = Object.assign({},formData, newFormVal);
          // console.log('vvvv=====',formData,'newFormVal====',this.groupFormList);
        }).catch(error => {
          // 处理验证失败的情况
          console.error('表单提交失败：', error);
        });
      },
      // 提交
      submit() {
        let params = Object.assign({}, this.groupFormList, this.ruleFormData);
        // console.log('params==',params);
        // return;
        let fnType = addPolicy;
        if (this.paramsData && this.paramsData.id) {
          fnType = updatePolicy;
        }
        this.$modal.loading();
        fnType(params).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.$router.push("/resource/serverScript");
          this.$modal.closeLoading();
        }).catch(error => {
          this.$modal.closeLoading();
        });
      },
      // 返回
      goBack() {
        this.$router.push({path:'/resource/serverScript'});
      },
      // 监听事件
      callback(result, dataVal, formVal) {
        if (result && result.fnCode) {
          switch (result.fnCode) {
            case 'resourceGroupId':
              this.ruleFormData['resourceGroupId'] = dataVal;
              this.ruleFormData['includedDevicesDataList'] = [];
              listArrRegisterList({id: dataVal}).then(res => {
                if (res && res.data) {
                  res.data.forEach(item => {
                    this.ruleFormData['includedDevicesDataList'].push(Number(item.id));
                  });
                }
              });
              break;
            case 'includedDevicesDataList':
              this.ruleFormData['resourceGroupId'] = null;
              this.ruleFormData['includedDevicesDataList'] = dataVal;
              break;
            default:
          }
        }
      }
    }
  }
</script>
<style scoped>
  ::v-deep .el-collapse-item__header {
    background-color: #d4e3fc!important;
    /*color: #fff!important;*/
    padding-left: 20px;
    font-size: 1rem;
  }
</style>
