<!-- 配置设备告警 -->
<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>
  </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/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: 'RoleTypeAdd',
              type: 'primary',
              handle: () => {
                editConfigureDeviceAlarms.value.toggle(null, configureDeviceAlarmsData.value);
              },
            },
            {
              label: '导入',
              name: 'groupImport',
              type: 'primary',
              extra: {
                // api: props.postImportApi, // 导入接口名
                title: '设备信息', // 弹窗title
                templateName: 'whiteListUser', // 所使用的文件名称
                indexName: '设备id', // 匹配类型字段
                message: [
                  { label: '1、若必填项未填写，则不能进行导入操作' },
                  { label: `2、当重复时，则更新数据。` },
                  { label: '3、数据将从模版的第五行进行导入。' },
                  { label: '4、文件导入勿超过5MB。' },
                ],
              },
            },
            {
              label: '导出',
              name: 'groupExports',
              type: 'primary',
              handle: () => {
                doWnload('/hx-ai-intelligent/asset/file/whiteListUser.xlsx');
              },
            },
            {
              label: '批量删除',
              name: 'groupTemDownload',
              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: 'FeedBackDetail',
                dynamicParams: ['uuid', 'appealType'],
                handle: (data: any) => {
                  editConfigureDeviceAlarms.value.toggle(data, configureDeviceAlarmsData);
                },
              },
              {
                label: '删除',
                name: 'FeedBackDetail',
                dynamicParams: ['uuid', 'appealType'],
                confirm: true,
                handle: () => {
                  http.post(deviceAlarms.configDel, { ids: data.id }).then(() => {
                    NsMessage.success('规则删除成功');
                    mainRef.value?.nsTableRef.reload();
                  });
                },
              },
            ],
          },
          formConfig: {
            title: value.errorCode,
            schemas: [
              {
                field: 'deviceName',
                label: '设备名称',
                component: 'nsSelectApi',
                componentProps: {
                  api: device.queryDevicePage,
                  allowClear: true,
                  params: {
                    orgId: orgId.value,
                    pageNum: 1,
                    pageSize: 99,
                  },
                  placeholder: '请选择设备点位',
                  resultField: 'data.records',
                  labelField: 'deviceName',
                  valueField: 'id',
                  autoAddLink: true, //默认添加联动
                },
              },
              {
                field: 'devicePoint',
                label: '设备点位',
                component: 'nsSelectApi',
                dynamicParams: {
                  id: 'deviceName', //帮定上级联动数据
                },
                componentProps: {
                  api: device.queryDevicePoint,
                  allowClear: true,
                  resultField: 'data',
                  placeholder: '请选择设备点位',
                  labelField: 'code',
                  valueField: 'id',
                  dependency: 'deviceName',
                },
              },
              {
                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 },
          // 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>
