<!-- 配置设备告警 -->
<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 === 'valueType'">
        {{ record.valueType.label }}
      </template>
    </template>
  </ns-view-list-table>
  <!-- 新增or编辑界面 -->
  <editConfigureDeviceAlarm ref="editConfigureDeviceAlarms" @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 editConfigureDeviceAlarm from '../equipmentAlarm/editConfigureDeviceAlarm.vue';
  import { deviceAlarms } from '/@/api/alarmManagement/alarmSettings/deviceAlarms';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { device } from '/@/api/deviceManage';

  export default {
    components: { editConfigureDeviceAlarm },

    setup() {
      //设备告警数据
      const configureDeviceAlarmsData = ref({});
      const show = ref(false);
      const tableConfig = ref({});
      const mainRef = ref({});
      const editConfigureDeviceAlarms = ref({});
      //组织数
      const orgId = ref('');
      const result = JSON.parse(sessionStorage.getItem('ORGID')!);
      orgId.value = result;
      // 改变状态
      const clickSwitch = (data: any) => {
        NsModal.confirm({
          title: '启用状态',
          icon: createVNode(ExclamationCircleOutlined),
          content: '确定' + (data.record.enableRules === 1 ? '关闭' : '启用') + '规则吗?',
          onOk: () => {
            http
              .post(deviceAlarms.configAddOrUpNewData, {
                id: data.record.id,
                enableRules: data.record.enableRules === 1 ? 0 : 1,
              })
              .then(() => {
                NsMessage.success(data.record.enableRules === 1 ? '规则已关闭' : '规则已启用');
                mainRef.value?.nsTableRef.reload();
              });
          },
        });
      };
      // 编辑或添加成功 刷新列表
      const editObject = () => {
        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) => {
        configureDeviceAlarmsData.value = value;
        show.value = true;
        tableConfig.value = {
          title: '告警规则',
          api: deviceAlarms.configGetTableList,
          headerActions: [
            {
              label: '新增',
              name: 'configureEquipmentAlarmAdd',
              type: 'primary',
              handle: () => {
                editConfigureDeviceAlarms.value.toggle(null, configureDeviceAlarmsData.value);
              },
            },
            {
              label: '导入',
              name: 'configureEquipmentAlarmImport',
              type: 'primary',
              extra: {
                // api: props.postImportApi, // 导入接口名
                title: '设备信息', // 弹窗title
                templateName: 'whiteListUser', // 所使用的文件名称
                indexName: '设备id', // 匹配类型字段
                message: [
                  { label: '1、若必填项未填写，则不能进行导入操作' },
                  { label: `2、当重复时，则更新数据。` },
                  { label: '3、数据将从模版的第五行进行导入。' },
                  { label: '4、文件导入勿超过5MB。' },
                ],
              },
            },
            {
              label: '导出',
              name: 'configureEquipmentAlarmExports',
              type: 'primary',
              handle: () => {
                doWnload('/hx-ai-intelligent/asset/file/whiteListUser.xlsx');
              },
            },
            {
              label: '批量删除',
              name: 'configureEquipmentAlarmDels',
              type: 'primary',
              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(deviceAlarms.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: 'devicePointName',
            },
            {
              title: '判断条件',
              dataIndex: 'conditionalJudgment',
            },
            {
              title: '取值类型',
              dataIndex: 'valueType',
            },
            {
              title: '异常描述',
              dataIndex: 'abnormalDescription',
            },
            {
              title: '启用状态',
              dataIndex: 'enableRules',
            },
          ],
          // rowSelection: null, 选择按钮
          columnActions: {
            title: '操作',
            actions: [
              {
                label: '编辑',
                name: 'configureEquipmentAlarmEdit',
                dynamicParams: ['uuid', 'appealType'],
                handle: (data: any) => {
                  editConfigureDeviceAlarms.value.toggle(data, configureDeviceAlarmsData);
                },
              },
              {
                label: '删除',
                name: 'configureEquipmentAlarmDel',
                dynamicParams: ['uuid', 'appealType'],
                confirm: true,
                handle: (data: any) => {
                  http.post(deviceAlarms.configDel, { ids: data.id }).then(() => {
                    NsMessage.success('告警规则删除成功');
                    mainRef.value?.nsTableRef.reload();
                  });
                },
              },
            ],
          },
          formConfig: {
            title: value.errorCode,
            schemas: [
              {
                field: 'deviceInfoCode',
                label: '设备名称',
                component: 'nsSelectApi',
                componentProps: {
                  api: device.queryDevicePage,
                  allowClear: true,
                  params: {
                    orgId: orgId.value,
                    pageNum: 1,
                    pageSize: 99,
                  },
                  placeholder: '请选择设备名称',
                  resultField: 'data.records',
                  labelField: 'deviceName',
                  valueField: 'deviceInfoCode',
                  showSearch: true,
                  filterOption: (input: string, option: any) => {
                    return option.deviceName.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                  },
                  autoAddLink: true, //默认添加联动
                },
              },
              {
                field: 'devicePoint',
                label: '设备点位',
                component: 'nsSelectApi',
                dynamicParams: {
                  deviceCode: 'deviceInfoCode', //帮定上级联动数据
                },
                componentProps: {
                  api: device.queryDevicePoint,
                  allowClear: true,
                  resultField: 'data',
                  placeholder: '请选择设备点位',
                  labelField: 'code',
                  valueField: 'id',
                  dependency: 'deviceInfoCode',
                  showSearch: true,
                  filterOption: (input: string, option: any) => {
                    return option.code.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                  },
                },
              },
              {
                field: 'enableRules',
                label: '启用状态',
                component: 'NsSelect',
                componentProps: {
                  placeholder: '请选择启用状态',
                  allowClear: true,
                  options: [
                    {
                      label: '启用',
                      value: 1,
                    },
                    {
                      label: '关闭',
                      value: 0,
                    },
                  ],
                },
              },
              {
                field: 'abnormalDescription',
                label: '异常描述',
                component: 'NsInput',

                componentProps: {
                  allowClear: true,
                  placeholder: '请输入异常描述关键字',
                },
              },
            ],
          },
          params: { equipmentAlarmId: value.id, orgId: orgId.value },
          // pagination: { pageSizeOptions: false },
          rowKey: 'id',
        };
      };
      return {
        configureDeviceAlarmsData,
        show,
        clickSwitch,
        doWnload,
        tableConfig,
        orgId,
        mainRef,
        editObject,
        editConfigureDeviceAlarms,
        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/deviceAlarms
