<template>
  <div class="procedure-map">
    <div class="option-area">
      <label style="color: var(--vent-font-color)">设备类型：</label>
      <Select
        @change="handleChange"
        :options="deviceKindOption"
        :fieldNames="{ label: 'label', value: 'value' }"
        v-model:value="deviceKind"
        style="width: 200px; color: black"
        placeholder="请选择设备类型"
        :allowClear="true"
      />
      <a-button type="primary" preIcon="ant-design:search-outlined" style="margin: 0 15px" @click="getSearch">查询</a-button>
      <a-button preIcon="ant-design:sync-outlined" @click="onReset" style="margin-right: 15px">重置</a-button>
      <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleAdd">新增</a-button>
      <a-button type="primary" @click="handleLink" style="margin-left: 15px">自动关联</a-button>
    </div>
    <a-table size="small" :dataSource="dataSource" :columns="columnsMap" :scroll="{ y: 620 }" :pagination="pagination" @change="pageChange">
      <template #action="{ record }">
        <a class="table-action-link" @click="handleEdit(record)">编辑</a>
        <!-- <a class="table-action-link" @click="handleDel(record)">删除</a> -->
        <a-popconfirm title="确定删除?" @confirm="handleDel(record)">
          <a class="table-action-link">删除</a>
        </a-popconfirm>
      </template>
    </a-table>
    <!-- 添加/编辑弹窗 -->
    <a-modal v-model:visible="visibleMap" width="1000px" :footer="null" :title="titleMap" centered destroyOnClose>
      <proceduresModal :isToggle="isToggle" :formState="formState" @close="handleClose" />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { Select, message } from 'ant-design-vue';
  import { ref, reactive, onMounted } from 'vue';
  import { BasicColumn } from '/@/components/Table';
  import { getDictItemsByCode } from '/@/utils/dict';
  import { deleteById, getList, autoLinkReg } from './internalManager.api';
  // import { columnsMap } from './internalManager.data';
  import proceduresModal from './procedures-modal.vue';

  const dataSource = ref<any[]>([]);
  const deviceKind = ref<string>('');
  const deviceKindOption = ref([]);
  const regTypeOption = ref([]);
  //分页参数配置
  const pagination = reactive({
    current: 1, // 当前页码
    pageSize: 10, // 每页显示条数
    total: 0, // 总条目数，后端返回
    // showTotal: (total, range) => `${range[0]}-${range[1]} 条，总共 ${total} 条`, // 分页右下角显示信息
    showSizeChanger: true, // 是否可改变每页显示条数
    pageSizeOptions: ['10', '20', '50'], // 可选的每页显示条数
  });
  const visibleMap = ref(false);
  const titleMap = ref('');
  const isToggle = ref('');
  const formState = reactive({
    id: '',
    regName: '',
    regType: '',
    deviceKind: '',
    dataId: '',
    monitorDataName: '',
    regRoute: '',
  });
  const columnsMap: BasicColumn[] = [
    {
      title: '序号',
      width: 60,
      align: 'center',
      customRender: ({ index }: { index: number }) => `${index + 1}`,
    },
    {
      title: '规程名称',
      dataIndex: 'regName',
      align: 'center',
    },
    {
      title: '规程类型',
      dataIndex: 'regType',
      align: 'center',
      // 新增：通过规程类型字典映射中文
      customRender: ({ text }) => {
        // 从规程类型字典中找到匹配的中文label
        const matchItem = regTypeOption.value.find((item) => item.value === text);
        return matchItem ? matchItem.label : text; // 未匹配到则显示原字段
      },
    },
    {
      title: '设备种类',
      dataIndex: 'deviceKind',
      align: 'center',
      // 新增：通过设备种类字典映射中文
      customRender: ({ text }) => {
        // 从设备种类字典中找到匹配的中文label
        const matchItem = deviceKindOption.value.find((item) => item.value === text);
        return matchItem ? matchItem.label : text; // 未匹配到则显示原字段
      },
    },
    {
      title: '关联监测数据名称',
      dataIndex: 'monitorDataName',
      align: 'center',
    },
    {
      title: '规则路由',
      dataIndex: 'regRoute',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 200,
      align: 'center',
      slots: { customRender: 'action' },
    },
  ];
  //关闭弹窗
  function handleClose() {
    visibleMap.value = false;
    getListMap();
  }
  //添加
  function handleAdd() {
    titleMap.value = '新增规程关联表';
    visibleMap.value = true;
    isToggle.value = 'add';
    Object.assign(formState, {
      id: '',
      regName: '',
      regType: '',
      deviceKind: '',
      dataId: '',
      monitorDataName: '',
      regRoute: '',
    });
  }
  //编辑
  function handleEdit(record) {
    titleMap.value = '编辑规程关联表';
    visibleMap.value = true;
    isToggle.value = 'edit';

    Object.assign(formState, {
      id: record.id,
      regName: record.regName,
      regType: record.regType,
      deviceKind: record.deviceKind,
      dataId: record.dataId,
      monitorDataName: record.monitorDataName,
      regRoute: record.regRoute,
    });
  }
  //删除
  async function handleDel(record) {
    await deleteById({ id: record.id });
    pagination.current = 1;
    getListMap();
  }

  //分页切换
  function pageChange(val) {
    pagination.current = val.current;
    pagination.pageSize = val.pageSize;
    getListMap();
  }

  //获取数据列表
  async function getListMap() {
    let res = await getList({ deviceKind: deviceKind.value, pageNo: pagination.current, pageSize: pagination.pageSize });
    if (res.records && res.records.length != 0) {
      dataSource.value = res.records;
      pagination.total = res.total;
    } else {
      dataSource.value = res.records;
    }
  }
  //查询
  function getSearch() {
    pagination.current = 1;
    getListMap();
  }
  //重置
  function onReset() {
    pagination.current = 1;
    getListMap();
  }
  // 设备类型切换
  function handleChange(type) {
    deviceKind.value = type;
    getListMap();
  }

  function handleLink() {
    if (deviceKind.value) {
      autoLinkReg({ Devicetype: deviceKind.value });
      console.log('自动关联设备类型：', deviceKind.value);
    } else {
      message.error('请选择设备类型进行自动关联');
      return;
    }
  }
  onMounted(() => {
    const deviceKindRes = getDictItemsByCode('devicekind');
    deviceKindOption.value = deviceKindRes;
    console.log('deviceKindOption', deviceKindOption.value);
    const regTypeRes = getDictItemsByCode('regType');
    regTypeOption.value = regTypeRes;
    console.log('regTypeOption', regTypeOption.value);
    getListMap();
  });
</script>

<style lang="less" scoped>
  @import '/@/design/theme.less';

  .procedure-map {
    position: relative;
    width: 100%;
    height: 100%;
    padding: 10px;
    box-sizing: border-box;

    .option-area {
      display: flex;
      height: 60px;
      align-items: center;
    }
  }

  :deep(.zxm-select-selector) {
    width: 100%;
    border: 1px solid var(--vent-form-item-border) !important;
    background-color: #ffffff00 !important;
  }

  :deep(.zxm-select-selection-item) {
    color: #fff !important;
  }
</style>
