<template>
  <div>
    <Form style="margin-bottom: 30px;" ref="formRef" :formList="formList" :config="{labelWidth: '140px'}" :ruleFormData="ruleFormData" @fnClick="callback">
      <template #tempGroup="{field, model, formModel}">
        <EditableMultiSelect
          v-model="groupModel"
          :multiple="false"
          :initial-options="groupList"
          @option-added="handleOptionAdded"
          @option-updated="handleOptionUpdated"
          @option-deleted="handleOptionDeleted"
          @value-change="handelValueChange"
        ></EditableMultiSelect>
      </template>
    </Form>
  </div>
</template>

<script>
  import Form from '@/components/form/index.vue';
  import EditableMultiSelect from "@/components/customModule/selectModule.vue";
  import {switchNameTree, listAllBusinessList} from "@/api/disRevenue/earnManage";
  import {addMonitorConfig, updateMonitorConfig, getMonitorGroup, addMonitorGroup, updateMonitorGroup, delMonitorGroup} from "@/api/disRevenue/resource";
  export default {
    name: "dialogMonitor",
    components: {Form, EditableMultiSelect},
    dicts: ['resource_type'],
    props: {
      formModel: {
        type: Object,
        default: () => {}
      }
    },
    watch: {
      formModel: {
        handler(val) {
          if (val && val.resourceType === '2') {
            val.deployDeviceSwitch = [];
            let newData = val && val.deployDevice ? val.deployDevice.split(',') : val.deployDevice;
            newData.forEach(item => {
              let lastVal = item.split(';');
              val.deployDeviceSwitch.push([Number(lastVal[lastVal.length - 1]), item]);
            });
            this.includeDataList();
          } else if (val && val.resourceType === '3') {
            this.businessList();
          }
          this.$refs.formRef.$refs.ruleForm.resetFields();
          this.ruleFormData = JSON.parse(JSON.stringify(val));
          this.groupModel = this.ruleFormData && this.ruleFormData['groupId'] || '';
          this.fnFormList();
          this.groupListData();
        }
      },
      deep: true,
      immediate: true
    },
    data() {
      return {
        groupList: [
          { label: '', value: '' },
        ],
        ruleFormData: {},
        formList: [],
        busNameList: {},
        switchNameList: {},
        groupModel: '',
      }
    },
    created() {
    },
    methods: {
      // 查询分组
      groupListData(type, targetVal) {
        getMonitorGroup().then(res => {
          if (res && res.data && res.data.length > 0) {
            this.groupList = res && res.data.map(item => {
              return Object.assign({}, item, {value: item.id, label: item.name})
            });
            if (type === 'del') {
              // 从选中值中移除
              const selectedIndex = this.groupModel.toString().indexOf(targetVal.toString());
              if (selectedIndex !== -1) {
                this.groupModel = ' ';
              }
            }
          } else {
            this.groupList = [{label: '', value: ''}];
          }
        });
      },
      // 新增
      handleOptionAdded(option) {
        addMonitorGroup({name: option.label}).then(res => {
          this.$message.success(`添加成功！`);
          this.groupListData();
        });
      },
      // 编辑
      handleOptionUpdated(data) {
        updateMonitorGroup({id: data.oldValue, name: data.newValue}).then(res => {
          this.$message.success(`更新成功！`);
          this.groupListData();
        });
      },
      // 删除
      handleOptionDeleted(value) {
        delMonitorGroup(value).then(res => {
          this.$message.info(`删除成功！`);
          this.groupListData('del', value);
        });
      },
      // 值变化时
      handelValueChange(value) {
        this.$set(this.ruleFormData, 'groupId', value);
      },
      // formList集合
      fnFormList() {
        this.formList = [{
          config: {colSpan: 'disBlock'},
          controls: {
            id: {label: 'ID',hidden: true},
            groupId: {label: '分组', span: 18, slotName: 'tempGroup', required: true},
            configName: {label: '配置名称', span: 18, type: 'input', required: true},
            monitorStartTime: {label: '监控数据开始时间', span: 18, type: 'datetime', disabled: this.ruleFormData && this.ruleFormData.id ? true : false, required: true},
            resourceType: {label: '资源类型', span: 18, type: 'select', eventName: 'change', required: true, options: this.dict.type.resource_type, disabled: this.ruleFormData && this.ruleFormData.id ? true : false},
            deployDevice: {label: '包含资源', span: 18, type: 'textarea', rows: 10, required: true, hidden: this.ruleFormData.resourceType && this.ruleFormData.resourceType === '1' ? false : true},
            deployDeviceSwitch: {label: '包含资源', span: 18, type: 'cascader', options: [], hidden: this.ruleFormData.resourceType && this.ruleFormData.resourceType === '2' ? false : true},
            businessName: {label: '包含业务', span: 18, type: 'select', options: [], disabled: this.ruleFormData && this.ruleFormData.id ? true : false, hidden: this.ruleFormData.resourceType && this.ruleFormData.resourceType === '3' ? false : true},
          }
        }];
      },
      // 包含资源
      includeDataList(num) {
        this.$modal.loading();
        // if (this.switchNameList && Object.keys(this.switchNameList).length <= 0) {
          switchNameTree().then(val => {
            this.switchNameList = val && val;
            this.formList[0].controls.deployDeviceSwitch['options'] = val && val.data;
            this.$modal.closeLoading();
          }).catch(() => {
            this.$modal.closeLoading();
          });
        // }
      },
      // 业务名称
      businessList() {
        // if (this.busNameList && Object.keys(this.busNameList).length <= 0) {
          listAllBusinessList().then(val => {
            this.formList[0].controls.businessName['options'] = val && val.data.map(item => {
              this.busNameList[item.businessName] = item;
              return Object.assign({label: item.businessName, value: item.businessName});
            });
          });
        // }
      },
      // 监听事件
      callback(result, dataVal, formVal) {
        if (result && result.fnCode) {
          switch (result.fnCode) {
            case 'resourceType':
              if (dataVal) {
                if (dataVal === '1') {
                  this.formList[0].controls.deployDevice['hidden'] = false;
                  this.formList[0].controls.deployDeviceSwitch['hidden'] = true;
                  this.formList[0].controls.businessName['hidden'] = true;
                } else if (dataVal === '2') {
                  this.formList[0].controls.deployDevice['hidden'] = true;
                  this.formList[0].controls.deployDeviceSwitch['hidden'] = false;
                  this.formList[0].controls.businessName['hidden'] = true;
                  this.includeDataList();
                } else if (dataVal === '3') {
                  this.formList[0].controls.deployDevice['hidden'] = true;
                  this.formList[0].controls.deployDeviceSwitch['hidden'] = true;
                  this.formList[0].controls.businessName['hidden'] = false;
                  this.businessList();
                }
              } else {
                this.formList[0].controls.deployDevice['hidden'] = true;
                this.formList[0].controls.deployDeviceSwitch['hidden'] = true;
                this.formList[0].controls.businessName['hidden'] = true;
              }
              break;
            case 'submit':
              if (dataVal && dataVal['businessName']) {
                dataVal['businessCode'] = this.busNameList[dataVal['businessName']].id;
              }
              if (dataVal.deployDeviceSwitch) {
                let newArr = [];
                dataVal.deployDeviceSwitch.forEach(item => {
                  newArr.push(item[1]);
                });
                dataVal.deployDevice = newArr.toString();
                delete dataVal.deployDeviceSwitch;
              }
              let fnName = addMonitorConfig;
              if (dataVal && dataVal.id) {
                fnName = updateMonitorConfig;
              }
              fnName(dataVal).then(res => {
                this.$emit("dialogResult", {open: false, type: 'submit'});
              });
              break;
            case 'cancel':
              this.$emit("dialogResult", {open: false});
              break;
            default:
          }
        }
      }
    }
  }
</script>

<style scoped>

</style>
