<template>
  <div class="p-4">
    <div class="btm-group vent-flex-row-between">
      <div>
        <label style="color: #fff">设备类型：</label>
        <ApiTreeSelect
          @change="handleChange"
          :api="deviceList.bind(null, { devicetype: '' })"
          :fieldNames="{ children: 'children', label: 'itemText', value: 'itemValue' }"
          v-model:value="deviceKind"
          style="width: 200px"
        />
        <a-button type="primary" @click="addRow"> 新增 </a-button>
      </div>
      <a-button class="vent-margin-l-10" type="primary" @click="handleSave()"> 批量保存 </a-button>
    </div>
    <div class="monitor-nav">
      <div class="device-button-group" v-if="relevanceDeviceData.length > 0">
        <div class="device-button" :class="{ 'device-active': deviceActive == device.type }" v-for="(device, index) in relevanceDeviceData" :key="index" @click="deviceChange(index)">{{ device.typeName }}</div>
      </div>
    </div>
    <BasicTable ref="editTable" @register="registerTable" :dataSource="dataSource" :columns="workFaceColumns" @edit-change="onEditChange" v-if="refresh">
      <template #action="{ record, column }">
        <TableAction :actions="createActions(record, column)" />
      </template>
    </BasicTable>
    <DeviceModalTable
      @register="registerModal"
      :deviceType="deviceKind"
      :deviceID="deviceId"
      @reload="getWorkFaceList"
      :selectionRowKeys="selectionRowKeys"
    />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, inject, onMounted } from 'vue';
  import { BasicTable, useTable, TableAction, BasicColumn, ActionItem, EditRecordRow } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { ApiTreeSelect } from '/@/components/Form';
  import DeviceModalTable from './DeviceModalTable.vue';
  import { deviceId, workDeviceList, deviceList, list, edit, workDeviceEdit, workRelevanceDeviceTypes, workRelevanceDeviceDelete } from './point.api';
  import { workFaceColumns, deviceColumns } from './point.data';
  type RelevanceDeviceType = {
    datalist: [],
    type: string,
    typeName: string
  }

  export default defineComponent({
    components: { BasicTable, TableAction, DeviceModalTable, ApiTreeSelect },
    props: {
      columns: {
        type: Array,
        requried: true,
      },
      deviceId: {
        type: String || Number,
        requried: true,
      },
      list: {
        type: Function,
        requried: true,
      },
      isAdd: {
        type: Boolean,
      },
    },
    emits: ['save', 'delete'],
    setup(props, { emit }) {
      const editTable = ref<any>(null);
      const activeTab = ref('1');
      const deviceKind = ref('');
      const type = inject('deviceType') || '';
      const refresh = ref(true)
      const currentEditKeyRef = ref('');
      const options = ref([]);

      const dataSource = ref<any>([]);
      const selectionRowKeys = ref<any[]>([]);

      const relevanceDeviceData = ref<RelevanceDeviceType[]>([])
      const deviceNavData = ref<any[]>([]) // 关联设备
      const deviceActive = ref('') // 激活状态下的设备

      const [registerModal, { openModal }] = useModal();

      const [registerTable, { insertTableDataRecord, reload }] = useTable({
        title: '',
        showIndexColumn: true,
        showTableSetting: false,
        tableSetting: { fullScreen: true },
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });

      async function getDeviceNavData() {
        relevanceDeviceData.value = await workRelevanceDeviceTypes({ id: props.deviceId })
        deviceChange(0)
      }

      function addRow() {
        openModal();
      }

      function handleEdit(record: EditRecordRow) {
        currentEditKeyRef.value = record.key;
        record.onEdit?.(true);
      }

      function handleCancel(record: EditRecordRow) {
        currentEditKeyRef.value = '';
        record.onEdit?.(false, false);
      }

      function handleDelete(record: EditRecordRow) {
        debugger
        emit('delete', record.id, reload);
      }
      async function getOptions() {
        const res = await deviceList({ devicetype: '' });
        options.value = res;
      }

      function getWorkFaceList() {
        deviceActive.value = deviceKind.value
        handleSuccess()
      }
      
      function deviceChange(index) {
        deviceActive.value = relevanceDeviceData.value[index].type
        dataSource.value = relevanceDeviceData.value[index].datalist
      }

      function handleChange(value, label, extra) {
        console.log('树节点选中------>',value, label, extra)
        deviceKind.value = value;
        const activeData = relevanceDeviceData.value.find(item => {
          return item.type === value
        })
        if(activeData){
          deviceActive.value = activeData.type
          dataSource.value = activeData.datalist
        }else{
          deviceActive.value = ''
          dataSource.value = []
        }
      }

      async function handleSave(record?: EditRecordRow) {
        if (record) {
          dataSource.value.filter((item) => {
            if (record.id && record.id === item.id) {
              Object.assign(item, record.editValueRefs);
            }
          });
          console.log('[ dataSource ] >', dataSource.value, record);
          // 校验
          await edit(dataSource.value);
          record.onEdit?.(false);
          refresh.value = false
        } else {
          //workDeviceEdit
          if (editTable.value && editTable?.value.getDataSource) {
            const arr: any[] = [];
            const dataList = editTable?.value.getDataSource();
            const ids = <any[]>[];
            dataList.forEach((element) => {
              arr.push(Object.assign(element, element.editValueRefs));
              ids.push(element.deviceId)
            });
            dataSource.value = dataList;
            // await workDeviceEdit({ deviceKind : deviceKind.value, ids: ids, sysid: props.deviceId }, handleSuccess)
            await edit(dataSource.value);
          }
        }
        nextTick(() => {
          refresh.value = true
          clearSelectedRowKeys()
        })
      }

      async function handleSuccess() {
        relevanceDeviceData.value = await workRelevanceDeviceTypes({ id: props.deviceId })
        handleChange(deviceActive.value)
      }

      function createActions(record: EditRecordRow, column: BasicColumn): ActionItem[] {
        if (!record.editable) {
          if (props.isAdd) {
            return [
              {
                label: '编辑',
                disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
                onClick: handleDelete.bind(null, record),
              },
            ];
          } else {
            return [
              {
                label: '编辑',
                disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                onClick: workRelevanceDeviceDelete.bind(null, { deviceid: record.deviceID, sysid: props.deviceId }, handleSuccess),
              },
            ];
          }
        }
        return [
          {
            label: '保存',
            onClick: handleSave.bind(null, record, column),
          },
          {
            label: '取消',
            popConfirm: {
              title: '是否取消编辑',
              confirm: handleCancel.bind(null, record, column),
            },
          },
        ];
      }

      function onEditChange({ column, value, record }) {
        // 本例
        if (column.dataIndex === 'devicetype') {
          // record.editValueRefs.name4.value = `${value}`;
        }
        // console.log(column, value, record);
      }

      onMounted(async () => {
        await getOptions();
        await getDeviceNavData()
        // getWorkFaceList();
      });

      return {
        editTable,
        activeTab,
        refresh,
        registerTable,
        handleEdit,
        createActions,
        onEditChange,
        addRow,
        workFaceColumns,
        deviceColumns,
        getOptions,
        options,
        deviceList,
        dataSource,
        deviceKind,
        handleChange,
        registerModal,
        handleSave,
        selectionRowKeys,
        getWorkFaceList,
        relevanceDeviceData,
        deviceNavData,
        deviceActive,
        deviceChange,
        
        // handleChangeDeviceType,
        // handleChangeLinkCode,
        // monitorParamsOptions,
      };
    },
  });
</script>
<style scoped lang="less">
  @ventSpace: zxm;

  :deep(.@{ventSpace}-table-body) {
    height: auto !important;
  }
  .btm-group {
    padding-bottom: 2px;
  }
  .device-button-group{
    // margin: 0 20px;
    display: flex;
    flex-wrap: wrap;
    pointer-events: auto;
    position: relative;
    margin-top: 10px;
    margin-bottom: 5px;
    &::after{
      position:absolute;
      content: '';
      width: calc(100% + 10px);
      height: 2px;
      top: 30px;
      left: -10px;
      border-bottom: 1px solid #0efcff;
    }
    .device-button{
      padding: 4px 10px;
      position: relative;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 14px;
      
      color: #fff;
      cursor: pointer;
      margin: 0 1px;

      &::before{
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        border: 1px solid #6176AF;
        // transform: skewX(-38deg);
        background-color: rgba(0, 77, 103,85%);
        z-index: -1;
      }
    }
    .device-active{
      // color: #0efcff;
      &::before{
        border-color: #0efcff;
        box-shadow: 1px 1px 3px 1px #0efcff inset;
      }
    }
  }
</style>
