<!-- 配置设备告警 -->
<template>
  <ns-view-list-table v-if="show" ref="mainRef" class="table" v-bind="tableConfig">
    <template #bodyCell="{ record, column }">
      <template v-if="column.dataIndex === 'enableRules'">
        <a-switch
          :checked="record.enableRules === 1 ? true : false"
          :class="{
            'blue-background': record.enableRules === 1 ? true : false,
            'grey-background': record.enableRules === 1 ? false : true,
          }"
          @click="clickSwitch({ enableRules: record.enableRules, record: record })" />
      </template>
      <template v-if="column.dataIndex === 'comparisonType'">
        {{ getcomparisonType(record) }}
      </template>
    </template>
  </ns-view-list-table>
  <!-- 新增or编辑界面 -->
  <editConfigureEnergyAlarm ref="editConfigureEnergyAlarms" @editObject="editObject" />
</template>
<script lang="ts">
  import { ref, createVNode } from 'vue';
  import { http } from '/nerv-lib/util';
  import { NsMessage, NsModal } from '/nerv-lib/component';
  import editConfigureEnergyAlarm from './editConfigureEnergyAlarm.vue';
  import { energyAlarms } from '/@/api/alarmManagement/alarmSettings/energyAlarm';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { dict } from '/@/api';

  export default {
    components: { editConfigureEnergyAlarm },

    setup() {
      //能源告警配置
      const configureEnergyAlarmsData = ref({});
      const show = ref(false);
      const tableConfig = ref({});
      const mainRef = ref({});
      const editConfigureEnergyAlarms = ref({});
      //组织树
      const orgId = ref('');
      const result = JSON.parse(sessionStorage.getItem('ORGID')!);
      orgId.value = result;
      //获取对比类型
      const getcomparisonType = (data: any) => {
        let datas = data.comparisonType.split(',');
        if (datas[0] === '1') {
          switch (datas[1]) {
            case '1':
              return '数值>输入数值';
            case '2':
              return '数值>同比';
            case '3':
              return '数值>环比';
            case '4':
              return '数值>对比基准';
          }
        } else {
          switch (datas[1]) {
            case '1':
              return '比例>输入比例';
            case '2':
              return '比例>同比';
            case '3':
              return '比例>环比';
            case '4':
              return '比例>对比基准';
          }
        }
      };
      const clickSwitch = (data: any) => {
        NsModal.confirm({
          title: '启用状态',
          icon: createVNode(ExclamationCircleOutlined),
          content: '确定' + (data.record.enableRules === 1 ? '关闭' : '启用') + '规则吗?',
          onOk: () => {
            http
              .post(energyAlarms.configAddOrUpNewData, {
                id: data.record.id,
                enableRules: data.record.enableRules === 1 ? 0 : 1,
              })
              .then(() => {
                NsMessage.success(data.record.enableRules === 1 ? '规则已关闭' : '规则已启用');
                mainRef.value?.nsTableRef.reload();
              });
          },
        });
      };
      const doWnload = (url: any) => {
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.href = encodeURI(url);
        //设置下载的文件名
        // a.download = fileName.value;
        //触发a标签的点击事件，进行下载
        a.click();
      };
      const setconfigureDeviceAlarmsData = (value: any) => {
        configureEnergyAlarmsData.value = value;
        show.value = true;
        tableConfig.value = {
          title: '告警规则',
          api: energyAlarms.configGetTableList,
          headerActions: [
            {
              label: '新增',
              name: 'configureEnergyAlarmAdd',
              type: 'primary',
              handle: () => {
                editConfigureEnergyAlarms.value.toggle(null, configureEnergyAlarmsData.value);
              },
            },
            {
              label: '导入',
              name: 'configureEnergyAlarmImport',
              type: 'primary',
              extra: {
                // api: props.postImportApi, // 导入接口名
                title: '设备信息', // 弹窗title
                templateName: 'whiteListUser', // 所使用的文件名称
                indexName: '设备id', // 匹配类型字段
                message: [
                  { label: '1、若必填项未填写，则不能进行导入操作' },
                  { label: `2、当重复时，则更新数据。` },
                  { label: '3、数据将从模版的第五行进行导入。' },
                  { label: '4、文件导入勿超过5MB。' },
                ],
              },
            },
            {
              label: '导出',
              name: 'configureEnergyAlarmExports',
              type: 'primary',
              handle: () => {
                doWnload('/hx-ai-intelligent/asset/file/whiteListUser.xlsx');
              },
            },
            {
              label: '批量删除',
              type: 'primary',
              name: 'configureEnergyAlarmDels',
              confirm: true,
              dynamicDisabled: (data: any) => {
                return data.list.length === 0;
              },
              handle: (data: any) => {
                let ids = [];
                data.list.forEach((item) => {
                  ids.push(item.id);
                });
                data.list = [];
                http.post(energyAlarms.configDel, { ids: ids.toString() }).then(() => {
                  NsMessage.success('告警规则删除成功');
                  //清空选中
                  mainRef.value.nsTableRef.clearCheck();
                  //刷新表单
                  mainRef.value?.nsTableRef.reload();
                });
              },
            },
          ],
          columns: [
            {
              title: '序号',
              dataIndex: 'address',
              customRender: (text: any) => {
                return text.index + 1;
              },
            },
            {
              title: '规则id',
              dataIndex: 'ruleId',
            },
            {
              title: '设备信息/节点信息',
              dataIndex: 'deviceInfo',
            },
            {
              title: '对比类型',
              dataIndex: 'comparisonType',
            },
            {
              title: '告警点位',
              dataIndex: 'devicePointName',
            },
            {
              title: '判断条件',
              dataIndex: 'conditionalJudgment',
            },
            {
              title: '异常描述',
              dataIndex: 'abnormalDescription',
              textEllipsis: true,
            },
            {
              title: '启用状态',
              dataIndex: 'enableRules',
            },
          ],
          // rowSelection: null, 选择按钮
          columnActions: {
            title: '操作',
            actions: [
              {
                label: '编辑',
                name: 'configureEnergyAlarmEdit',
                dynamicParams: ['uuid', 'appealType'],
                handle: (data: any) => {
                  editConfigureEnergyAlarms.value.toggle(data, configureEnergyAlarmsData.value);
                },
              },
              {
                label: '删除',
                name: 'configureEnergyAlarmDel',
                dynamicParams: ['uuid', 'appealType'],
                confirm: true,
                handle: (data: any) => {
                  http.post(energyAlarms.configDel, { ids: data.id }).then(() => {
                    NsMessage.success('告警规则删除成功');
                    //刷新表单
                    mainRef.value?.nsTableRef.reload();
                  });
                },
              },
            ],
          },
          formConfig: {
            title: value.errorCode,
            schemas: [
              {
                field: 'deviceName',
                label: '设备信息/节点信息',
                component: 'NsInput',
                componentProps: {
                  allowClear: true,
                  placeholder: '请输入设备信息/节点信息关键字',
                },
              },
              {
                field: 'dataSourcesType',
                label: '告警点位',
                component: 'nsSelectApi',
                // dynamicParams: {
                //   id: 'deviceName', //帮定上级联动数据
                // },
                componentProps: {
                  api: () => dict({ params: { dicKey: 'ENERGY_TYPE' } }),
                  immediate: true,
                  allowClear: true,
                  labelField: 'cnValue',
                  valueField: 'id',
                  placeholder: '请选择告警点位',
                  showSearch: true,
                  filterOption: (input: string, option: any) => {
                    return option.cnValue.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                  },
                  // autoSelectFirst: true,
                },
              },
              {
                field: 'enableRules',
                label: '启用状态',
                component: 'NsSelect',
                componentProps: {
                  allowClear: true,
                  placeholder: '请选择启用状态',
                  options: [
                    {
                      label: '启用',
                      value: 1,
                    },
                    {
                      label: '关闭',
                      value: 0,
                    },
                  ],
                },
              },
              {
                field: 'abnormalDescription',
                label: '异常描述',
                component: 'NsInput',
                componentProps: {
                  allowClear: true,
                  placeholder: '请输入异常描述关键字',
                },
              },
            ],
          },
          params: { energyConsumptionAlarmId: value.id, orgId: orgId.value },
          // pagination: { pageSizeOptions: false },
          rowKey: 'id',
        };
      };
      // 编辑或添加成功 刷新列表
      const editObject = () => {
        mainRef.value?.nsTableRef.reload();
      };
      return {
        configureEnergyAlarmsData,
        show,
        clickSwitch,
        doWnload,
        mainRef,
        editObject,
        getcomparisonType,
        orgId,
        tableConfig,
        editConfigureEnergyAlarms,
        setconfigureDeviceAlarmsData,
      };
    },
  };
</script>
<style lang="less" scoped>
  .blue-background.ant-switch-checked {
    background-color: linear-gradient(
      180deg,
      rgba(1, 206, 255, 1) 0%,
      rgba(0, 150, 229, 1) 100%
    ) !important;
  }

  .grey-background.ant-switch {
    background-color: grey !important;
  }

  .blue-background.ant-switch-checked .ant-switch-handle {
    background-color: linear-gradient(
      180deg,
      rgba(1, 206, 255, 1) 0%,
      rgba(0, 150, 229, 1) 100%
    ) !important;
  }

  .grey-background.ant-switch .ant-switch-handle {
    background-color: grey !important;
  }
</style>
../../../../api/alarmManagement/alarmSettings/energyAlarm
