<template>
  <ns-drawer
    v-model:visible="visible"
    width="600"
    :title="'设置通知联系人'"
    :ok="btnClick"
    :cancel="handleClose"
    placement="right"
    :footer-style="{ textAlign: 'right' }"
    @close="handleClose">
    <div style="width: 100%; overflow: hidden; overflow-y: hidden; height: 100%">
      <a-form ref="formRef" :model="infoObject" :rules="rules" style="width: 80%">
        <a-form-item ref="notificationMethod" label="通知方式" name="notificationMethod">
          <a-select
            ref="select"
            v-model:value="infoObject.notificationMethod"
            style="width: 100%"
            mode="multiple"
            :options="devicePointData"
            show-search
            :allowClear="true"
            placeholder="请选择通知方式"
            :field-names="{ label: 'cnValue', value: 'dicKey', options: 'children' }"
            :filter-option="filterDevicePoint" />
        </a-form-item>
        <a-form-item label="启用规则">
          <a-switch
            :checked="infoObject.enableNotifications === 1 ? true : false"
            :class="{
              'blue-background': infoObject.enableNotifications === 1 ? true : false,
              'grey-background': infoObject.enableNotifications === 1 ? false : true,
            }"
            @click="clickSwitch" />
        </a-form-item>
      </a-form>
      <div style="width: 100%; height: 765px; overflow-y: auto">
        <div style="margin-bottom: 8px">
          <div style="width: 100%; display: flex; position: relative" class="ns-title-extra-box">
            <span style="margin-left: 12px; color: #333333">联系人名单</span>
          </div>
          <img
            style="width: 100%; margin-top: -10px"
            src="https://files.axshare.com/gsc/4T0UQR/7e/5d/a2/7e5da2a277344db8af30521cefeb70cc/images/告警设置/u150.svg?pageId=1f58c1ba-b461-4fe8-a2b3-295f1e7b0aa0" />
        </div>
        <div style="margin-bottom: 16px">
          <a-button type="primary" @click="chengUser">选择联系人 </a-button>
        </div>
        <a-table
          :dataSource="dataSource"
          :columns="columns"
          :scroll="{ x: 800, y: 700 }"
          :pagination="pagination">
          <template #bodyCell="{ record, column }">
            <template v-if="column.dataIndex === 'address'">
              {{ record?.deptRoleInfoList || record.userRoleInfos?.[0].deptRoleInfoList }}
            </template>
            <template v-if="column.dataIndex === 'operation'">
              <a style="color: #2778ff" @click="remove(record)">移除</a>
            </template>
          </template>
        </a-table>
      </div>
    </div>
    <linkPeople
      v-show="visibleModel"
      ref="linkPeoples"
      @handleCancel="handleCancel"
      @handleOk="handleOk" />
  </ns-drawer>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { NsMessage } from '/nerv-lib/component';
  import { http } from '/nerv-lib/util';
  import linkPeople from './linkPeople/index.vue';
  import { notificationManagementApi } from '/@/api/alarmManagement/alarmSettings/notificationManagements';
  import { dict } from '/@/api';

  //table 数据
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 80,
      fixed: 'left',
      customRender: (text: any) => {
        return text.index + 1;
      },
    },
    {
      title: '姓名',
      dataIndex: 'realName',
      width: 80,
      fixed: 'left',
      key: 'deviceName',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      width: 80,
      key: 'sex',
    },
    {
      title: '组织关系',
      dataIndex: 'orgName',
      key: 'site',
    },
    {
      title: '部门',
      dataIndex: 'address',
      key: 'address',
      width: 200,
      textEllipsis: true,
    },
    {
      title: '操作',
      width: 80,
      dataIndex: 'operation',
      fixed: 'right',
    },
  ];
  const visibleModel = ref(false);
  const dataSource = ref([]);
  const visible = ref(false);
  const linkPeoples = ref(null);
  const handleChangePage = (current: number, pageSize: number) => {
    pagination.value.current = current;
    pagination.value.pageSize = pageSize;
  };
  const pagination = ref({
    total: 0,
    size: 'small',
    current: 1,
    pageSize: 10,
    showQuickJumper: true,
    showLessItems: true,
    // showSizeChanger: true, //分页改变大小
    showTotal: (total: number, range: any) =>
      total && range ? `显示第${range[0]}到${range[1]}条记录,共 ${total} 条记录` : '',
    onChange: handleChangePage,
  });
  //点击联系人
  const chengUser = () => {
    visibleModel.value = true;
    let ids = [];
    dataSource.value.forEach((item) => {
      ids.push(item.userId);
    });
    // 传到子页面
    linkPeoples.value.getData({ id: ids, data: dataSource.value });
  };
  //取消弹窗
  const handleCancel = () => {
    visibleModel.value = false;
  };
  //确定选择人
  const handleOk = (data: any) => {
    visibleModel.value = false;
    dataSource.value = data.data;
  };
  //表单数据
  const infoObject = ref({
    enableNotifications: 0,
  });
  //设备点位搜索
  const filterDevicePoint = (input: string, option: any) => {
    return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };
  //开关
  const clickSwitch = () => {
    if (infoObject.value.enableNotifications === 1) {
      infoObject.value.enableNotifications = 0;
    } else {
      infoObject.value.enableNotifications = 1;
    }
  };
  // 通知信息
  const devicePointData = ref([]);

  const rules = {
    notificationMethod: [{ required: true, message: '请选择通知方式', trigger: 'change' }],
    user: [{ required: true, message: '请选择通知人', trigger: 'change' }],
  };
  const formRef = ref();
  const emit = defineEmits(['updNotification']);
  const toggle = async (value: any) => {
    // NOTIFICATIONMETHOD
    let devicePoint = await dict({ params: { dicKey: 'NOTIFICATIONMETHOD' } });
    devicePointData.value = devicePoint.data.data;
    //判断 是新增 还是修改
    if (value) {
      // // 获取接口
      await http
        .post(notificationManagementApi.findById, {
          id: value.id,
        })
        .then((res) => {
          infoObject.value = res.data;
          //处理通知方式
          if (infoObject.value.notificationMethod) {
            infoObject.value.notificationMethod = infoObject.value.notificationMethod.split(',');
          } else {
            infoObject.value.notificationMethod = [];
          }
          //处理通知人
          dataSource.value = res.data.hxAlarmNotifyUserList;
        });
    } else {
      dataSource.value = [];
      infoObject.value = {
        enableNotifications: 0,
        notificationMethod: [],
      };
      dataSource.value = [];
    }
    visible.value = !visible.value;
  };
  //移除数据
  const remove = (data: any) => {
    dataSource.value.forEach((item, index) => {
      if (item.userId === data.userId) {
        dataSource.value.splice(index, 1);
      }
    });
    dataSource.value = [...dataSource.value];
  };
  const btnClick = () => {
    if (dataSource.value.length === 0) {
      NsMessage.warn('请选择联系人');
      return;
    }
    //表单校验
    formRef.value.validate().then(() => {
      //发送请求数据
      let obj = {
        id: null,
        notificationMethod: null,
        hxAlarmNotifyUserList: [],
        enableNotifications: 0,
        orgId: null,
      };
      obj.notificationMethod = infoObject.value.notificationMethod.toString();
      obj.id = infoObject.value.id;
      obj.enableNotifications = infoObject.value.enableNotifications;
      obj.orgId = infoObject.value.orgId;
      //处理 选择人数据
      dataSource.value.forEach((item) => {
        obj.hxAlarmNotifyUserList.push({
          userId: item.userId,
          contactInformationId: infoObject.value.id,
        });
      });
      //调用接口
      http.post(notificationManagementApi.upData, obj).then((res) => {
        if (res.msg === 'success') {
          NsMessage.success('操作成功');
          visible.value = false;
          dataSource.value = [];
          emit('updNotification', null);
        }
      });
    });
  };
  const handleClose = () => {
    // 清楚校验错误信息
    formRef.value.resetFields();
    visible.value = false;
    visibleModel.value = false;
    dataSource.value = [];
  };
  defineExpose({
    toggle,
    handleClose,
    handleCancel,
    handleChangePage,
    formRef,
  });
</script>
<style scoped lang="less">
  .drawerContainer {
    height: 100%;
    display: flex;
    justify-content: space-between;
  }
  .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;
  }
  :deep(.ant-form-item-label) {
    z-index: 20;
    text-align: left;
    width: 20%;
  }
</style>
../../../../api/alarmManagement/alarmSettings/notificationManagements
